org.springframework.web.bind.support.WebDataBinderFactory Java Examples

The following examples show how to use org.springframework.web.bind.support.WebDataBinderFactory. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ModelAttributeMethodProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-9378
public void resolveArgumentOrdering() throws Exception {
	String name = "testBean";
	Object testBean = new TestBean(name);
	this.container.addAttribute(name, testBean);
	this.container.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, testBean);

	Object anotherTestBean = new TestBean();
	this.container.addAttribute("anotherTestBean", anotherTestBean);

	StubRequestDataBinder dataBinder = new StubRequestDataBinder(testBean, name);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.request, testBean, name)).willReturn(dataBinder);

	this.processor.resolveArgument(this.paramModelAttr, this.container, this.request, binderFactory);

	Object[] values = this.container.getModel().values().toArray();
	assertSame("Resolved attribute should be updated to be last", testBean, values[1]);
	assertSame("BindingResult of resolved attr should be last", dataBinder.getBindingResult(), values[2]);
}
 
Example #2
Source File: ServletResponseMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Set {@link ModelAndViewContainer#setRequestHandled(boolean)} to
 * {@code false} to indicate that the method signature provides access
 * to the response. If subsequently the underlying method returns
 * {@code null}, the request is considered directly handled.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	if (mavContainer != null) {
		mavContainer.setRequestHandled(true);
	}

	Class<?> paramType = parameter.getParameterType();

	// ServletResponse, HttpServletResponse
	if (ServletResponse.class.isAssignableFrom(paramType)) {
		return resolveNativeResponse(webRequest, paramType);
	}

	// ServletResponse required for all further argument types
	return resolveArgument(paramType, resolveNativeResponse(webRequest, ServletResponse.class));
}
 
Example #3
Source File: ServletModelAttributeMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Instantiate the model attribute from a URI template variable or from a
 * request parameter if the name matches to the model attribute name and
 * if there is an appropriate type conversion strategy. If none of these
 * are true delegate back to the base class.
 * @see #createAttributeFromRequestValue
 */
@Override
protected final Object createAttribute(String attributeName, MethodParameter parameter,
		WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {

	String value = getRequestValueForAttribute(attributeName, request);
	if (value != null) {
		Object attribute = createAttributeFromRequestValue(
				value, attributeName, parameter, binderFactory, request);
		if (attribute != null) {
			return attribute;
		}
	}

	return super.createAttribute(attributeName, parameter, binderFactory, request);
}
 
Example #4
Source File: ServletModelAttributeMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Create a model attribute from a String request value (e.g. URI template
 * variable, request parameter) using type conversion.
 * <p>The default implementation converts only if there a registered
 * {@link Converter} that can perform the conversion.
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute (never {@code null})
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null} if no suitable
 * conversion found
 */
@Nullable
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
		MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
		throws Exception {

	DataBinder binder = binderFactory.createBinder(request, null, attributeName);
	ConversionService conversionService = binder.getConversionService();
	if (conversionService != null) {
		TypeDescriptor source = TypeDescriptor.valueOf(String.class);
		TypeDescriptor target = new TypeDescriptor(parameter);
		if (conversionService.canConvert(source, target)) {
			return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
		}
	}
	return null;
}
 
Example #5
Source File: AbstractRequestAttributesArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveOptional() throws Exception {
	WebDataBinder dataBinder = new WebRequestDataBinder(null);
	dataBinder.setConversionService(new DefaultConversionService());
	WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
	given(factory.createBinder(this.webRequest, null, "foo")).willReturn(dataBinder);

	MethodParameter param = initMethodParameter(3);
	Object actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertFalse(((Optional<?>) actual).isPresent());

	Foo foo = new Foo();
	this.webRequest.setAttribute("foo", foo, getScope());

	actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertTrue(((Optional<?>) actual).isPresent());
	assertSame(foo, ((Optional<?>) actual).get());
}
 
