SPR-8215 Move HandlerMethod code into trunk

This commit is contained in:
Rossen Stoyanchev
2011-04-06 11:30:59 +00:00
parent 0f7d43ba90
commit acc75aa4b8
86 changed files with 11635 additions and 13 deletions

View File

@@ -0,0 +1,126 @@
/*
* 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.method.annotation;
import static java.util.Arrays.asList;
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 java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.DefaultSessionAttributeStore;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.SessionAttributesHandler;
/**
* Test fixture for {@link SessionAttributesHandler} unit tests.
*
* @author Rossen Stoyanchev
*/
public class HandlerSessionAttributeStoreTests {
private DefaultSessionAttributeStore sessionAttributes;
private SessionAttributesHandler handlerSessionAttributes;
private Class<?> handlerType = SessionAttributeHandler.class;
private NativeWebRequest request;
@Before
public void setUp() {
this.sessionAttributes = new DefaultSessionAttributeStore();
this.handlerSessionAttributes = new SessionAttributesHandler(handlerType, sessionAttributes);
this.request = new ServletWebRequest(new MockHttpServletRequest());
}
@Test
public void isSessionAttribute() throws Exception {
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr1", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr2", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("simple", TestBean.class));
assertFalse("Attribute name not known", handlerSessionAttributes.isHandlerSessionAttribute("simple", null));
}
@Test
public void retrieveAttributes() throws Exception {
sessionAttributes.storeAttribute(request, "attr1", "value1");
sessionAttributes.storeAttribute(request, "attr2", "value2");
sessionAttributes.storeAttribute(request, "attr3", new TestBean());
// Query attributes to associate them with the handler type
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr1", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr3", TestBean.class));
Map<String, ?> attributes = handlerSessionAttributes.retrieveHandlerSessionAttributes(request);
assertEquals(new HashSet<String>(asList("attr1", "attr3")), attributes.keySet());
}
@Test
public void cleanupAttribute() throws Exception {
sessionAttributes.storeAttribute(request, "attr1", "value1");
sessionAttributes.storeAttribute(request, "attr2", "value2");
sessionAttributes.storeAttribute(request, "attr3", new TestBean());
// Query attribute to associate it with the handler type
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr1", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr3", TestBean.class));
handlerSessionAttributes.cleanupHandlerSessionAttributes(request);
assertNull(sessionAttributes.retrieveAttribute(request, "attr1"));
assertNotNull(sessionAttributes.retrieveAttribute(request, "attr2"));
assertNull(sessionAttributes.retrieveAttribute(request, "attr3"));
}
@Test
public void storeAttributes() throws Exception {
Map<String, Object> attributes = new HashMap<String, Object>();
attributes.put("attr1", "value1");
attributes.put("attr2", "value2");
attributes.put("attr3", new TestBean());
// Query attribute to associate it with the handler type
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr1", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr2", null));
assertTrue(handlerSessionAttributes.isHandlerSessionAttribute("attr3", TestBean.class));
handlerSessionAttributes.storeHandlerSessionAttributes(request, attributes);
assertEquals("value1", sessionAttributes.retrieveAttribute(request, "attr1"));
assertEquals("value2", sessionAttributes.retrieveAttribute(request, "attr2"));
assertTrue(sessionAttributes.retrieveAttribute(request, "attr3") instanceof TestBean);
}
@SessionAttributes(value = { "attr1", "attr2" }, types = { TestBean.class })
private static class SessionAttributeHandler {
}
}

View File

@@ -0,0 +1,168 @@
/*
* 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.method.annotation;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.convert.ConversionService;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.ConfigurableWebBindingInitializer;
import org.springframework.web.bind.support.DefaultDataBinderFactory;
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.annotation.support.RequestParamMethodArgumentResolver;
import org.springframework.web.method.support.InvocableHandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolverContainer;
/**
* Test fixture for {@link InitBinderMethodDataBinderFactory} unit tests.
*
* @author Rossen Stoyanchev
*/
public class InitBinderMethodDataBinderFactoryTests {
private MockHttpServletRequest request;
private NativeWebRequest webRequest;
private ConfigurableWebBindingInitializer bindingInitializer;
@Before
public void setUp() throws Exception {
this.request = new MockHttpServletRequest();
this.webRequest = new ServletWebRequest(request);
this.bindingInitializer = new ConfigurableWebBindingInitializer();
}
@Test
public void createBinder() throws Exception {
InitBinderMethodDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
WebDataBinder dataBinder = factory.createBinder(webRequest, null, null);
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
@Test
public void createBinderWithGlobalInitialization() throws Exception {
ConversionService conversionService = new DefaultFormattingConversionService();
bindingInitializer.setConversionService(conversionService );
InitBinderMethodDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
WebDataBinder dataBinder = factory.createBinder(webRequest, null, null);
assertSame(conversionService, dataBinder.getConversionService());
}
@Test
public void createBinderWithAttrName() throws Exception {
InitBinderMethodDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
WebDataBinder dataBinder = factory.createBinder(webRequest, null, "foo");
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
@Test
public void createBinderWithAttrNameNoMatch() throws Exception {
WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
WebDataBinder dataBinder = factory.createBinder(webRequest, null, "invalidName");
assertNull(dataBinder.getDisallowedFields());
}
@Test(expected=IllegalStateException.class)
public void returnValueNotExpected() throws Exception {
WebDataBinderFactory factory = createFactory("initBinderReturnValue", WebDataBinder.class);
factory.createBinder(webRequest, null, "invalidName");
}
@Test
public void createBinderTypeConversion() throws Exception {
request.setParameter("requestParam", "22");
HandlerMethodArgumentResolverContainer argResolvers = new HandlerMethodArgumentResolverContainer();
argResolvers.registerArgumentResolver(new RequestParamMethodArgumentResolver(null, false));
String methodName = "initBinderTypeConversion";
WebDataBinderFactory factory = createFactory(argResolvers, methodName, WebDataBinder.class, int.class);
WebDataBinder dataBinder = factory.createBinder(webRequest, null, "foo");
assertNotNull(dataBinder.getDisallowedFields());
assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]);
}
private InitBinderMethodDataBinderFactory createFactory(String methodName, Class<?>... parameterTypes)
throws Exception {
return createFactory(new HandlerMethodArgumentResolverContainer(), methodName, parameterTypes);
}
private InitBinderMethodDataBinderFactory createFactory(HandlerMethodArgumentResolverContainer argResolvers,
String methodName, Class<?>... parameterTypes) throws Exception {
Object handler = new InitBinderHandler();
Method method = InitBinderHandler.class.getMethod(methodName, parameterTypes);
InvocableHandlerMethod controllerMethod = new InvocableHandlerMethod(handler, method);
controllerMethod.setArgumentResolverContainer(argResolvers);
controllerMethod.setDataBinderFactory(new DefaultDataBinderFactory(null));
controllerMethod.setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());
return new InitBinderMethodDataBinderFactory(Arrays.asList(controllerMethod), bindingInitializer);
}
private static class InitBinderHandler {
@SuppressWarnings("unused")
@InitBinder
public void initBinder(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@SuppressWarnings("unused")
@InitBinder(value="foo")
public void initBinderWithAttributeName(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}
@SuppressWarnings("unused")
@InitBinder
public String initBinderReturnValue(WebDataBinder dataBinder) {
return "invalid";
}
@SuppressWarnings("unused")
@InitBinder
public void initBinderTypeConversion(WebDataBinder dataBinder, @RequestParam int requestParam) {
dataBinder.setDisallowedFields("requestParam-" + requestParam);
}
}
}

