Java Code Examples for org.springframework.core.Conventions#getVariableNameForParameter()

The following examples show how to use org.springframework.core.Conventions#getVariableNameForParameter() . 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: ErrorsMethodArgumentResolver.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private Object getErrors(MethodParameter parameter, BindingContext context) {
	Assert.isTrue(parameter.getParameterIndex() > 0,
			"Errors argument must be declared immediately after a model attribute argument");

	int index = parameter.getParameterIndex() - 1;
	MethodParameter attributeParam = MethodParameter.forExecutable(parameter.getExecutable(), index);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(attributeParam.getParameterType());

	Assert.state(adapter == null, "An @ModelAttribute and an Errors/BindingResult argument " +
			"cannot both be declared with an async type wrapper. " +
			"Either declare the @ModelAttribute without an async wrapper type or " +
			"handle a WebExchangeBindException error signal through the async type.");

	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null && StringUtils.hasText(ann.value()) ?
			ann.value() : Conventions.getVariableNameForParameter(attributeParam));
	Object errors = context.getModel().asMap().get(BindingResult.MODEL_KEY_PREFIX + name);

	Assert.state(errors != null, () -> "An Errors/BindingResult argument is expected " +
			"immediately after the @ModelAttribute argument to which it applies. " +
			"For @RequestBody and @RequestPart arguments, please declare them with a reactive " +
			"type wrapper and use its onError operators to handle WebExchangeBindException: " +
			parameter.getMethod());

	return errors;
}
 
Example 2
Source File: HandlerMethodInvoker.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam,
		ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception {

	// Bind request parameter onto object...
	String name = attrName;
	if ("".equals(name)) {
		name = Conventions.getVariableNameForParameter(methodParam);
	}
	Class<?> paramType = methodParam.getParameterType();
	Object bindObject;
	if (implicitModel.containsKey(name)) {
		bindObject = implicitModel.get(name);
	}
	else if (this.methodResolver.isSessionAttribute(name, paramType)) {
		bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name);
		if (bindObject == null) {
			raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session");
		}
	}
	else {
		bindObject = BeanUtils.instantiateClass(paramType);
	}
	WebDataBinder binder = createBinder(webRequest, bindObject, name);
	initBinder(handler, name, binder, webRequest);
	return binder;
}
 
Example 3
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 4
Source File: RequestResponseBodyMethodProcessor.java    From spring4-understanding with Apache License 2.0 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, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

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

	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());
		}
	}
	mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

	return arg;
}
 
Example 5
Source File: HandlerMethodInvoker.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam,
		ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception {

	// Bind request parameter onto object...
	String name = attrName;
	if ("".equals(name)) {
		name = Conventions.getVariableNameForParameter(methodParam);
	}
	Class<?> paramType = methodParam.getParameterType();
	Object bindObject;
	if (implicitModel.containsKey(name)) {
		bindObject = implicitModel.get(name);
	}
	else if (this.methodResolver.isSessionAttribute(name, paramType)) {
		bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name);
		if (bindObject == null) {
			raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session");
		}
	}
	else {
		bindObject = BeanUtils.instantiateClass(paramType);
	}
	WebDataBinder binder = createBinder(webRequest, bindObject, name);
	initBinder(handler, name, binder, webRequest);
	return binder;
}
 
Example 6
Source File: ErrorsMethodArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
private Object getErrors(MethodParameter parameter, BindingContext context) {
	Assert.isTrue(parameter.getParameterIndex() > 0,
			"Errors argument must be declared immediately after a model attribute argument");

	int index = parameter.getParameterIndex() - 1;
	MethodParameter attributeParam = MethodParameter.forExecutable(parameter.getExecutable(), index);
	ReactiveAdapter adapter = getAdapterRegistry().getAdapter(attributeParam.getParameterType());

	Assert.state(adapter == null, "An @ModelAttribute and an Errors/BindingResult argument " +
			"cannot both be declared with an async type wrapper. " +
			"Either declare the @ModelAttribute without an async wrapper type or " +
			"handle a WebExchangeBindException error signal through the async type.");

	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null && StringUtils.hasText(ann.value()) ?
			ann.value() : Conventions.getVariableNameForParameter(attributeParam));
	Object errors = context.getModel().asMap().get(BindingResult.MODEL_KEY_PREFIX + name);

	Assert.state(errors != null, () -> "An Errors/BindingResult argument is expected " +
			"immediately after the @ModelAttribute argument to which it applies. " +
			"For @RequestBody and @RequestPart arguments, please declare them with a reactive " +
			"type wrapper and use its onError operators to handle WebExchangeBindException: " +
			parameter.getMethod());

	return errors;
}
 
Example 7
Source File: RequestResponseBodyMethodProcessor.java    From lams with GNU General Public License v2.0 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, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

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

	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());
		}
	}
	mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example 8