Example #6
Source File: AbstractWebArgumentResolverAdapter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Delegate to the {@link WebArgumentResolver} instance.
 * @throws IllegalStateException if the resolved value is not assignable
 * to the method parameter.
 */
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	Class<?> paramType = parameter.getParameterType();
	Object result = this.adaptee.resolveArgument(parameter, webRequest);
	if (result == WebArgumentResolver.UNRESOLVED || !ClassUtils.isAssignableValue(paramType, result)) {
		throw new IllegalStateException(
				"Standard argument type [" + paramType.getName() + "] in method " + parameter.getMethod() +
				"resolved to incompatible value of type [" + (result != null ? result.getClass() : null) +
				"]. Consider declaring the argument type in a less specific fashion.");
	}
	return result;
}
 
Example #7
Source File: RequestResponseBodyMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	parameter = parameter.nestedIfOptional();
	Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
	String name = Conventions.getVariableNameForParameter(parameter);

	if (binderFactory != null) {
		WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
		if (arg != null) {
			validateIfApplicable(binder, parameter);
			if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
				throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
			}
		}
		if (mavContainer != null) {
			mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
		}
	}

	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example #8
Source File: PathVariableMapMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Return a Map with all URI template variables or an empty map.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	@SuppressWarnings("unchecked")
	Map<String, String> uriTemplateVars =
			(Map<String, String>) webRequest.getAttribute(
					HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	if (!CollectionUtils.isEmpty(uriTemplateVars)) {
		return new LinkedHashMap<>(uriTemplateVars);
	}
	else {
		return Collections.emptyMap();
	}
}
 
Example #9
Source File: HttpEntityMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory)
		throws IOException, HttpMediaTypeNotSupportedException {

	ServletServerHttpRequest inputMessage = createInputMessage(webRequest);
	Type paramType = getHttpEntityType(parameter);
	if (paramType == null) {
		throw new IllegalArgumentException("HttpEntity parameter '" + parameter.getParameterName() +
				"' in method " + parameter.getMethod() + " is not parameterized");
	}

	Object body = readWithMessageConverters(webRequest, parameter, paramType);
	if (RequestEntity.class == parameter.getParameterType()) {
		return new RequestEntity<>(body, inputMessage.getHeaders(),
				inputMessage.getMethod(), inputMessage.getURI());
	}
	else {
		return new HttpEntity<>(body, inputMessage.getHeaders());
	}
}
 
Example #10
Source File: PathVariableMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveArgumentWrappedAsOptional() throws Exception {
	Map<String, String> uriTemplateVars = new HashMap<>();
	uriTemplateVars.put("name", "value");
	request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, uriTemplateVars);

	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	@SuppressWarnings("unchecked")
	Optional<String> result = (Optional<String>)
			resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory);
	assertEquals("PathVariable not resolved correctly", "value", result.get());

	@SuppressWarnings("unchecked")
	Map<String, Object> pathVars = (Map<String, Object>) request.getAttribute(View.PATH_VARIABLES);
	assertNotNull(pathVars);
	assertEquals(1, pathVars.size());
	assertEquals(Optional.of("value"), pathVars.get("name"));
}
 
Example #11
Source File: ErrorsMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter,
		@Nullable ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
		@Nullable WebDataBinderFactory binderFactory) throws Exception {

	Assert.state(mavContainer != null,
			"Errors/BindingResult argument only supported on regular handler methods");

	ModelMap model = mavContainer.getModel();
	String lastKey = CollectionUtils.lastElement(model.keySet());
	if (lastKey != null && lastKey.startsWith(BindingResult.MODEL_KEY_PREFIX)) {
		return model.get(lastKey);
	}

	throw new IllegalStateException(
			"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());
}
 
Example #12
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void resolveOptionalParamList() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, List.class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.empty(), result);

	request.addParameter("name", "123", "456");
	result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.class, result.getClass());
	assertEquals(Arrays.asList("123", "456"), ((Optional) result).get());
}
 
