Example usage for org.springframework.core MethodParameter getMethodAnnotation

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

Introduction

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

Prototype

@Nullable
public <A extends Annotation> A getMethodAnnotation(Class<A> annotationType) 

Source Link

Document

Return the method/constructor annotation of the given type, if available.

Usage

From source file:com.github.jonpeterson.spring.mvc.versioning.VersionedModelResponseBodyAdvice.java

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
        Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    VersionedResponseBody versionedResponseBody = returnType.getMethodAnnotation(VersionedResponseBody.class);
    String targetVersion = null;//from  w w  w  .jav a 2 s .co  m

    String queryParamName = versionedResponseBody.queryParamName();
    if (!queryParamName.isEmpty()) {
        List<String> queryParamValues = UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams()
                .get(queryParamName);
        if (queryParamValues != null && !queryParamValues.isEmpty())
            targetVersion = queryParamValues.get(0);
    }

    if (targetVersion == null) {
        String headerName = versionedResponseBody.headerName();
        if (!headerName.isEmpty()) {
            List<String> headerValues = request.getHeaders().get(headerName);
            if (headerValues != null && !headerValues.isEmpty())
                targetVersion = headerValues.get(0);
        }
    }

    if (targetVersion == null)
        targetVersion = versionedResponseBody.defaultVersion();

    try {
        boolean serializeToSet = false;

        for (BeanPropertyDefinition beanPropertyDefinition : mapper.getSerializationConfig()
                .introspect(mapper.getTypeFactory().constructType(body.getClass())).findProperties()) {
            AnnotatedMember field = beanPropertyDefinition.getField();
            AnnotatedMember setter = beanPropertyDefinition.getSetter();
            if ((field != null && field.hasAnnotation(JsonSerializeToVersion.class))
                    || (setter != null && setter.hasAnnotation(JsonSerializeToVersion.class))) {
                if (setter != null)
                    setter.setValue(body, targetVersion);
                else
                    field.setValue(body, targetVersion);
                serializeToSet = true;
            }
        }

        if (!serializeToSet)
            throw new RuntimeException("no @" + JsonSerializeToVersion.class.getSimpleName()
                    + " annotation found on String field or setter method in " + body.getClass()
                    + "; this is a requirement when using @" + VersionedResponseBody.class.getSimpleName());

    } catch (Exception e) {
        throw new RuntimeException("unable to set the version of the response body model", e);
    }

    return body;
}

From source file:com.github.zhanhb.download.spring.PathDownloaderHandler.java

@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType,
        ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
    HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
    ToDownload toDownload = returnType.getMethodAnnotation(ToDownload.class);

    PathPartial d = toDownload.attachment() ? downloader : viewer;
    d.service(request, response, Path.class.cast(returnValue));
    mavContainer.setRequestHandled(true);
}

From source file:cn.guoyukun.spring.jpa.web.bind.method.annotation.SearchableMethodArgumentResolver.java

private SearchableDefaults getSearchableDefaults(MethodParameter parameter) {
    //?//from  w ww . j a  v  a2s  .c  om
    SearchableDefaults searchDefaults = parameter.getParameterAnnotation(SearchableDefaults.class);
    //?
    if (searchDefaults == null) {
        searchDefaults = parameter.getMethodAnnotation(SearchableDefaults.class);
    }
    return searchDefaults;
}

From source file:org.makersoft.mvc.method.annotation.FormatHandlerMethodReturnValueHandler.java

protected <T extends Object> void writeWithJSONSerialize(T returnValue, MethodParameter returnType,
        NativeWebRequest webRequest) throws IOException, HttpMediaTypeNotAcceptableException {
    ServletServerHttpRequest inputMessage = this.createInputMessage(webRequest);
    ServletServerHttpResponse outputMessage = this.createOutputMessage(webRequest);

    Format format = returnType.getMethodAnnotation(Format.class);
    JSONResult result = new JSONResult();

    if (format.excludes().length > 0) {
        result.setExcludeProperties(StringUtils.join(format.excludes(), ","));
    }/* ww  w.j a  v  a2s  .c  o m*/

    if (format.includes().length > 0) {
        result.setIncludeProperties(StringUtils.join(format.includes(), ","));
    }

    // default false
    result.setIgnoreHierarchy(format.ignoreHierarchy());

    //settings 
    result.setEncoding(encoding);
    result.setWrapWithComments(wrapWithComments);
    result.setPrefix(prefix);
    result.setEnableGZIP(enableGZIP);
    result.setEnumAsBean(enumAsBean);
    result.setNoCache(noCache);
    result.setExcludeNullProperties(excludeNullProperties);
    result.setCallbackParameter(callbackParameter);
    result.setWrapPrefix(wrapPrefix);
    result.setWrapSuffix(wrapSuffix);

    try {
        result.execute(inputMessage.getServletRequest(), outputMessage.getServletResponse(), returnValue);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:cn.guoyukun.spring.jpa.web.bind.method.annotation.PageableMethodArgumentResolver.java

private PageableDefaults getPageableDefaults(MethodParameter parameter) {
    //?//from ww  w.  ja v  a  2s .c o m
    PageableDefaults pageableDefaults = parameter.getParameterAnnotation(PageableDefaults.class);
    //?
    if (pageableDefaults == null) {
        pageableDefaults = parameter.getMethodAnnotation(PageableDefaults.class);
    }
    return pageableDefaults;
}

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

/**
 * Derive the model attribute name for the given return value based on:
 * <ol>/*ww w  . j a v  a2  s  . c  o m*/
 * <li>the method {@code ModelAttribute} annotation value
 * <li>the declared return type if it is more specific than {@code Object}
 * <li>the actual return value type
 * </ol>
 * @param returnValue the value returned from a method invocation
 * @param returnType a descriptor for the return type of the method
 * @return the derived name (never {@code null} or empty String)
 */
public static String getNameForReturnValue(@Nullable Object returnValue, MethodParameter returnType) {
    ModelAttribute ann = returnType.getMethodAnnotation(ModelAttribute.class);
    if (ann != null && StringUtils.hasText(ann.value())) {
        return ann.value();
    } else {
        Method method = returnType.getMethod();
        Assert.state(method != null, "No handler method");
        Class<?> containingClass = returnType.getContainingClass();
        Class<?> resolvedType = GenericTypeResolver.resolveReturnType(method, containingClass);
        return Conventions.getVariableNameForReturnType(method, resolvedType, returnValue);
    }
}

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

/**
 * Return {@code true} if there is a method-level {@code @ModelAttribute} 
 * or if it is a non-simple type when {@code annotationNotRequired=true}.
 *//*from  ww  w .j a  v  a2 s .co m*/
public boolean supportsReturnType(MethodParameter returnType) {
    if (returnType.getMethodAnnotation(ModelAttribute.class) != null) {
        return true;
    } else if (this.annotationNotRequired) {
        return !BeanUtils.isSimpleProperty(returnType.getParameterType());
    } else {
        return false;
    }
}