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

The following examples show how to use org.springframework.core.MethodParameter#getMethodAnnotation() . 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: ClientAppUserAccessTokenArgumentResolver.java    From kaif with Apache License 2.0 6 votes vote down vote up
@Override
public ClientAppUserAccessToken resolveArgument(MethodParameter parameter,
    ModelAndViewContainer mavContainer,
    NativeWebRequest webRequest,
    WebDataBinderFactory binderFactory) throws Exception {
  String tokenStr = Strings.trimToEmpty(webRequest.getHeader(HttpHeaders.AUTHORIZATION));
  if (!tokenStr.startsWith("Bearer ")) {
    throw new MissingBearerTokenException();
  }
  String token = tokenStr.substring("Bearer ".length(), tokenStr.length()).trim();
  Optional<ClientAppUserAccessToken> accessToken = clientAppService.verifyAccessToken(token);
  if (!accessToken.isPresent()) {
    throw new InvalidTokenException();
  }
  RequiredScope requiredScope = parameter.getMethodAnnotation(RequiredScope.class);
  if (!accessToken.get().containsScope(requiredScope.value())) {
    throw new InsufficientScopeException(requiredScope.value());
  }
  return accessToken.get();
}
 
Example 2
Source File: MappingJackson2MessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Determine a Jackson serialization view based on the given conversion hint.
 * @param conversionHint the conversion hint Object as passed into the
 * converter for the current conversion attempt
 * @return the serialization view class, or {@code null} if none
 */
@Nullable
protected Class<?> getSerializationView(@Nullable Object conversionHint) {
	if (conversionHint instanceof MethodParameter) {
		MethodParameter methodParam = (MethodParameter) conversionHint;
		JsonView annotation = methodParam.getParameterAnnotation(JsonView.class);
		if (annotation == null) {
			annotation = methodParam.getMethodAnnotation(JsonView.class);
			if (annotation == null) {
				return null;
			}
		}
		return extractViewClass(annotation, conversionHint);
	}
	else if (conversionHint instanceof JsonView) {
		return extractViewClass((JsonView) conversionHint, conversionHint);
	}
	else if (conversionHint instanceof Class) {
		return (Class<?>) conversionHint;
	}
	else {
		return null;
	}
}
 
Example 3
Source File: ParamEncryptRequestBodyAdvice.java    From open-capacity-platform with Apache License 2.0 6 votes vote down vote up
@Override
public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter,
		Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
	try {
		boolean encode = false;
		if (methodParameter.getMethod().isAnnotationPresent(SecurityParameter.class)) {
			SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation(SecurityParameter.class);
			encode = serializedField.inDecode();
		}

		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密");
			 return new ParamEncryptRequestBodyAdvice.DefaultHttpInputMessage(httpInputMessage);
		} else {
			return httpInputMessage;
		}
	} catch (Exception e) {
		log.error(
				"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行解密出现异常:" + e.getMessage());
	}
	 return httpInputMessage;
}
 
Example 4
Source File: JSONPResponseBodyAdvice.java    From uavstack with Apache License 2.0 6 votes vote down vote up
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                              Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
                              ServerHttpResponse response) {

    ResponseJSONP responseJsonp = returnType.getMethodAnnotation(ResponseJSONP.class);
    if(responseJsonp == null){
        responseJsonp = returnType.getContainingClass().getAnnotation(ResponseJSONP.class);
    }

    HttpServletRequest servletRequest = ((ServletServerHttpRequest) request).getServletRequest();
    String callbackMethodName = servletRequest.getParameter(responseJsonp.callback());

    if (!IOUtils.isValidJsonpQueryParam(callbackMethodName)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Invalid jsonp parameter value:" + callbackMethodName);
        }
        callbackMethodName = null;
    }

    JSONPObject jsonpObject = new JSONPObject(callbackMethodName);
    jsonpObject.addParameter(body);
    beforeBodyWriteInternal(jsonpObject, selectedContentType, returnType, request, response);
    return jsonpObject;
}
 
Example 5
Source File: MappingJackson2MessageConverter.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Determine a Jackson serialization view based on the given conversion hint.
 * @param conversionHint the conversion hint Object as passed into the
 * converter for the current conversion attempt
 * @return the serialization view class, or {@code null} if none
 * @since 4.2
 */
@Nullable
protected Class<?> getSerializationView(@Nullable Object conversionHint) {
	if (conversionHint instanceof MethodParameter) {
		MethodParameter param = (MethodParameter) conversionHint;
		JsonView annotation = (param.getParameterIndex() >= 0 ?
				param.getParameterAnnotation(JsonView.class) : param.getMethodAnnotation(JsonView.class));
		if (annotation != null) {
			return extractViewClass(annotation, conversionHint);
		}
	}
	else if (conversionHint instanceof JsonView) {
		return extractViewClass((JsonView) conversionHint, conversionHint);
	}
	else if (conversionHint instanceof Class) {
		return (Class<?>) conversionHint;
	}

	// No JSON view specified...
	return null;
}
 