Example #13
Source File: ModelAttributeMethodProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-9378
public void resolveArgumentOrdering() throws Exception {
	String name = "testBean";
	Object testBean = new TestBean(name);
	this.container.addAttribute(name, testBean);
	this.container.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, testBean);

	Object anotherTestBean = new TestBean();
	this.container.addAttribute("anotherTestBean", anotherTestBean);

	StubRequestDataBinder dataBinder = new StubRequestDataBinder(testBean, name);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.request, testBean, name)).willReturn(dataBinder);

	this.processor.resolveArgument(this.paramModelAttr, this.container, this.request, binderFactory);

	Object[] values = this.container.getModel().values().toArray();
	assertSame("Resolved attribute should be updated to be last", testBean, values[1]);
	assertSame("BindingResult of resolved attr should be last", dataBinder.getBindingResult(), values[2]);
}
 
Example #14
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void resolveOptionalParamValue() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer.class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.empty(), result);

	request.addParameter("name", "123");
	result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.class, result.getClass());
	assertEquals(123, ((Optional) result).get());
}
 
Example #15
Source File: PathVariableMapMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Return a Map with all URI template variables or an empty map.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	@SuppressWarnings("unchecked")
	Map<String, String> uriTemplateVars =
			(Map<String, String>) webRequest.getAttribute(
					HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);

	if (!CollectionUtils.isEmpty(uriTemplateVars)) {
		return new LinkedHashMap<>(uriTemplateVars);
	}
	else {
		return Collections.emptyMap();
	}
}
 
Example #16
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveOptionalMultipartFile() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MockMultipartHttpServletRequest request = new MockMultipartHttpServletRequest();
	MultipartFile expected = new MockMultipartFile("mfile", "Hello World".getBytes());
	request.addFile(expected);
	webRequest = new ServletWebRequest(request);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);

	assertTrue(result instanceof Optional);
	assertEquals("Invalid result", expected, ((Optional<?>) result).get());
}
 
Example #17
Source File: RequestParamMethodArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void resolveOptionalParamArray() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer[].class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.empty(), result);

	request.addParameter("name", "123", "456");
	result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.class, result.getClass());
	assertArrayEquals(new Integer[] {123, 456}, (Integer[]) ((Optional) result).get());
}
 
Example #18
Source File: ModelFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void updateModelSessionAttributesSaved() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(attribute, container.getModel().get(attributeName));
	assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example #19
Source File: ModelFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-12542
public void updateModelWhenRedirecting() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	String queryParam = "123";
	String queryParamName = "q";
	container.setRedirectModel(new ModelMap(queryParamName, queryParam));
	container.setRedirectModelScenario(true);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(queryParam, container.getModel().get(queryParamName));
	assertEquals(1, container.getModel().size());
	assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example #20
Source File: RequestJsonToPoHandlerMethodArgumentResolver.java    From jframework with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory binderFactory) throws Exception {
    RequestJsonToPo parameterAnnotation = parameter.getParameterAnnotation(RequestJsonToPo.class);
    Objects.requireNonNull(parameterAnnotation);
    String value = parameterAnnotation.value();
    Class<?> clazz = parameter.getNestedParameterType();
    String jsonParameter = nativeWebRequest.getParameter(value);
    if (jsonParameter == null) {
        if (clazz.isAssignableFrom(List.class)) {
            return Lists.newArrayList();
        }
        return clazz.newInstance();
    }
    jsonParameter = URLDecoder.decode(jsonParameter, StandardCharsets.UTF_8.name());

    if (clazz.isAssignableFrom(List.class) || clazz.isAssignableFrom(ArrayList.class)) {
        String typeName = ((sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl) parameter.getGenericParameterType()).getActualTypeArguments()[0].getTypeName();
        Class<?> aClass = Class.forName(typeName);
        return JsonUtil.toList(jsonParameter, aClass);
    } else {
        return JsonUtil.toObject(jsonParameter, clazz);
    }
}
 
