Example usage for org.springframework.core MethodParameter getParameterAnnotations

List of usage examples for org.springframework.core MethodParameter getParameterAnnotations

Introduction

In this page you can find the example usage for org.springframework.core MethodParameter getParameterAnnotations.

Prototype

public Annotation[] getParameterAnnotations() 

Source Link

Document

Return the annotations associated with the specific method/constructor parameter.

Usage

From source file:org.springframework.kafka.listener.adapter.MessagingMessageListenerAdapter.java

private Type determineInferredType(Method method) {
    if (method == null) {
        return null;
    }//from  www. j av a 2 s  .  com

    Type genericParameterType = null;
    boolean hasAck = false;

    for (int i = 0; i < method.getParameterTypes().length; i++) {
        MethodParameter methodParameter = new MethodParameter(method, i);
        /*
         * We're looking for a single non-annotated parameter, or one annotated with @Payload.
         * We ignore parameters with type Message because they are not involved with conversion.
         */
        if (eligibleParameter(methodParameter) && (methodParameter.getParameterAnnotations().length == 0
                || methodParameter.hasParameterAnnotation(Payload.class))) {
            if (genericParameterType == null) {
                genericParameterType = methodParameter.getGenericParameterType();
                if (genericParameterType instanceof ParameterizedType) {
                    ParameterizedType parameterizedType = (ParameterizedType) genericParameterType;
                    if (parameterizedType.getRawType().equals(Message.class)) {
                        genericParameterType = ((ParameterizedType) genericParameterType)
                                .getActualTypeArguments()[0];
                    } else if (parameterizedType.getRawType().equals(List.class)
                            && parameterizedType.getActualTypeArguments().length == 1) {
                        Type paramType = parameterizedType.getActualTypeArguments()[0];
                        this.isConsumerRecordList = paramType.equals(ConsumerRecord.class)
                                || (paramType instanceof ParameterizedType && ((ParameterizedType) paramType)
                                        .getRawType().equals(ConsumerRecord.class));
                        this.isMessageList = paramType.equals(Message.class)
                                || (paramType instanceof ParameterizedType
                                        && ((ParameterizedType) paramType).getRawType().equals(Message.class));
                    }
                }
            } else {
                if (this.logger.isDebugEnabled()) {
                    this.logger.debug("Ambiguous parameters for target payload for method " + method
                            + "; no inferred type available");
                }
                break;
            }
        } else if (methodParameter.getGenericParameterType().equals(Acknowledgment.class)) {
            hasAck = true;
        }
    }
    Assert.state(
            !this.isConsumerRecordList || method.getParameterTypes().length == 1
                    || (method.getGenericParameterTypes().length == 2 && hasAck),
            "A parameter of type 'List<ConsumerRecord>' must be the only parameter "
                    + "(except for an optional 'Acknowledgment')");
    Assert.state(
            !this.isMessageList || method.getParameterTypes().length == 1
                    || (method.getGenericParameterTypes().length == 2 && hasAck),
            "A parameter of type 'List<Message<?>>' must be the only parameter "
                    + "(except for an optional 'Acknowledgment')");

    return genericParameterType;
}

From source file:org.springframework.messaging.handler.annotation.reactive.PayloadMethodArgumentResolver.java

