Java Code Examples for org.springframework.core.MethodParameter#getParameterAnnotations()

The following examples show how to use org.springframework.core.MethodParameter#getParameterAnnotations() . 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: ModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Validate the specified candidate value if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter declaration
 * @param targetType the target type
 * @param fieldName the name of the field
 * @param value the candidate value
 * @since 5.1
 * @see #validateIfApplicable(WebDataBinder, MethodParameter)
 * @see SmartValidator#validateValue(Class, String, Object, Errors, Object...)
 */
protected void validateValueIfApplicable(WebDataBinder binder, MethodParameter parameter,
		Class<?> targetType, String fieldName, @Nullable Object value) {

	for (Annotation ann : parameter.getParameterAnnotations()) {
		Object[] validationHints = determineValidationHints(ann);
		if (validationHints != null) {
			for (Validator validator : binder.getValidators()) {
				if (validator instanceof SmartValidator) {
					try {
						((SmartValidator) validator).validateValue(targetType, fieldName, value,
								binder.getBindingResult(), validationHints);
					}
					catch (IllegalArgumentException ex) {
						// No corresponding field on the target class...
					}
				}
			}
			break;
		}
	}
}
 
Example 2
Source File: ModelAttributeMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Validate the specified candidate value if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter declaration
 * @param targetType the target type
 * @param fieldName the name of the field
 * @param value the candidate value
 * @since 5.1
 * @see #validateIfApplicable(WebDataBinder, MethodParameter)
 * @see SmartValidator#validateValue(Class, String, Object, Errors, Object...)
 */
protected void validateValueIfApplicable(WebDataBinder binder, MethodParameter parameter,
		Class<?> targetType, String fieldName, @Nullable Object value) {

	for (Annotation ann : parameter.getParameterAnnotations()) {
		Object[] validationHints = determineValidationHints(ann);
		if (validationHints != null) {
			for (Validator validator : binder.getValidators()) {
				if (validator instanceof SmartValidator) {
					try {
						((SmartValidator) validator).validateValue(targetType, fieldName, value,
								binder.getBindingResult(), validationHints);
					}
					catch (IllegalArgumentException ex) {
						// No corresponding field on the target class...
					}
				}
			}
			break;
		}
	}
}
 
Example 3
Source File: PayloadArgumentResolver.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Validate the payload if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param message the currently processed message
 * @param parameter the method parameter
 * @param target the target payload object
 * @throws MethodArgumentNotValidException in case of binding errors
 */
protected void validate(Message<?> message, MethodParameter parameter, Object target) {
	if (this.validator == null) {
		return;
	}
	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});
			BeanPropertyBindingResult bindingResult =
					new BeanPropertyBindingResult(target, getParameterName(parameter));
			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);
			}
			break;
		}
	}
}
 
Example 4
Source File: MethodParameterValidatorConstraintResolver.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
@Override
public List<Constraint> resolveForParameter(MethodParameter param) {
    if (CONSTRAINT_CLASS == null) {
        return Collections.emptyList();
    }

    List<Constraint> constraints = new ArrayList<>();
    for (Annotation annot : param.getParameterAnnotations()) {
        Class<? extends Annotation> type = annot.annotationType();
        if (type.getAnnotation(CONSTRAINT_CLASS) != null) {
            Constraint constraint = createConstraint(annot, type);
            constraints.add(constraint);
        }
    }
    return constraints;
}
 
Example 5
Source File: ModelAttributeMethodArgumentResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void validateIfApplicable(WebExchangeDataBinder binder, MethodParameter parameter) {
	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));
			if (hints != null) {
				Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
				binder.validate(validationHints);
			}
			else {
				binder.validate();
			}
		}
	}
}
 
Example 6
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
/**
 * Validate the model attribute if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid}.
 *
 * @param binder    the DataBinder to be used
 * @param parameter the method parameter
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid")) {
            Object hints = AnnotationUtils.getValue(annot);
            binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
        }
    }
}
 
Example 7
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
private boolean validateParameter(MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid")) {
            return true;
        }
    }

    return false;
}
 
Example 8
Source File: AbstractMessageConverterMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the request part if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param methodParam the method parameter
 * @see #isBindExceptionRequired
 * @since 4.1.5
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
	Annotation[] annotations = methodParam.getParameterAnnotations();
	for (Annotation ann : annotations) {
		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});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example 9
Source File: AutoRequestBodyProcessor.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private boolean hasSpringAnnotation(MethodParameter parameter){
    for(Annotation ann:parameter.getParameterAnnotations()){
        if(ann.annotationType().getPackage().getName().startsWith("org.springframework.web.bind.annotation")){
            return true;
        }
    }
    return false;
}
 
Example 10
Source File: ModelAttributeMethodProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Validate the model attribute if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param methodParam the method parameter
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter methodParam) {
	Annotation[] annotations = methodParam.getParameterAnnotations();
	for (Annotation ann : annotations) {
		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});
			binder.validate(validationHints);
			break;
		}
	}
}
 
Example 11
Source File: SpecificationArgumentResolver.java    From specification-arg-resolver with Apache License 2.0 5 votes vote down vote up
private boolean isAnnotated(MethodParameter methodParameter) {
	for (Annotation annotation : methodParameter.getParameterAnnotations()) {
		for (Class<? extends Annotation> annotationType : resolversBySupportedType.keySet()) {
			if (annotationType.equals(annotation.annotationType())) {
				return true;
			}
		}
	}

	return isAnnotatedRecursively(methodParameter.getParameterType());
}
 
Example 12
Source File: FormModelMethodArgumentResolver.java    From es with Apache License 2.0 5 votes vote down vote up
private boolean validateParameter(MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();
    for (Annotation annot : annotations) {
        if (annot.annotationType().getSimpleName().startsWith("Valid")) {
            return true;
        }
    }

    return false;
}
 
Example 13
Source File: TypeDescriptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getParameterType());
	this.annotatedElement = new AnnotatedElementAdapter(methodParameter.getParameterIndex() == -1 ?
			methodParameter.getMethodAnnotations() : methodParameter.getParameterAnnotations());
}
 
Example 14
Source File: TypeDescriptor.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Create a new type descriptor from a {@link MethodParameter}.
 * <p>Use this constructor when a source or target conversion point is a
 * constructor parameter, method parameter, or method return value.
 * @param methodParameter the method parameter
 */