Example #21
Source File: AbstractRequestAttributesArgumentResolverTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void resolveOptional() throws Exception {
	WebDataBinder dataBinder = new WebRequestDataBinder(null);
	dataBinder.setConversionService(new DefaultConversionService());
	WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
	given(factory.createBinder(this.webRequest, null, "foo")).willReturn(dataBinder);

	MethodParameter param = initMethodParameter(3);
	Object actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertFalse(((Optional<?>) actual).isPresent());

	Foo foo = new Foo();
	this.webRequest.setAttribute("foo", foo, getScope());

	actual = testResolveArgument(param, factory);
	assertNotNull(actual);
	assertEquals(Optional.class, actual.getClass());
	assertTrue(((Optional<?>) actual).isPresent());
	assertSame(foo, ((Optional<?>) actual).get());
}
 
Example #22
Source File: ServletModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Instantiate the model attribute from a URI template variable or from a
 * request parameter if the name matches to the model attribute name and
 * if there is an appropriate type conversion strategy. If none of these
 * are true delegate back to the base class.
 * @see #createAttributeFromRequestValue
 */
@Override
protected final Object createAttribute(String attributeName, MethodParameter parameter,
		WebDataBinderFactory binderFactory, NativeWebRequest request) throws Exception {

	String value = getRequestValueForAttribute(attributeName, request);
	if (value != null) {
		Object attribute = createAttributeFromRequestValue(
				value, attributeName, parameter, binderFactory, request);
		if (attribute != null) {
			return attribute;
		}
	}

	return super.createAttribute(attributeName, parameter, binderFactory, request);
}
 
Example #23
Source File: ServletModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a model attribute from a String request value (e.g. URI template
 * variable, request parameter) using type conversion.
 * <p>The default implementation converts only if there a registered
 * {@link Converter} that can perform the conversion.
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute (never {@code null})
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null} if no suitable
 * conversion found
 */
@Nullable
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
		MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
		throws Exception {

	DataBinder binder = binderFactory.createBinder(request, null, attributeName);
	ConversionService conversionService = binder.getConversionService();
	if (conversionService != null) {
		TypeDescriptor source = TypeDescriptor.valueOf(String.class);
		TypeDescriptor target = new TypeDescriptor(parameter);
		if (conversionService.canConvert(source, target)) {
			return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
		}
	}
	return null;
}
 
Example #24
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void resolveOptionalParamArray() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, Integer[].class);
	Object result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.empty(), result);

	request.addParameter("name", "123", "456");
	result = resolver.resolveArgument(param, null, webRequest, binderFactory);
	assertEquals(Optional.class, result.getClass());
	assertArrayEquals(new Integer[] {123, 456}, (Integer[]) ((Optional) result).get());
}
 
Example #25
Source File: PathVariableMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void wrapEmptyWithOptional() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	assertEquals(Optional.empty(), resolver.resolveArgument(paramOptional, mavContainer, webRequest, binderFactory));
}
 
Example #26
Source File: RequestParamMethodArgumentResolverTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void optionalMultipartFileWithoutMultipartRequest() throws Exception {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(new DefaultConversionService());
	WebDataBinderFactory binderFactory = new DefaultDataBinderFactory(initializer);

	MethodParameter param = this.testMethod.annotPresent(RequestParam.class).arg(Optional.class, MultipartFile.class);
	Object actual = resolver.resolveArgument(param, null, webRequest, binderFactory);

	assertEquals(Optional.empty(), actual);
}
 
Example #27
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
Example #28
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrName() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example #29
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrNameNoMatch() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "invalidName");

	assertNull(dataBinder.getDisallowedFields());
}
 
Example #30
Source File: ModelAttributeMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void resolveArgumentViaDefaultConstructor() throws Exception {
	WebDataBinder dataBinder = new WebRequestDataBinder(null);
	WebDataBinderFactory factory = mock(WebDataBinderFactory.class);
	given(factory.createBinder(any(), notNull(), eq("attrName"))).willReturn(dataBinder);

	this.processor.resolveArgument(this.paramNamedValidModelAttr, this.container, this.request, factory);
	verify(factory).createBinder(any(), notNull(), eq("attrName"));
}