@Nullable
private Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) {
    if (this.validator == null) {
        return null;
    }/*from  ww w .ja va2 s .c o  m*/
    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;
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

private Object[] resolveHandlerArguments(Method handlerMethod, Object handler, NativeWebRequest webRequest,
        ExtendedModelMap implicitModel) throws Exception {

    Class<?>[] paramTypes = handlerMethod.getParameterTypes();
    Object[] args = new Object[paramTypes.length];

    for (int i = 0; i < args.length; i++) {
        MethodParameter methodParam = new MethodParameter(handlerMethod, i);
        methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
        String paramName = null;//  w ww  . j  a va  2 s  . c o m
        String headerName = null;
        boolean requestBodyFound = false;
        String cookieName = null;
        String pathVarName = null;
        String attrName = null;
        boolean required = false;
        String defaultValue = null;
        boolean validate = false;
        Object[] validationHints = null;
        int annotationsFound = 0;
        Annotation[] paramAnns = methodParam.getParameterAnnotations();

        for (Annotation paramAnn : paramAnns) {
            if (RequestParam.class.isInstance(paramAnn)) {
                RequestParam requestParam = (RequestParam) paramAnn;
                paramName = requestParam.value();
                required = requestParam.required();
                defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
                annotationsFound++;
            } else if (RequestHeader.class.isInstance(paramAnn)) {
                RequestHeader requestHeader = (RequestHeader) paramAnn;
                headerName = requestHeader.value();
                required = requestHeader.required();
                defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());
                annotationsFound++;
            } else if (RequestBody.class.isInstance(paramAnn)) {
                requestBodyFound = true;
                annotationsFound++;
            } else if (CookieValue.class.isInstance(paramAnn)) {
                CookieValue cookieValue = (CookieValue) paramAnn;
                cookieName = cookieValue.value();
                required = cookieValue.required();
                defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());
                annotationsFound++;
            } else if (PathVariable.class.isInstance(paramAnn)) {
                PathVariable pathVar = (PathVariable) paramAnn;
                pathVarName = pathVar.value();
                annotationsFound++;
            } else if (ModelAttribute.class.isInstance(paramAnn)) {
                ModelAttribute attr = (ModelAttribute) paramAnn;
                attrName = attr.value();
                annotationsFound++;
            } else if (Value.class.isInstance(paramAnn)) {
                defaultValue = ((Value) paramAnn).value();
            } else {
                Validated validatedAnn = AnnotationUtils.getAnnotation(paramAnn, Validated.class);
                if (validatedAnn != null || paramAnn.annotationType().getSimpleName().startsWith("Valid")) {
                    validate = true;
                    Object hints = (validatedAnn != null ? validatedAnn.value()
                            : AnnotationUtils.getValue(paramAnn));
                    validationHints = (hints instanceof Object[] ? (Object[]) hints : new Object[] { hints });
                }
            }
        }

        if (annotationsFound > 1) {
            throw new IllegalStateException("Handler parameter annotations are exclusive choices - "
                    + "do not specify more than one such annotation on the same parameter: " + handlerMethod);
        }

        if (annotationsFound == 0) {
            Object argValue = resolveCommonArgument(methodParam, webRequest);
            if (argValue != WebArgumentResolver.UNRESOLVED) {
                args[i] = argValue;
            } else if (defaultValue != null) {
                args[i] = resolveDefaultValue(defaultValue);
            } else {
                Class<?> paramType = methodParam.getParameterType();
                if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {
                    if (!paramType.isAssignableFrom(implicitModel.getClass())) {
                        throw new IllegalStateException("Argument [" + paramType.getSimpleName()
                                + "] is of type "
                                + "Model or Map but is not assignable from the actual model. You may need to switch "
                                + "newer MVC infrastructure classes to use this argument.");
                    }
                    args[i] = implicitModel;
                } else if (SessionStatus.class.isAssignableFrom(paramType)) {
                    args[i] = this.sessionStatus;
                } else if (HttpEntity.class.isAssignableFrom(paramType)) {
                    args[i] = resolveHttpEntityRequest(methodParam, webRequest);
                } else if (Errors.class.isAssignableFrom(paramType)) {
                    throw new IllegalStateException("Errors/BindingResult argument declared "
                            + "without preceding model attribute. Check your handler method signature!");
                } else if (BeanUtils.isSimpleProperty(paramType)) {
                    paramName = "";
                } else {
                    attrName = "";
                }
            }
        }

        if (paramName != null) {
            args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);
        } else if (headerName != null) {
            args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest,
                    handler);
        } else if (requestBodyFound) {
            args[i] = resolveRequestBody(methodParam, webRequest, handler);
        } else if (cookieName != null) {
            args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);
        } else if (pathVarName != null) {
            args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
        } else if (attrName != null) {
            WebDataBinder binder = resolveModelAttribute(attrName, methodParam, implicitModel, webRequest,
                    handler);
            boolean assignBindingResult = (args.length > i + 1
                    && Errors.class.isAssignableFrom(paramTypes[i + 1]));
            if (binder.getTarget() != null) {
                doBind(binder, webRequest, validate, validationHints, !assignBindingResult);
            }
            args[i] = binder.getTarget();
            if (assignBindingResult) {
                args[i + 1] = binder.getBindingResult();
                i++;
            }
            implicitModel.putAll(binder.getBindingResult().getModel());
        }
    }

    return args;
}

From source file:org.springframework.web.bind.annotation.support.HandlerMethodInvoker.java

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 MethodParameter(initBinderMethod, i);
        methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
        String paramName = null;//from www . j  a va  2  s. com
        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.value();
                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;
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * 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
 *//*  w  w  w . ja v a 2 s .  c o m*/
protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
    Annotation[] annotations = parameter.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;
        }
    }
}

From source file:org.springframework.web.method.annotation.support.ModelAttributeMethodProcessor.java

/**
 * Whether to validate the model attribute.
 * The default implementation checks for {@code @javax.validation.Valid}. 
 * @param modelAttribute the model attribute
 * @param parameter the method argument//  w  ww  . j a v  a2 s.co m
 */
protected boolean isValidationApplicable(Object modelAttribute, MethodParameter parameter) {
    Annotation[] annotations = parameter.getParameterAnnotations();
    for (Annotation annot : annotations) {
        if ("Valid".equals(annot.annotationType().getSimpleName())) {
            return true;
        }
    }
    return false;
}