public TypeDescriptor(MethodParameter methodParameter) {
	this.resolvableType = ResolvableType.forMethodParameter(methodParameter);
	this.type = this.resolvableType.resolve(methodParameter.getNestedParameterType());
	this.annotatedElement = new AnnotatedElementAdapter(methodParameter.getParameterIndex() == -1 ?
			methodParameter.getMethodAnnotations() : methodParameter.getParameterAnnotations());
}
 
Example 15
Source File: JwtTokenArgumentResolver.java    From watchdog-framework with MIT License 5 votes vote down vote up
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    String authorization = request.getHeader("Authorization");
    String result = null;
    JwtClaim token = null;
    if(authorization!=null){
        Annotation[] methodAnnotations = parameter.getParameterAnnotations();
        for (Annotation methodAnnotation : methodAnnotations) {
            if(methodAnnotation instanceof JwtClaim){
                token = (JwtClaim) methodAnnotation;
                break;
            }
        }
        if(token!=null){
            result = JwtUtil.get(authorization,token.value());
        }
    }
    if(result!=null){
        return result;
    }
    if(token==null || token.exception()){
        throw new RequestException(ResponseCode.NOT_SING_IN);
    }else{
        return null;
    }
}
 
Example 16
Source File: ModelAttributeMethodArgumentResolver.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void validateIfApplicable(WebExchangeDataBinder binder, MethodParameter parameter) {
	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));
			if (hints != null) {
				Object[] validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] {hints});
				binder.validate(validationHints);
			}
			else {
				binder.validate();
			}
		}
	}
}
 
Example 17
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 18
Source File: HandlerMethodInvoker.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
private Object[] resolveInitBinderArguments(Object handler, Method initBinderMethod,
		WebDataBinder binder, NativeWebRequest webRequest) throws Exception {

	Class<?>[] initBinderParams = initBinderMethod.getParameterTypes();
	Object[] initBinderArgs = new Object[initBinderParams.length];

	for (int i = 0; i < initBinderArgs.length; i++) {
		MethodParameter methodParam = new SynthesizingMethodParameter(initBinderMethod, i);
		methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
		GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
		String paramName = null;
		boolean paramRequired = false;
		String paramDefaultValue = null;
		String pathVarName = null;
		Annotation[] paramAnns = methodParam.getParameterAnnotations();

		for (Annotation paramAnn : paramAnns) {
			if (RequestParam.class.isInstance(paramAnn)) {
				RequestParam requestParam = (RequestParam) paramAnn;
				paramName = requestParam.name();
				paramRequired = requestParam.required();
				paramDefaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
				break;
			}
			else if (ModelAttribute.class.isInstance(paramAnn)) {
				throw new IllegalStateException(
						"@ModelAttribute is not supported on @InitBinder methods: " + initBinderMethod);
			}
			else if (PathVariable.class.isInstance(paramAnn)) {
				PathVariable pathVar = (PathVariable) paramAnn;
				pathVarName = pathVar.value();
			}
		}

		if (paramName == null && pathVarName == null) {
			Object argValue = resolveCommonArgument(methodParam, webRequest);
			if (argValue != WebArgumentResolver.UNRESOLVED) {
				initBinderArgs[i] = argValue;
			}
			else {
				Class<?> paramType = initBinderParams[i];
				if (paramType.isInstance(binder)) {
					initBinderArgs[i] = binder;
				}
				else if (BeanUtils.isSimpleProperty(paramType)) {
					paramName = "";
				}
				else {
					throw new IllegalStateException("Unsupported argument [" + paramType.getName() +
							"] for @InitBinder method: " + initBinderMethod);
				}
			}
		}

		if (paramName != null) {
			initBinderArgs[i] =
					resolveRequestParam(paramName, paramRequired, paramDefaultValue, methodParam, webRequest, null);
		}
		else if (pathVarName != null) {
			initBinderArgs[i] = resolvePathVariable(pathVarName, methodParam, webRequest, null);
		}
	}

	return initBinderArgs;
}
 
Example 19
Source File: MapMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public boolean supportsParameter(MethodParameter parameter) {
	return Map.class.isAssignableFrom(parameter.getParameterType()) &&
			parameter.getParameterAnnotations().length == 0;
}
 
Example 20
Source File: ModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Validate the model attribute if applicable.
 * <p>The default implementation checks for {@code @javax.validation.Valid},
 * Spring's {@link org.springframework.validation.annotation.Validated},
 * and custom annotations whose name starts with "Valid".
 * @param binder the DataBinder to be used
 * @param parameter the method parameter declaration
 * @see WebDataBinder#validate(Object...)
 * @see SmartValidator#validate(Object, Errors, Object...)
 */
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
	for (Annotation ann : parameter.getParameterAnnotations()) {
		Object[] validationHints = determineValidationHints(ann);
		if (validationHints != null) {
			binder.validate(validationHints);
			break;
		}
	}
}