Example 6
Source File: DecryptRequestBodyAdvice.java    From encrypt-body-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 获取方法控制器上的加密注解信息
 * @param methodParameter 控制器方法
 * @return 加密注解信息
 */
private DecryptAnnotationInfoBean getMethodAnnotation(MethodParameter methodParameter){
    if(methodParameter.getMethod().isAnnotationPresent(DecryptBody.class)){
        DecryptBody decryptBody = methodParameter.getMethodAnnotation(DecryptBody.class);
        return DecryptAnnotationInfoBean.builder()
                .decryptBodyMethod(decryptBody.value())
                .key(decryptBody.otherKey())
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(DESDecryptBody.class)){
        return DecryptAnnotationInfoBean.builder()
                .decryptBodyMethod(DecryptBodyMethod.DES)
                .key(methodParameter.getMethodAnnotation(DESDecryptBody.class).otherKey())
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(AESDecryptBody.class)){
        return DecryptAnnotationInfoBean.builder()
                .decryptBodyMethod(DecryptBodyMethod.AES)
                .key(methodParameter.getMethodAnnotation(AESDecryptBody.class).otherKey())
                .build();
    }
    return null;
}
 
Example 7
Source File: ModelAttributeMethodProcessor.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Return {@code true} if there is a method-level {@code @ModelAttribute}
 * or if it is a non-simple type when {@code annotationNotRequired=true}.
 */
@Override
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;
	}
}
 
Example 8
Source File: RestJsonWrapperAdvice.java    From bird-java with MIT License 5 votes vote down vote up
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> converter) {
    if(methodParameter.getMethodAnnotation(JsonWrapperIgnore.class) != null || methodParameter.getDeclaringClass().isAnnotationPresent(JsonWrapperIgnore.class)){
        return false;
    }
    return methodParameter.getDeclaringClass().getName().startsWith(this.wrapperScanPackage);
}
 
Example 9
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Derive the model attribute name for the given return value using one of:
 * <ol>
 * 	<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 the return type of the method
 * @return the model name, never {@code null} nor empty
 */
public static String getNameForReturnValue(Object returnValue, MethodParameter returnType) {
	ModelAttribute annotation = returnType.getMethodAnnotation(ModelAttribute.class);
	if (annotation != null && StringUtils.hasText(annotation.value())) {
		return annotation.value();
	}
	else {
		Method method = returnType.getMethod();
		Class<?> resolvedType = GenericTypeResolver.resolveReturnType(method, returnType.getContainingClass());
		return Conventions.getVariableNameForReturnType(method, resolvedType, returnValue);
	}
}
 
Example 10
Source File: SecretRequestAdvice.java    From faster-framework-project with Apache License 2.0 5 votes vote down vote up
/**
 * 是否支持加密消息体
 *
 * @param methodParameter methodParameter
 * @return true/false
 */
private boolean supportSecretRequest(MethodParameter methodParameter) {
    Class currentClass = methodParameter.getContainingClass();

    //如果当前类被排除,则不解析
    if (excludeClassList.contains(currentClass.getName())) {
        return false;
    }
    //如果扫描的不是全部,并且当前类不在扫描范围内,排除
    if (!this.isScanAllController && !includeClassList.contains(currentClass.getName())) {
        return false;
    }
    //如果不为注解扫描模式,则返回支持。
    if (!secretProperties.isScanAnnotation()) {
        return true;
    }
    //如果为注解扫描模式,判断
    //类注解
    Annotation classAnnotation = currentClass.getAnnotation(SecretBody.class);
    //方法注解
    SecretBody methodAnnotation = methodParameter.getMethodAnnotation(SecretBody.class);
    //如果类与方法均不存在注解,则排除
    if (classAnnotation == null && methodAnnotation == null) {
        return false;
    }
    //如果当前类的注解含有排除标识,则排除
    if (classAnnotation != null && ((SecretBody) classAnnotation).exclude()) {
        return false;
    }
    //如果当前方法的注解含有排除标识,则排除
    if (methodAnnotation != null && methodAnnotation.exclude()) {
        return false;
    }
    return true;
}
 
Example 11
Source File: EncryptResponseBodyAdvice.java    From encrypt-body-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 获取方法控制器上的加密注解信息
 * @param methodParameter 控制器方法
 * @return 加密注解信息
 */