View File

@@ -0,0 +1,199 @@
/*
* 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.method.annotation;
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.assertSame;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.DefaultSessionAttributeStore;
import org.springframework.web.bind.support.SessionAttributeStore;
import org.springframework.web.bind.support.SimpleSessionStatus;
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.annotation.support.ModelMethodProcessor;
import org.springframework.web.method.support.HandlerMethodArgumentResolverContainer;
import org.springframework.web.method.support.InvocableHandlerMethod;
/**
* Text fixture for {@link ModelFactory} unit tests.
*
* @author Rossen Stoyanchev
*/
public class ModelFactoryTests {
private NativeWebRequest webRequest;
private SessionAttributeStore sessionAttributeStore;
private SessionAttributesHandler handlerSessionAttributeStore;
private InvocableHandlerMethod requestMethod;
@Before
public void setUp() throws Exception {
Object handler = new ModelHandler();
Method method = handler.getClass().getDeclaredMethod("handle");
this.requestMethod = new InvocableHandlerMethod(handler, method);
this.sessionAttributeStore = new DefaultSessionAttributeStore();
this.handlerSessionAttributeStore = new SessionAttributesHandler(handler.getClass(), sessionAttributeStore);
this.webRequest = new ServletWebRequest(new MockHttpServletRequest());
}
@Test
public void createModel() throws Exception {
ModelMap model = createFactory(new ModelHandler(), "model", Model.class).createModel(webRequest, requestMethod);
assertEquals(Boolean.TRUE, model.get("model"));
}
@Test
public void createModelWithName() throws Exception {
ModelMap model = createFactory(new ModelHandler(), "modelWithName").createModel(webRequest, requestMethod);
assertEquals(Boolean.TRUE, model.get("name"));
}
@Test
public void createModelWithDefaultName() throws Exception {
ModelMap model = createFactory(new ModelHandler(), "modelWithDefaultName").createModel(webRequest, requestMethod);
assertEquals(Boolean.TRUE, model.get("boolean"));
}
@Test
public void createModelWithExistingName() throws Exception {
ModelMap model = createFactory(new ModelHandler(), "modelWithName").createModel(webRequest, requestMethod);
assertEquals(Boolean.TRUE, model.get("name"));
}
@Test
public void createModelWithNullAttribute() throws Exception {
ModelMap model = createFactory(new ModelHandler(), "modelWithNullAttribute").createModel(webRequest, requestMethod);
assertTrue(model.containsKey("name"));
assertNull(model.get("name"));
}
@Test
public void createModelExistingSessionAttributes() throws Exception {
sessionAttributeStore.storeAttribute(webRequest, "sessionAttr", "sessionAttrValue");
// Query attribute to associate it with the handler type
assertTrue(handlerSessionAttributeStore.isHandlerSessionAttribute("sessionAttr", null));
ModelMap model = createFactory(new ModelHandler(), "model", Model.class).createModel(webRequest, requestMethod);
assertEquals("sessionAttrValue", model.get("sessionAttr"));
}
@Test
public void updateBindingResult() throws Exception {
Object handler = new ModelHandler();
SessionAttributeStore store = new DefaultSessionAttributeStore();
SessionAttributesHandler sessionAttributeStore = new SessionAttributesHandler(handler.getClass(), store);
String attrName = "attr1";
Object attrValue = new Object();
ModelMap actualModel = new ExtendedModelMap();
actualModel.addAttribute(attrName, attrValue);
WebDataBinder dataBinder = new WebDataBinder(attrValue, attrName);
WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
expect(binderFactory.createBinder(webRequest, attrValue, attrName)).andReturn(dataBinder);
replay(binderFactory);
ModelFactory modelFactory = new ModelFactory(null, binderFactory, sessionAttributeStore);
modelFactory.updateAttributes(webRequest, new SimpleSessionStatus(), actualModel, null);
assertEquals(attrValue, actualModel.remove(attrName));
assertSame(dataBinder.getBindingResult(), actualModel.remove(bindingResultKey(attrName)));
assertEquals(0, actualModel.size());
verify(binderFactory);
}
private String bindingResultKey(String key) {
return BindingResult.MODEL_KEY_PREFIX + key;
}
private ModelFactory createFactory(Object handler, String methodName, Class<?>... parameterTypes) throws Exception{
Method method = ModelHandler.class.getMethod(methodName, parameterTypes);
HandlerMethodArgumentResolverContainer argResolvers = new HandlerMethodArgumentResolverContainer();
argResolvers.registerArgumentResolver(new ModelMethodProcessor());
InvocableHandlerMethod controllerMethod = new InvocableHandlerMethod(handler, method);
controllerMethod.setArgumentResolverContainer(argResolvers);
controllerMethod.setDataBinderFactory(null);
controllerMethod.setParameterNameDiscoverer(new LocalVariableTableParameterNameDiscoverer());
return new ModelFactory(Arrays.asList(controllerMethod), null, handlerSessionAttributeStore);
}
@SessionAttributes("sessionAttr")
private static class ModelHandler {
@SuppressWarnings("unused")
@ModelAttribute
public void model(Model model) {
model.addAttribute("model", Boolean.TRUE);
}
@SuppressWarnings("unused")
@ModelAttribute("name")
public Boolean modelWithName() {
return Boolean.TRUE;
}
@SuppressWarnings("unused")
@ModelAttribute
public Boolean modelWithDefaultName() {
return Boolean.TRUE;
}
@SuppressWarnings("unused")
@ModelAttribute("name")
public Boolean modelWithNullAttribute() {
return null;
}
@SuppressWarnings("unused")
public void handle() {
}
}
}

View File