Source File: RequestResponseBodyMethodProcessor.java    From java-technology-stack 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 9
Source File: TeapotMappingHandler.java    From example-restful-project with MIT License 5 votes vote down vote up
/**
 * Converts {@link TeapotMapping} to {@link Teapot} domain object. Apply
 * binding on {@link Teapot}.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    /* Read mapping from request */
    TeapotMapping mapping = (TeapotMapping) readWithMessageConverters(
            webRequest, parameter, TeapotMapping.class);
    String name = Conventions.getVariableNameForParameter(parameter);

    /* Convert mapping to domain object */
    Teapot teapot = mapper.fromMapping(mapping);

    WebDataBinder binder = binderFactory
            .createBinder(webRequest, teapot, name);

    if (teapot != null) {
        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
            throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
        }
    }

    mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

    return teapot;
}
 
Example 10
Source File: PayloadMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
	if (this.validator == null) {
		return null;
	}
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Validated validatedAnn = AnnotationUtils.getAnnotation(ann, Validated.class);
		if (validatedAnn != null || ann.annotationType().getSimpleName().startsWith("Valid")) {
			Object hints = (validatedAnn != null ? validatedAnn.value() : AnnotationUtils.getValue(ann));
			Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
			String name = Conventions.getVariableNameForParameter(parameter);
			return target -> {
				BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name);
				if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator) {
					((SmartValidator) this.validator).validate(target, bindingResult, validationHints);
				}
				else {
					this.validator.validate(target, bindingResult);
				}
				if (bindingResult.hasErrors()) {
					throw new MethodArgumentNotValidException(message, parameter, bindingResult);
				}
			};
		}
	}
	return null;
}
 
Example 11
Source File: AbstractMessageReaderArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void validate(Object target, Object[] validationHints, MethodParameter param,
		BindingContext binding, ServerWebExchange exchange) {

	String name = Conventions.getVariableNameForParameter(param);
	WebExchangeDataBinder binder = binding.createDataBinder(exchange, target, name);
	binder.validate(validationHints);
	if (binder.getBindingResult().hasErrors()) {
		throw new WebExchangeBindException(param, binder.getBindingResult());
	}
}
 
Example 12
Source File: AbstractMessageReaderArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void validate(Object target, Object[] validationHints, MethodParameter param,
		BindingContext binding, ServerWebExchange exchange) {

	String name = Conventions.getVariableNameForParameter(param);
	WebExchangeDataBinder binder = binding.createDataBinder(exchange, target, name);
	binder.validate(validationHints);
	if (binder.getBindingResult().hasErrors()) {
		throw new WebExchangeBindException(param, binder.getBindingResult());
	}
}
 
Example 13
Source File: ModelFactory.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Derive the model attribute name for the given method parameter based on
 * a {@code @ModelAttribute} parameter annotation (if present) or falling
 * back on parameter type based conventions.
 * @param parameter a descriptor for the method parameter
 * @return the derived name
 * @see Conventions#getVariableNameForParameter(MethodParameter)
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null ? ann.value() : null);
	return (StringUtils.hasText(name) ? name : Conventions.getVariableNameForParameter(parameter));
}
 
Example 14
Source File: ModelFactory.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Derive the model attribute name for a method parameter based on:
 * <ol>
 * <li>the parameter {@code @ModelAttribute} annotation value
 * <li>the parameter type
 * </ol>
 * @param parameter a descriptor for the method parameter
 * @return the derived name (never {@code null} or empty String)
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null ? ann.value() : null);
	return (StringUtils.hasText(name) ? name : Conventions.getVariableNameForParameter(parameter));
}
 
Example 15
Source File: ModelInitializer.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Derive the model attribute name for the given method parameter based on
 * a {@code @ModelAttribute} parameter annotation (if present) or falling
 * back on parameter type based conventions.
 * @param parameter a descriptor for the method parameter
 * @return the derived name
 * @see Conventions#getVariableNameForParameter(MethodParameter)
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null ? ann.value() : null);
	return (StringUtils.hasText(name) ? name : Conventions.getVariableNameForParameter(parameter));
}
 
Example 16
Source File: ModelFactory.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Derive the model attribute name for the given method parameter based on
 * a {@code @ModelAttribute} parameter annotation (if present) or falling
 * back on parameter type based conventions.
 * @param parameter a descriptor for the method parameter
 * @return the derived name
 * @see Conventions#getVariableNameForParameter(MethodParameter)
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null ? ann.value() : null);
	return (StringUtils.hasText(name) ? name : Conventions.getVariableNameForParameter(parameter));
}
 
Example 17
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Derives the model attribute name for a method parameter based on:
 * <ol>
 * 	<li>The parameter {@code @ModelAttribute} annotation value
 * 	<li>The parameter type
 * </ol>
 * @return the derived name; never {@code null} or an empty string
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute annot = parameter.getParameterAnnotation(ModelAttribute.class);
	String attrName = (annot != null) ? annot.value() : null;
	return StringUtils.hasText(attrName) ? attrName :  Conventions.getVariableNameForParameter(parameter);
}
 
Example 18
Source File: ModelInitializer.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Derive the model attribute name for the given method parameter based on
 * a {@code @ModelAttribute} parameter annotation (if present) or falling
 * back on parameter type based conventions.
 * @param parameter a descriptor for the method parameter
 * @return the derived name
 * @see Conventions#getVariableNameForParameter(MethodParameter)
 */
public static String getNameForParameter(MethodParameter parameter) {
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	String name = (ann != null ? ann.value() : null);
	return (StringUtils.hasText(name) ? name : Conventions.getVariableNameForParameter(parameter));
}