private EncryptAnnotationInfoBean getMethodAnnotation(MethodParameter methodParameter){
    if(methodParameter.getMethod().isAnnotationPresent(EncryptBody.class)){
        EncryptBody encryptBody = methodParameter.getMethodAnnotation(EncryptBody.class);
        return EncryptAnnotationInfoBean.builder()
                .encryptBodyMethod(encryptBody.value())
                .key(encryptBody.otherKey())
                .shaEncryptType(encryptBody.shaType())
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(MD5EncryptBody.class)){
        return EncryptAnnotationInfoBean.builder()
                .encryptBodyMethod(EncryptBodyMethod.MD5)
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(SHAEncryptBody.class)){
        return EncryptAnnotationInfoBean.builder()
                .encryptBodyMethod(EncryptBodyMethod.SHA)
                .shaEncryptType(methodParameter.getMethodAnnotation(SHAEncryptBody.class).value())
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(DESEncryptBody.class)){
        return EncryptAnnotationInfoBean.builder()
                .encryptBodyMethod(EncryptBodyMethod.DES)
                .key(methodParameter.getMethodAnnotation(DESEncryptBody.class).otherKey())
                .build();
    }
    if(methodParameter.getMethod().isAnnotationPresent(AESEncryptBody.class)){
        return EncryptAnnotationInfoBean.builder()
                .encryptBodyMethod(EncryptBodyMethod.AES)
                .key(methodParameter.getMethodAnnotation(AESEncryptBody.class).otherKey())
                .build();
    }
    return null;
}
 
Example 12
Source File: JsonViewResponseBodyAdvice.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected void beforeBodyWriteInternal(MappingJacksonValue bodyContainer, MediaType contentType,
		MethodParameter returnType, ServerHttpRequest request, ServerHttpResponse response) {

	JsonView ann = returnType.getMethodAnnotation(JsonView.class);
	Assert.state(ann != null, "No JsonView annotation");

	Class<?>[] classes = ann.value();
	if (classes.length != 1) {
		throw new IllegalArgumentException(
				"@JsonView only supported for response body advice with exactly 1 class argument: " + returnType);
	}

	bodyContainer.setSerializationView(classes[0]);
}
 
Example 13
Source File: ParamEncryptResponseBodyAdvice.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@Override
public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType selectedContentType,
		Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
	if (null != body) {

		boolean encode = false;
		if (methodParameter.getMethod()
				.isAnnotationPresent((Class<? extends Annotation>) SecurityParameter.class)) {
			final SecurityParameter serializedField = (SecurityParameter) methodParameter
					.getMethodAnnotation((Class) SecurityParameter.class);
			encode = serializedField.outEncode();
		}
		if (encode) {
			log.info("对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密");
			final ObjectMapper objectMapper = new ObjectMapper();
			try {
				final String result = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(body);
				return DESHelper.encrypt(result);
			} catch (Exception e) {
				log.info(
						"对方法method :【" + methodParameter.getMethod().getName() + "】返回数据进行加密出现异常:" + e.getMessage());
			}
		}
		
	}

	return body;
}
 
Example 14
Source File: ModelFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Derive the model attribute name for the given return value. Results will be
 * based on:
 * <ol>
 * <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);
	}
}
 
Example 15
Source File: PageableMethodArgumentResolver.java    From es with Apache License 2.0 5 votes vote down vote up
private PageableDefaults getPageableDefaults(MethodParameter parameter) {
    //首先从参数上找
    PageableDefaults pageableDefaults = parameter.getParameterAnnotation(PageableDefaults.class);
    //找不到从方法上找
    if (pageableDefaults == null) {
        pageableDefaults = parameter.getMethodAnnotation(PageableDefaults.class);
    }
    return pageableDefaults;
}
 
Example 16
Source File: AbstractJackson2Encoder.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected <A extends Annotation> A getAnnotation(MethodParameter parameter, Class<A> annotType) {
	return parameter.getMethodAnnotation(annotType);
}
 
Example 17
Source File: JsonBodyReturnValueProcessor.java    From rocket-console with Apache License 2.0 4 votes vote down vote up
public boolean supportsReturnType(MethodParameter returnType) {
    return returnType.getMethodAnnotation(JsonBody.class) != null;
}
 
Example 18
Source File: HandlerMethodUtils.java    From spring-webmvc-support with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Find {@link Annotation} from {@link MethodParameter method parameter or method return type}
 *
 * @param methodParameter {@link MethodParameter method parameter or method return type}
 * @param annotationClass {@link Annotation} type
 * @param <A>             {@link Annotation} type
 * @return {@link Annotation} If found , return <code>null</code>
 */
public static <A extends Annotation> A findAnnotation(MethodParameter methodParameter, Class<A> annotationClass) {

    A annotation = null;

    boolean isReturnType = methodParameter.getParameterIndex() < 0;

    if (isReturnType) {

        annotation = methodParameter.getMethodAnnotation(annotationClass);

    } else { // is parameter

        annotation = methodParameter.getParameterAnnotation(annotationClass);

    }


    return annotation;

}
 
Example 19
Source File: JsonViewResponseBodyAdvice.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
	return (super.supports(returnType, converterType) && returnType.getMethodAnnotation(JsonView.class) != null);
}
 
Example 20
Source File: SubscriptionMethodReturnValueHandler.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public boolean supportsReturnType(MethodParameter returnType) {
	return (returnType.getMethodAnnotation(SubscribeMapping.class) != null &&
			returnType.getMethodAnnotation(SendTo.class) == null &&
			returnType.getMethodAnnotation(SendToUser.class) == null);
}