@@ -0,0 +1,125 @@
/*
* 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.method.annotation.support;
import static org.junit.Assert.assertSame;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.support.ErrorsMethodArgumentResolver;
/**
* Test fixture for {@link ErrorsMethodArgumentResolver} unit tests.
*
* @author Rossen Stoyanchev
*/
public class ErrorsMethodHandlerArgumentResolverTests {
private NativeWebRequest webRequest;
private ErrorsMethodArgumentResolver resolver;
private MethodParameter errorsParam;
@Before
public void setUp() throws Exception {
this.webRequest = new ServletWebRequest(new MockHttpServletRequest());
this.resolver = new ErrorsMethodArgumentResolver();
Method method = this.getClass().getDeclaredMethod("handle", Errors.class);
this.errorsParam = new MethodParameter(method, 0);
}
@Test
public void supports() throws Exception {
resolver.supportsParameter(errorsParam);
}
@Test
public void bindingResult() throws Exception {
WebDataBinder dataBinder = new WebDataBinder(new Object(), "attr");
BindingResult bindingResult = dataBinder.getBindingResult();
ModelMap model = new ExtendedModelMap();
model.addAttribute("ignore1", "value1");
model.addAttribute("ignore2", "value2");
model.addAttribute("ignore3", "value3");
model.addAttribute("ignore4", "value4");
model.addAttribute("ignore5", "value5");
model.addAllAttributes(bindingResult.getModel()); // Predictable iteration order of model keys important!
Object actual = resolver.resolveArgument(errorsParam, model, webRequest, null);
assertSame(actual, bindingResult);
}
@Test
public void bindingResultExistingModelAttribute() throws Exception {
Object target1 = new Object();
WebDataBinder binder1 = new WebDataBinder(target1, "attr1");
BindingResult bindingResult1 = binder1.getBindingResult();
Object target2 = new Object();
WebDataBinder binder2 = new WebDataBinder(target1, "attr2");
BindingResult bindingResult2 = binder2.getBindingResult();
ModelMap model = new ExtendedModelMap();
model.addAttribute("attr1", target1);
model.addAttribute("attr2", target2);
model.addAttribute("filler", "fillerValue");
model.addAllAttributes(bindingResult1.getModel());
model.addAllAttributes(bindingResult2.getModel());
Object actual = resolver.resolveArgument(errorsParam, model, webRequest, null);
assertSame("Should resolve to the latest BindingResult added", actual, bindingResult2);
}
@Test(expected=IllegalStateException.class)
public void bindingResultNotFound() throws Exception {
WebDataBinder dataBinder = new WebDataBinder(new Object(), "attr");
BindingResult bindingResult = dataBinder.getBindingResult();
ModelMap model = new ExtendedModelMap();
model.addAllAttributes(bindingResult.getModel());
model.addAttribute("ignore1", "value1");
resolver.resolveArgument(errorsParam, model, webRequest, null);
}
@Test(expected=IllegalStateException.class)
public void noBindingResult() throws Exception {
resolver.resolveArgument(errorsParam, new ExtendedModelMap(), webRequest, null);
}
@SuppressWarnings("unused")
private void handle(Errors errors) {
}
}

View File

@@ -0,0 +1,110 @@
/*
* 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.method.annotation.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.method.annotation.support.ExpressionValueMethodArgumentResolver;
/**
* Test fixture for {@link ExpressionValueMethodArgumentResolver} unit tests.
*
* @author Rossen Stoyanchev
*/
public class ExpressionValueMethodArgumentResolverTests {
private ExpressionValueMethodArgumentResolver resolver;
private MethodParameter systemParameter;
private MethodParameter requestParameter;
private MethodParameter unsupported;
private MockHttpServletRequest servletRequest;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.refresh();
resolver = new ExpressionValueMethodArgumentResolver(context.getBeanFactory());
Method method = getClass().getMethod("params", int.class, String.class, String.class);
systemParameter = new MethodParameter(method, 0);
requestParameter = new MethodParameter(method, 1);
unsupported = new MethodParameter(method, 2);
servletRequest = new MockHttpServletRequest();
webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());
// Expose request to the current thread (for SpEL expressions)
RequestContextHolder.setRequestAttributes(webRequest);
}
@After
public void teardown() {
RequestContextHolder.resetRequestAttributes();
}
@Test
public void supportsParameter() throws Exception {
assertTrue(resolver.supportsParameter(systemParameter));
assertTrue(resolver.supportsParameter(requestParameter));
assertFalse(resolver.supportsParameter(unsupported));
}
@Test
public void resolveSystemProperty() throws Exception {
System.setProperty("systemIntValue", "22");
Object value = resolver.resolveArgument(systemParameter, null, webRequest, null);
assertEquals("22", value);
}
@Test
public void resolveRequestProperty() throws Exception {
servletRequest.setContextPath("/contextPath");
Object value = resolver.resolveArgument(requestParameter, null, webRequest, null);
assertEquals("/contextPath", value);
}
public void params(@Value("#{systemProperties.systemIntValue}") int param1,
@Value("#{request.contextPath}") String param2,
String unsupported) {
}
}

View File

