Example usage for org.springframework.core MethodParameter getParameterAnnotation

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

Introduction

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

Prototype

@SuppressWarnings("unchecked")
@Nullable
public <A extends Annotation> A getParameterAnnotation(Class<A> annotationType) 

Source Link

Document

Return the parameter annotation of the given type, if available.

Usage

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

@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
    Header annot = parameter.getParameterAnnotation(Header.class);
    Assert.state(annot != null, "No Header annotation");
    return new HeaderNamedValueInfo(annot);
}

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

/**
 * Decode the content of the given message payload through a compatible
 * {@link Decoder}.//w  w  w.  j a  v  a  2s.  co m
 *
 * <p>Validation is applied if the method argument is annotated with
 * {@code @javax.validation.Valid} or
 * {@link org.springframework.validation.annotation.Validated}. Validation
 * failure results in an {@link MethodArgumentNotValidException}.
 *
 * @param parameter the target method argument that we are decoding to
 * @param message the message from which the content was extracted
 * @return a Mono with the result of argument resolution
 *
 * @see #extractContent(MethodParameter, Message)
 * @see #getMimeType(Message)
 */
@Override
public final Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) {

    Payload ann = parameter.getParameterAnnotation(Payload.class);
    if (ann != null && StringUtils.hasText(ann.expression())) {
        throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver");
    }

    MimeType mimeType = getMimeType(message);
    mimeType = mimeType != null ? mimeType : MimeTypeUtils.APPLICATION_OCTET_STREAM;

    Flux<DataBuffer> content = extractContent(parameter, message);
    return decodeContent(parameter, message, ann == null || ann.required(), content, mimeType);
}

From source file:org.springframework.messaging.handler.annotation.support.HeaderMethodArgumentResolver.java

@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
    Header annotation = parameter.getParameterAnnotation(Header.class);
    Assert.state(annotation != null, "No Header annotation");
    return new HeaderNamedValueInfo(annotation);
}

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

/**
 * Resolve the argument from the model or if not found instantiate it with
 * its default if it is available. The model attribute is then populated
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 * @throws BindException if data binding and validation result in an error
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 *//*from  w w w . j  a  v a 2s.c o m*/
@Override
@Nullable
public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

    Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
    Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");

    String name = ModelFactory.getNameForParameter(parameter);
    ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
    if (ann != null) {
        mavContainer.setBinding(name, ann.binding());
    }

    Object attribute = null;
    BindingResult bindingResult = null;

    if (mavContainer.containsAttribute(name)) {
        attribute = mavContainer.getModel().get(name);
    } else {
        // Create attribute instance
        try {
            attribute = createAttribute(name, parameter, binderFactory, webRequest);
        } catch (BindException ex) {
            if (isBindExceptionRequired(parameter)) {
                // No BindingResult parameter -> fail with BindException
                throw ex;
            }
            // Otherwise, expose null/empty value and associated BindingResult
            if (parameter.getParameterType() == Optional.class) {
                attribute = Optional.empty();
            }
            bindingResult = ex.getBindingResult();
        }
    }

    if (bindingResult == null) {
        // Bean property binding and validation;
        // skipped in case of binding failure on construction.
        WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
        if (binder.getTarget() != null) {
            if (!mavContainer.isBindingDisabled(name)) {
                bindRequestParameters(binder, webRequest);
            }
            validateIfApplicable(binder, parameter);
            if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
        // Value type adaptation, also covering java.util.Optional
        if (!parameter.getParameterType().isInstance(attribute)) {
            attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
        }
        bindingResult = binder.getBindingResult();
    }

    // Add resolved attribute and BindingResult at the end of the model
    Map<String, Object> bindingResultModel = bindingResult.getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return attribute;
}

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

/**
 * 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/* w w  w  . j  a v  a 2s. c om*/
 * @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));
}

From source file:org.springframework.web.reactive.result.method.HandlerMethodArgumentResolverSupport.java

/**
 * Evaluate the {@code Predicate} on the method parameter type if it has the
 * given annotation, nesting within {@link java.util.Optional} if necessary,
 * but raise an {@code IllegalStateException} if the same matches the generic
 * type within a reactive type wrapper.//  w  w  w  .  ja  v  a 2  s.  c  om
 */
protected <A extends Annotation> boolean checkAnnotatedParamNoReactiveWrapper(MethodParameter parameter,
        Class<A> annotationType, BiPredicate<A, Class<?>> typePredicate) {

    A annotation = parameter.getParameterAnnotation(annotationType);
    if (annotation == null) {
        return false;
    }

    parameter = parameter.nestedIfOptional();
    Class<?> type = parameter.getNestedParameterType();

    ReactiveAdapter adapter = getAdapterRegistry().getAdapter(type);
    if (adapter != null) {
        assertHasValues(adapter, parameter);
        parameter = parameter.nested();
        type = parameter.getNestedParameterType();
    }

    if (typePredicate.test(annotation, type)) {
        if (adapter == null) {
            return true;
        }
        throw buildReactiveWrapperException(parameter);
    }

    return false;
}

From source file:plum.mvc.PageArgumentResolver.java

@Override
public boolean supportsParameter(MethodParameter parameter) {
    return parameter.getParameterAnnotation(PaginationParam.class) != null;
}

From source file:plum.mvc.PageArgumentResolver.java

@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    final PaginationParam attr = parameter.getParameterAnnotation(PaginationParam.class);

    final Map<String, String[]> params = webRequest.getParameterMap();
    //?KEY?// w ww.j  a va 2s .  c  o m
    final Map<String, String[]> case_params = new CaseInsensitiveMap(params);
    String sPageIndex = case_params.get(attr.indexName())[0];
    String sPageSize = case_params.get(attr.sizeName())[0];
    //like sore=column desc,column2 asc
    String sort = case_params.get(attr.sortName())[0];

    final PageQuery pageQuery = new PageQuery();
    int pageSize;
    int pageIndex;
    try {
        pageIndex = Integer.valueOf(sPageIndex);
        pageSize = Integer.valueOf(sPageSize);
    } catch (NumberFormatException e) {
        logger.error("number paging is error!", e);
        if (!attr.required()) {
            return null;
        }
        pageSize = attr.pageSize();
        pageIndex = 0;
    } finally {
        try {
            case_params.clear();
        } catch (UnsupportedOperationException e) {
            logger.warn("param is not clear!");
        }
    }
    final List<SortInfo> sortFields = SortInfo.parseSortColumns(sort);

    pageQuery.setPageSize(pageSize);
    pageQuery.setSortInfoList(sortFields);
    pageQuery.setPage((pageIndex - 1) * pageSize);

    return pageQuery;

}