@@ -0,0 +1,275 @@
/*
* 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.method.annotation.support;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.notNull;
import static org.easymock.EasyMock.replay;
import static org.easymock.EasyMock.verify;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.TestBean;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.bind.support.WebRequestDataBinder;
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.method.support.ModelAndViewContainer;
/**
* Test fixture for {@link ModelAttributeMethodProcessor} unit tests.
*
* @author Rossen Stoyanchev
*/
public class ModelAttributeMethodProcessorTests {
private ModelAttributeMethodProcessor processor;
private MethodParameter annotatedParam;
private MethodParameter integerParam;
private MethodParameter defaultNameParam;
private MethodParameter notAnnotatedParam;
private MethodParameter annotatedReturnParam;
private MethodParameter notAnnotatedReturnParam;
private ModelMap model;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
this.processor = new ModelAttributeMethodProcessor(true);
Class<?> handlerType = ModelAttributeHandler.class;
Method method = handlerType.getDeclaredMethod("modelAttribute", TestBean.class, Errors.class, int.class,
TestBean.class, TestBean.class);
this.annotatedParam = new MethodParameter(method, 0);
this.integerParam = new MethodParameter(method, 2);
this.defaultNameParam = new MethodParameter(method, 3);
this.notAnnotatedParam = new MethodParameter(method, 4);
this.annotatedReturnParam = new MethodParameter(getClass().getDeclaredMethod("annotatedReturnValue"), -1);
this.notAnnotatedReturnParam = new MethodParameter(getClass().getDeclaredMethod("notAnnotatedReturnValue"), -1);
model = new ExtendedModelMap();
this.webRequest = new ServletWebRequest(new MockHttpServletRequest());
}
@Test
public void supportParameter() throws Exception {
assertTrue(processor.supportsParameter(annotatedParam));
assertFalse(processor.supportsParameter(integerParam));
assertTrue(processor.supportsParameter(notAnnotatedParam));
this.processor = new ModelAttributeMethodProcessor(false);
assertFalse(processor.supportsParameter(notAnnotatedParam));
}
@Test
public void supportsReturnType() throws Exception {
assertTrue(processor.supportsReturnType(annotatedReturnParam));
assertFalse(processor.supportsReturnType(notAnnotatedReturnParam));
}
@Test
public void shouldValidate() throws Exception {
assertTrue(processor.shouldValidate(annotatedParam));
assertFalse(processor.shouldValidate(notAnnotatedParam));
}
@Test
public void failOnError() throws Exception {
assertFalse(processor.failOnError(annotatedParam));
assertTrue(processor.failOnError(notAnnotatedParam));
}
@Test
public void createBinderFromModelAttribute() throws Exception {
createBinderFromModelAttr("attrName", annotatedParam);
createBinderFromModelAttr("testBean", defaultNameParam);
createBinderFromModelAttr("testBean", notAnnotatedParam);
}
private void createBinderFromModelAttr(String expectedAttrName, MethodParameter param) throws Exception {
Object target = new TestBean();
model.addAttribute(expectedAttrName, target);
WebDataBinder dataBinder = new WebRequestDataBinder(null);
WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
expect(binderFactory.createBinder(webRequest, target, expectedAttrName)).andReturn(dataBinder);
replay(binderFactory);
processor.resolveArgument(param, model, webRequest, binderFactory);
verify(binderFactory);
}
@Test
public void createBinderWithAttributeConstructor() throws Exception {
WebDataBinder dataBinder = new WebRequestDataBinder(null);
WebDataBinderFactory factory = createMock(WebDataBinderFactory.class);
expect(factory.createBinder((NativeWebRequest) anyObject(), notNull(), eq("attrName"))).andReturn(dataBinder);
replay(factory);
processor.resolveArgument(annotatedParam, model, webRequest, factory);
verify(factory);
}
@Test
public void bindAndValidate() throws Exception {
Object target = new TestBean();
model.addAttribute("attrName", target);
StubRequestDataBinder dataBinder = new StubRequestDataBinder(target);
WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
expect(binderFactory.createBinder(webRequest, target, "attrName")).andReturn(dataBinder);
replay(binderFactory);
processor.resolveArgument(annotatedParam, model, webRequest, binderFactory);
assertTrue(dataBinder.isBindInvoked());
assertTrue(dataBinder.isValidateInvoked());
}
@Test(expected=BindException.class)
public void bindAndFail() throws Exception {
Object target = new TestBean();
model.addAttribute(target);
StubRequestDataBinder dataBinder = new StubRequestDataBinder(target);
dataBinder.getBindingResult().reject("error");
WebDataBinderFactory binderFactory = createMock(WebDataBinderFactory.class);
expect(binderFactory.createBinder(webRequest, target, "testBean")).andReturn(dataBinder);
replay(binderFactory);
processor.resolveArgument(notAnnotatedParam, model, webRequest, binderFactory);
}
@SuppressWarnings("rawtypes")
@Test
public void handleAnnotatedReturnValue() throws Exception {
ModelAndViewContainer<?> mavContainer = new ModelAndViewContainer(model);
processor.handleReturnValue("expected", annotatedReturnParam, mavContainer, webRequest);
assertEquals("expected", mavContainer.getModel().get("modelAttrName"));
}
@SuppressWarnings("rawtypes")
@Test
public void handleNotAnnotatedReturnValue() throws Exception {
TestBean testBean = new TestBean("expected");
ModelAndViewContainer<?> mavContainer = new ModelAndViewContainer(model);
processor.handleReturnValue(testBean, notAnnotatedReturnParam, mavContainer, webRequest);
assertSame(testBean, mavContainer.getModel().get("testBean"));
}
@SessionAttributes(types=TestBean.class)
private static class ModelAttributeHandler {
@SuppressWarnings("unused")
public void modelAttribute(@ModelAttribute("attrName") @Valid TestBean annotatedAttr,
Errors errors,
int intArg,
@ModelAttribute TestBean defaultNameAttr,
TestBean notAnnotatedAttr) {
}
}
@SuppressWarnings("unused")
@ModelAttribute("modelAttrName")
private String annotatedReturnValue() {
return null;
}
@SuppressWarnings("unused")
private TestBean notAnnotatedReturnValue() {
return null;
}
private static class StubRequestDataBinder extends WebRequestDataBinder {
private boolean bindInvoked;
private boolean validateInvoked;
public StubRequestDataBinder(Object target) {
super(target);
}
public boolean isBindInvoked() {
return bindInvoked;
}
public boolean isValidateInvoked() {
return validateInvoked;
}
@Override
public void bind(WebRequest request) {
this.bindInvoked = true;
}
@Override
public void validate() {
this.validateInvoked = true;
}
}
@Target({ METHOD, FIELD, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface Valid {
}
}

View File

@@ -0,0 +1,131 @@
/*
* 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.method.annotation.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
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.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;
/**
* Test fixture for {@link ModelMethodProcessor} unit tests.
*
* @author Rossen Stoyanchev
*/
public class ModelMethodProcessorTests {
private ModelMethodProcessor resolver;
private MethodParameter modelParameter;
private MethodParameter modelReturnType;
private MethodParameter mapParameter;
private MethodParameter mapReturnType;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
this.resolver = new ModelMethodProcessor();
Method modelMethod = getClass().getDeclaredMethod("model", Model.class);
this.modelParameter = new MethodParameter(modelMethod, 0);
this.modelReturnType = new MethodParameter(modelMethod, -1);
Method mapMethod = getClass().getDeclaredMethod("map", Map.class);
this.mapParameter = new MethodParameter(mapMethod, 0);
this.mapReturnType = new MethodParameter(mapMethod, 0);
this.webRequest = new ServletWebRequest(new MockHttpServletRequest());
}
@Test
public void usesResponseArgument() {
assertFalse(resolver.usesResponseArgument(null));
}
@Test
public void supportsParameter() {
assertTrue(resolver.supportsParameter(modelParameter));
assertTrue(resolver.supportsParameter(mapParameter));
}
@Test
public void supportsReturnType() {
assertTrue(resolver.supportsReturnType(modelReturnType));
assertTrue(resolver.supportsReturnType(mapReturnType));
}
@Test
public void resolveArgumentValue() throws Exception {
ExtendedModelMap model = new ExtendedModelMap();
Object result = resolver.resolveArgument(modelParameter, model, webRequest, null);
assertSame(model, result);
result = resolver.resolveArgument(mapParameter, model, webRequest, null);
assertSame(model, result);
}
@SuppressWarnings("rawtypes")
@Test
public void handleReturnValue() throws Exception {
ExtendedModelMap implicitModel = new ExtendedModelMap();
implicitModel.put("attr1", "value1");
ExtendedModelMap returnValue = new ExtendedModelMap();
returnValue.put("attr2", "value2");
ModelAndViewContainer<?> mavContainer = new ModelAndViewContainer(implicitModel);
resolver.handleReturnValue(returnValue , modelReturnType, mavContainer, webRequest);
ModelMap actualModel = mavContainer.getModel();
assertEquals("value1", actualModel.get("attr1"));
assertEquals("value2", actualModel.get("attr2"));
mavContainer = new ModelAndViewContainer(implicitModel);
resolver.handleReturnValue(returnValue , mapReturnType, mavContainer, webRequest);
actualModel = mavContainer.getModel();
assertEquals("value1", actualModel.get("attr1"));
assertEquals("value2", actualModel.get("attr2"));
}
@SuppressWarnings("unused")
private Model model(Model model) {
return null;
}
@SuppressWarnings("unused")
private Map<String, Object> map(Map<String, Object> map) {
return null;
}
}

View File

@@ -0,0 +1,140 @@
/*
* 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.method.annotation.support;
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.Collections;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
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.RequestHeader;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.support.RequestHeaderMapMethodArgumentResolver;
/**
* @author Arjen Poutsma
*/
public class RequestHeaderMapMethodArgumentResolverTests {
private RequestHeaderMapMethodArgumentResolver resolver;
private MethodParameter mapParameter;
private MethodParameter multiValueMapParameter;
private MethodParameter httpHeadersParameter;
private MockHttpServletRequest servletRequest;
private MethodParameter unsupportedParameter;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
resolver = new RequestHeaderMapMethodArgumentResolver();
Method method = getClass()
.getMethod("params", Map.class, MultiValueMap.class, HttpHeaders.class, Map.class);
mapParameter = new MethodParameter(method, 0);
multiValueMapParameter = new MethodParameter(method, 1);
httpHeadersParameter = new MethodParameter(method, 2);
unsupportedParameter = new MethodParameter(method, 3);
servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void usesResponseArgument() throws NoSuchMethodException {
assertFalse("resolver uses response argument", resolver.usesResponseArgument(null));
}
@Test
public void supportsParameter() {
assertTrue("Map parameter not supported", resolver.supportsParameter(mapParameter));
assertTrue("MultiValueMap parameter not supported", resolver.supportsParameter(multiValueMapParameter));
assertTrue("HttpHeaders parameter not supported", resolver.supportsParameter(httpHeadersParameter));
assertFalse("non-@RequestParam map supported", resolver.supportsParameter(unsupportedParameter));
}
@Test
@SuppressWarnings("unchecked")
public void resolveMapArgument() throws Exception {
String headerName = "foo";
String headerValue = "bar";
Map<String, String> expected = Collections.singletonMap(headerName, headerValue);
servletRequest.addHeader(headerName, headerValue);
Map<String, String> result = (Map<String, String>) resolver.resolveArgument(mapParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapArgument() throws Exception {
String headerName = "foo";
String headerValue1 = "bar";
String headerValue2 = "baz";
MultiValueMap<String, String> expected = new LinkedMultiValueMap<String, String>(1);
expected.add(headerName, headerValue1);
expected.add(headerName, headerValue2);
servletRequest.addHeader(headerName, headerValue1);
servletRequest.addHeader(headerName, headerValue2);
MultiValueMap<String, String> result =
(MultiValueMap<String, String>) resolver.resolveArgument(multiValueMapParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
public void resolveHttpHeadersArgument() throws Exception {
String headerName = "foo";
String headerValue1 = "bar";
String headerValue2 = "baz";
HttpHeaders expected = new HttpHeaders();
expected.add(headerName, headerValue1);
expected.add(headerName, headerValue2);
servletRequest.addHeader(headerName, headerValue1);
servletRequest.addHeader(headerName, headerValue2);
HttpHeaders result = (HttpHeaders) resolver.resolveArgument(httpHeadersParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
public void params(@RequestHeader Map<?, ?> param1,
@RequestHeader MultiValueMap<?, ?> param2,
@RequestHeader HttpHeaders param3,
Map<?,?> unsupported) {
}
}

View File

@@ -0,0 +1,151 @@
/*
* 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.method.annotation.support;
import static org.junit.Assert.assertArrayEquals;
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.Map;
import org.junit.After;
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.web.bind.annotation.RequestHeader;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.method.annotation.support.RequestHeaderMethodArgumentResolver;
/**
* @author Arjen Poutsma
* @author Rossen Stoyanchev
*/
public class RequestHeaderMethodArgumentResolverTests {
private RequestHeaderMethodArgumentResolver resolver;
private MethodParameter stringParameter;
private MethodParameter stringArrayParameter;
private MethodParameter systemPropertyParameter;
private MethodParameter contextPathParameter;
private MethodParameter otherParameter;
private MockHttpServletRequest servletRequest;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
GenericWebApplicationContext context = new GenericWebApplicationContext();
context.refresh();
resolver = new RequestHeaderMethodArgumentResolver(context.getBeanFactory());
Method method = getClass().getMethod("params", String.class, String[].class, String.class, String.class, Map.class);
stringParameter = new MethodParameter(method, 0);
stringArrayParameter = new MethodParameter(method, 1);
systemPropertyParameter = new MethodParameter(method, 2);
contextPathParameter = new MethodParameter(method, 3);
otherParameter = new MethodParameter(method, 4);
servletRequest = new MockHttpServletRequest();
webRequest = new ServletWebRequest(servletRequest, new MockHttpServletResponse());
// Expose request to the current thread (for SpEL expressions)
RequestContextHolder.setRequestAttributes(webRequest);
}
@After
public void teardown() {
RequestContextHolder.resetRequestAttributes();
}
@Test
public void usesResponseArgument() throws NoSuchMethodException {
assertFalse("resolver uses response argument", resolver.usesResponseArgument(null));
}
@Test
public void supportsParameter() {
assertTrue("String parameter not supported", resolver.supportsParameter(stringParameter));
assertTrue("String array parameter not supported", resolver.supportsParameter(stringArrayParameter));
assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(otherParameter));
}
@Test
public void resolveStringArgument() throws Exception {
String expected = "foo";
servletRequest.addHeader("name", expected);
String result = (String) resolver.resolveArgument(stringParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
public void resolveStringArrayArgument() throws Exception {
String[] expected = new String[]{"foo", "bar"};
servletRequest.addHeader("name", expected);
String[] result = (String[]) resolver.resolveArgument(stringArrayParameter, null, webRequest, null);
assertArrayEquals("Invalid result", expected, result);
}
@Test
public void resolveDefaultValue() throws Exception {
String result = (String) resolver.resolveArgument(stringParameter, null, webRequest, null);
assertEquals("Invalid result", "bar", result);
}
@Test
public void resolveDefaultValueFromSystemProperty() throws Exception {
System.setProperty("header", "bar");
String result = (String) resolver.resolveArgument(systemPropertyParameter, null, webRequest, null);
assertEquals("bar", result);
}
@Test
public void resolveDefaultValueFromRequest() throws Exception {
servletRequest.setContextPath("/bar");
String result = (String) resolver.resolveArgument(contextPathParameter, null, webRequest, null);
assertEquals("/bar", result);
}
@Test(expected = IllegalStateException.class)
public void notFound() throws Exception {
String result = (String) resolver.resolveArgument(stringArrayParameter, null, webRequest, null);
assertEquals("Invalid result", "bar", result);
}
public void params(@RequestHeader(value = "name", defaultValue = "bar") String param1,
@RequestHeader("name") String[] param2,
@RequestHeader(value = "name", defaultValue="#{systemProperties.header}") String param3,
@RequestHeader(value = "name", defaultValue="#{request.contextPath}") String param4,
@RequestHeader("name") Map<?, ?> unsupported) {
}
}

View File

@@ -0,0 +1,118 @@
/*
* 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.method.annotation.support;
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.Collections;
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.RequestParam;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.support.RequestParamMapMethodArgumentResolver;
/**
* @author Arjen Poutsma
*/
public class RequestParamMapMethodArgumentResolverTests {
private RequestParamMapMethodArgumentResolver resolver;
private MethodParameter mapParameter;
private MethodParameter multiValueMapParameter;
private MockHttpServletRequest servletRequest;
private NativeWebRequest webRequest;
private MethodParameter unsupportedParameter;
@Before
public void setUp() throws Exception {
resolver = new RequestParamMapMethodArgumentResolver();
Method method = getClass()
.getMethod("params", Map.class, MultiValueMap.class, Map.class);
mapParameter = new MethodParameter(method, 0);
multiValueMapParameter = new MethodParameter(method, 1);
unsupportedParameter = new MethodParameter(method, 2);
servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void usesResponseArgument() throws NoSuchMethodException {
assertFalse("resolver uses response argument", resolver.usesResponseArgument(null));
}
@Test
public void supportsParameter() {
assertTrue("Map parameter not supported", resolver.supportsParameter(mapParameter));
assertTrue("MultiValueMap parameter not supported", resolver.supportsParameter(multiValueMapParameter));
assertFalse("non-@RequestParam map supported", resolver.supportsParameter(unsupportedParameter));
}
@Test
@SuppressWarnings("unchecked")
public void resolveMapArgument() throws Exception {
String headerName = "foo";
String headerValue = "bar";
Map<String, String> expected = Collections.singletonMap(headerName, headerValue);
servletRequest.addParameter(headerName, headerValue);
Map<String, String> result = (Map<String, String>) resolver.resolveArgument(mapParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
@SuppressWarnings("unchecked")
public void resolveMultiValueMapArgument() throws Exception {
String headerName = "foo";
String headerValue1 = "bar";
String headerValue2 = "baz";
MultiValueMap<String, String> expected = new LinkedMultiValueMap<String, String>(1);
expected.add(headerName, headerValue1);
expected.add(headerName, headerValue2);
servletRequest.addParameter(headerName, new String[]{headerValue1, headerValue2});
MultiValueMap<String, String> result =
(MultiValueMap<String, String>) resolver.resolveArgument(multiValueMapParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
public void params(@RequestParam Map<?, ?> param1,
@RequestParam MultiValueMap<?, ?> param2,
Map<?, ?> unsupported) {
}
}

View File

@@ -0,0 +1,161 @@
/*
* 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.method.annotation.support;
import static org.junit.Assert.assertArrayEquals;
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.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.mock.web.MockMultipartFile;
import org.springframework.mock.web.MockMultipartHttpServletRequest;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.support.RequestParamMethodArgumentResolver;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Arjen Poutsma
*/
public class RequestParamMethodArgumentResolverTests {
private RequestParamMethodArgumentResolver resolver;
private MethodParameter stringParameter;
private MethodParameter stringArrayParameter;
private MethodParameter mapParameter;
private MethodParameter fileParameter;
private MethodParameter otherParameter;
private MockHttpServletRequest servletRequest;
private NativeWebRequest webRequest;
private MethodParameter plainParameter;
@Before
public void setUp() throws Exception {
resolver = new RequestParamMethodArgumentResolver(null, true);
Method method = getClass()
.getMethod("params", String.class, String[].class, Map.class, MultipartFile.class, Map.class, String.class);
stringParameter = new MethodParameter(method, 0);
stringArrayParameter = new MethodParameter(method, 1);
mapParameter = new MethodParameter(method, 2);
fileParameter = new MethodParameter(method, 3);
otherParameter = new MethodParameter(method, 4);
plainParameter = new MethodParameter(method, 5);
plainParameter.initParameterNameDiscovery(new LocalVariableTableParameterNameDiscoverer());
servletRequest = new MockHttpServletRequest();
MockHttpServletResponse servletResponse = new MockHttpServletResponse();
webRequest = new ServletWebRequest(servletRequest, servletResponse);
}
@Test
public void usesResponseArgument() throws NoSuchMethodException {
assertFalse("resolver uses response argument", resolver.usesResponseArgument(null));
}
@Test
public void supportsParameter() {
assertTrue("String parameter not supported", resolver.supportsParameter(stringParameter));
assertTrue("String array parameter not supported", resolver.supportsParameter(stringArrayParameter));
assertTrue("Named map not parameter supported", resolver.supportsParameter(mapParameter));
assertTrue("MultipartFile parameter not supported", resolver.supportsParameter(fileParameter));
assertFalse("non-@RequestParam parameter supported", resolver.supportsParameter(otherParameter));
assertTrue("Simple type params supported w/o annotations", resolver.supportsParameter(plainParameter));
resolver = new RequestParamMethodArgumentResolver(null, false);
assertFalse(resolver.supportsParameter(plainParameter));
}
@Test
public void resolveStringArgument() throws Exception {
String expected = "foo";
servletRequest.addParameter("name", expected);
String result = (String) resolver.resolveArgument(stringParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
public void resolveStringArrayArgument() throws Exception {
String[] expected = new String[]{"foo", "bar"};
servletRequest.addParameter("name", expected);
String[] result = (String[]) resolver.resolveArgument(stringArrayParameter, null, webRequest, null);
assertArrayEquals("Invalid result", expected, result);
}
@Test
public void resolveMultipartFileArgument() throws Exception {
MockMultipartHttpServletRequest servletRequest = new MockMultipartHttpServletRequest();
MultipartFile expected = new MockMultipartFile("file", "Hello World".getBytes());
servletRequest.addFile(expected);
webRequest = new ServletWebRequest(servletRequest);
MultipartFile result = (MultipartFile) resolver.resolveArgument(fileParameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
}
@Test
public void resolveDefaultValue() throws Exception {
String result = (String) resolver.resolveArgument(stringParameter, null, webRequest, null);
assertEquals("Invalid result", "bar", result);
}
@Test(expected = MissingServletRequestParameterException.class)
public void notFound() throws Exception {
String result = (String) resolver.resolveArgument(stringArrayParameter, null, webRequest, null);
assertEquals("Invalid result", "bar", result);
}
@Test
public void resolveSimpleTypeParam() throws Exception {
servletRequest.setParameter("plainParam", "plainValue");
String result = (String) resolver.resolveArgument(plainParameter, null, webRequest, null);
assertEquals("plainValue", result);
}
public void params(@RequestParam(value = "name", defaultValue = "bar") String param1,
@RequestParam("name") String[] param2,
@RequestParam("name") Map<?, ?> param3,
@RequestParam(value = "file") MultipartFile file,
@RequestParam Map<?, ?> unsupported,
String plainParam) {
}
}

View File

@@ -0,0 +1,165 @@
/*
* 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.method.annotation.support;
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.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.annotation.support.WebArgumentResolverAdapter;
/**
* @author Arjen Poutsma
*/
public class WebArgumentResolverAdapterTests {
private WebArgumentResolver adaptee;
private WebArgumentResolverAdapter adapter;
private MethodParameter parameter;
private NativeWebRequest webRequest;
@Before
public void setUp() throws Exception {
adaptee = createMock(WebArgumentResolver.class);
adapter = new WebArgumentResolverAdapter(adaptee);
parameter = new MethodParameter(getClass().getMethod("handle", Integer.TYPE), 0);
webRequest = new ServletWebRequest(new MockHttpServletRequest());
RequestContextHolder.setRequestAttributes(webRequest);
}
@After
public void resetRequestContextHolder() {
RequestContextHolder.resetRequestAttributes();
}
@Test
public void supportsParameter() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(42);
replay(adaptee);
boolean result = adapter.supportsParameter(parameter);
assertTrue("Parameter not supported", result);
verify(adaptee);
}
@Test
public void supportsParameterUnresolved() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(WebArgumentResolver.UNRESOLVED);
replay(adaptee);
boolean result = adapter.supportsParameter(parameter);
assertFalse("Parameter supported", result);
verify(adaptee);
}
@Test
public void supportsParameterWrongType() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn("Foo");
replay(adaptee);
boolean result = adapter.supportsParameter(parameter);
assertFalse("Parameter supported", result);
verify(adaptee);
}
@Test
public void supportsParameterThrowsException() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andThrow(new Exception());
replay(adaptee);
boolean result = adapter.supportsParameter(parameter);
assertFalse("Parameter supported", result);
verify(adaptee);
}
@Test
public void resolveArgument() throws Exception {
int expected = 42;
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(expected);
replay(adaptee);
Object result = adapter.resolveArgument(parameter, null, webRequest, null);
assertEquals("Invalid result", expected, result);
verify(adaptee);
}
@Test(expected = IllegalStateException.class)
public void resolveArgumentUnresolved() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn(WebArgumentResolver.UNRESOLVED);
replay(adaptee);
adapter.resolveArgument(parameter, null, webRequest, null);
verify(adaptee);
}
@Test(expected = IllegalStateException.class)
public void resolveArgumentWrongType() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andReturn("Foo");
replay(adaptee);
adapter.resolveArgument(parameter, null, webRequest, null);
verify(adaptee);
}
@Test(expected = Exception.class)
public void resolveArgumentThrowsException() throws Exception {
expect(adaptee.resolveArgument(parameter, webRequest)).andThrow(new Exception());
replay(adaptee);
adapter.resolveArgument(parameter, null, webRequest, null);
verify(adaptee);
}
public void handle(int param) {
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.method.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
/**
* Test fixture for {@link HandlerMethodArgumentResolverContainer} unit tests.
*
* @author Rossen Stoyanchev
*/
public class HandlerMethodArgumentResolverContainerTests {
private HandlerMethodArgumentResolverContainer container;
private MethodParameter paramInteger;
private MethodParameter paramString;
@Before
public void setUp() throws Exception {
this.container = new HandlerMethodArgumentResolverContainer();
Method method = getClass().getDeclaredMethod("handle", Integer.class, String.class);
this.paramInteger = new MethodParameter(method, 0);
this.paramString = new MethodParameter(method, 1);
}
@Test
public void supportsParameter() throws Exception {
registerResolver(Integer.class, null, false);
assertTrue(this.container.supportsParameter(paramInteger));
assertFalse(this.container.supportsParameter(paramString));
}
@Test
public void resolveArgument() throws Exception {
registerResolver(Integer.class, Integer.valueOf(55), false);
Object resolvedValue = this.container.resolveArgument(paramInteger, null, null, null);
assertEquals(Integer.valueOf(55), resolvedValue);
}
@Test
public void resolveArgumentMultipleResolvers() throws Exception {
registerResolver(Integer.class, Integer.valueOf(1), false);
registerResolver(Integer.class, Integer.valueOf(2), false);
Object resolvedValue = this.container.resolveArgument(paramInteger, null, null, null);
assertEquals("Didn't use the first registered resolver", Integer.valueOf(1), resolvedValue);
}
@Test(expected=IllegalStateException.class)
public void noSuitableArgumentResolver() throws Exception {
this.container.resolveArgument(paramString, null, null, null);
}
@Test
public void argResolverUsesResponse() throws Exception {
registerResolver(Integer.class, null, true);
assertTrue(this.container.usesResponseArgument(paramInteger));
}
@Test
public void argResolverDoesntUseResponse() throws Exception {
registerResolver(Integer.class, null, false);
assertFalse(this.container.usesResponseArgument(paramInteger));
}
protected StubArgumentResolver registerResolver(Class<?> supportedType, Object stubValue, boolean usesResponse) {
StubArgumentResolver resolver = new StubArgumentResolver(supportedType, stubValue, usesResponse);
this.container.registerArgumentResolver(resolver);
return resolver;
}
@SuppressWarnings("unused")
private void handle(Integer arg1, String arg2) {
}
}

View File

@@ -0,0 +1,113 @@
/*
* 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.method.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.MethodParameter;
/**
* Test fixture for {@link HandlerMethodReturnValueHandlerContainer} unit tests.
*
* @author Rossen Stoyanchev
*/
public class HandlerMethodReturnValueHandlerContainerTests {
private HandlerMethodReturnValueHandlerContainer container;
ModelAndViewContainer<?> mavContainer;
private MethodParameter paramInteger;
private MethodParameter paramString;
@Before
public void setUp() throws Exception {
this.container = new HandlerMethodReturnValueHandlerContainer();
this.paramInteger = new MethodParameter(getClass().getDeclaredMethod("handleInteger"), -1);
this.paramString = new MethodParameter(getClass().getDeclaredMethod("handleString"), -1);
mavContainer = new ModelAndViewContainer<Object>(null);
}
@Test
public void supportsReturnType() throws Exception {
registerReturnValueHandler(Integer.class, false);
assertTrue(this.container.supportsReturnType(paramInteger));
assertFalse(this.container.supportsReturnType(paramString));
}
@Test
public void handleReturnValue() throws Exception {
StubReturnValueHandler handler = registerReturnValueHandler(Integer.class, false);
this.container.handleReturnValue(Integer.valueOf(55), paramInteger, mavContainer, null);
assertEquals(Integer.valueOf(55), handler.getUnhandledReturnValue());
}
@Test
public void handleReturnValueMultipleHandlers() throws Exception {
StubReturnValueHandler handler1 = registerReturnValueHandler(Integer.class, false);
StubReturnValueHandler handler2 = registerReturnValueHandler(Integer.class, false);
this.container.handleReturnValue(Integer.valueOf(55), paramInteger, mavContainer, null);
assertEquals("Didn't use the 1st registered handler", Integer.valueOf(55), handler1.getUnhandledReturnValue());
assertNull("Shouldn't have use the 2nd registered handler", handler2.getUnhandledReturnValue());
}
@Test(expected=IllegalStateException.class)
public void noSuitableReturnValueHandler() throws Exception {
registerReturnValueHandler(Integer.class, false);
this.container.handleReturnValue("value", paramString, null, null);
}
@Test
public void returnValueHandlerUsesResponse() throws Exception {
registerReturnValueHandler(Integer.class, true);
assertTrue(this.container.usesResponseArgument(paramInteger));
}
@Test
public void returnValueHandlerDosntUseResponse() throws Exception {
registerReturnValueHandler(Integer.class, false);
assertFalse(this.container.usesResponseArgument(paramInteger));
}
protected StubReturnValueHandler registerReturnValueHandler(Class<?> returnType, boolean usesResponse) {
StubReturnValueHandler handler = new StubReturnValueHandler(returnType, usesResponse);
this.container.registerReturnValueHandler(handler);
return handler;
}
@SuppressWarnings("unused")
private Integer handleInteger() {
return null;
}
@SuppressWarnings("unused")
private String handleString() {
return null;
}
}

View File

@@ -0,0 +1,131 @@
/*
* 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.method.support;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.lang.reflect.Method;
import org.junit.Before;
import org.junit.Test;
import org.springframework.http.HttpStatus;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
/**
* Test fixture for {@link InvocableHandlerMethod} unit tests.
*
* @author Rossen Stoyanchev
*/
public class InvocableHandlerMethodTests {
private HandlerMethodArgumentResolverContainer argResolvers;
private NativeWebRequest webRequest;
private MockHttpServletResponse response;
@Before
public void setUp() throws Exception {
argResolvers = new HandlerMethodArgumentResolverContainer();
response = new MockHttpServletResponse();
this.webRequest = new ServletWebRequest(new MockHttpServletRequest(), response);
}
@Test
public void argResolutionAndReturnValueHandling() throws Exception {
StubArgumentResolver resolver0 = registerResolver(Integer.class, 99, false);
StubArgumentResolver resolver1 = registerResolver(String.class, "value", false);
InvocableHandlerMethod method = handlerMethod(new Handler(), "handle", Integer.class, String.class);
Object returnValue = method.invokeForRequest(webRequest, null);
assertEquals("Integer resolver not invoked", 1, resolver0.getResolvedParameterNames().size());
assertEquals("String resolver not invoked", 1, resolver1.getResolvedParameterNames().size());
assertEquals("Invalid return value", "99-value", returnValue);
}
@Test
public void providedArgResolution() throws Exception {
InvocableHandlerMethod method = handlerMethod(new Handler(), "handle", Integer.class, String.class);
Object returnValue = method.invokeForRequest(webRequest, null, 99, "value");
assertEquals("Expected raw return value with no handlers registered", String.class, returnValue.getClass());
assertEquals("Provided argument values were not resolved", "99-value", returnValue);
}
@Test
public void parameterNameDiscovery() throws Exception {
StubArgumentResolver resolver = registerResolver(Integer.class, 99, false);
InvocableHandlerMethod method = handlerMethod(new Handler(), "parameterNameDiscovery", Integer.class);
method.invokeForRequest(webRequest, null);
assertEquals("intArg", resolver.getResolvedParameterNames().get(0).getParameterName());
}
@Test
public void usesResponseArgResolver() throws Exception {
InvocableHandlerMethod requestMethod = handlerMethod(new Handler(), "usesResponse", int.class);
registerResolver(int.class, 99, true);
assertTrue(requestMethod.usesResponseArgument());
}
private InvocableHandlerMethod handlerMethod(Object handler, String methodName, Class<?>... paramTypes)
throws Exception {
Method method = handler.getClass().getDeclaredMethod(methodName, paramTypes);
InvocableHandlerMethod handlerMethod = new InvocableHandlerMethod(handler, method);
handlerMethod.setArgumentResolverContainer(argResolvers);
return handlerMethod;
}
private StubArgumentResolver registerResolver(Class<?> supportedType, Object stubValue, boolean usesResponse) {
StubArgumentResolver resolver = new StubArgumentResolver(supportedType, stubValue, usesResponse);
argResolvers.registerArgumentResolver(resolver);
return resolver;
}
private static class Handler {
@SuppressWarnings("unused")
public String handle(Integer intArg, String stringArg) {
return intArg + "-" + stringArg;
}
@SuppressWarnings("unused")
@RequestMapping
public void parameterNameDiscovery(Integer intArg) {
}
@SuppressWarnings("unused")
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "400 Bad Request")
public void responseStatus() {
}
@SuppressWarnings("unused")
public String usesResponse(int arg) {
return "";
}
}
}

View File

@@ -0,0 +1,67 @@
/*
* 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.method.support;
import java.util.ArrayList;
import java.util.List;
import org.springframework.core.MethodParameter;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
/**
* Resolves a method argument from a stub value. Records all resolved parameters.
*
* @author Rossen Stoyanchev
*/
public class StubArgumentResolver implements HandlerMethodArgumentResolver {
private final Class<?> supportedType;
private final Object stubValue;
private final boolean usesResponse;
private List<MethodParameter> resolvedParameters = new ArrayList<MethodParameter>();
public StubArgumentResolver(Class<?> supportedType, Object stubValue, boolean usesResponse) {
this.supportedType = supportedType;
this.stubValue = stubValue;
this.usesResponse = usesResponse;
}
public List<MethodParameter> getResolvedParameterNames() {
return resolvedParameters;
}
public boolean usesResponseArgument(MethodParameter parameter) {
return this.usesResponse;
}
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterType().equals(this.supportedType);
}
public Object resolveArgument(MethodParameter parameter, ModelMap model, NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
this.resolvedParameters.add(parameter);
return this.stubValue;
}
}

View File

@@ -0,0 +1,63 @@
/*
* 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.method.support;
import org.springframework.core.Conventions;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
/**
* Handles a return value by adding it as a model attribute with a default name.
* Records the raw return value (before handling).
*
* @author Rossen Stoyanchev
*/
public class StubReturnValueHandler implements HandlerMethodReturnValueHandler {
private final Class<?> supportedReturnType;
private final boolean usesResponse;
private Object unhandledReturnValue;
public StubReturnValueHandler(Class<?> supportedReturnType, boolean usesResponse) {
this.supportedReturnType = supportedReturnType;
this.usesResponse = usesResponse;
}
public Object getUnhandledReturnValue() {
return this.unhandledReturnValue;
}
public boolean supportsReturnType(MethodParameter returnType) {
return returnType.getParameterType().equals(this.supportedReturnType);
}
public <V> void handleReturnValue(Object returnValue,
MethodParameter returnType,
ModelAndViewContainer<V> mavContainer,
NativeWebRequest webRequest) throws Exception {
this.unhandledReturnValue = returnValue;
if (returnValue != null) {
mavContainer.addModelAttribute(Conventions.getVariableName(returnValue), returnValue);
}
}
public boolean usesResponseArgument(MethodParameter parameter) {
return this.usesResponse;
}
}