Java Code Examples for org.springframework.core.annotation.AnnotatedElementUtils

The following examples show how to use org.springframework.core.annotation.AnnotatedElementUtils. These examples are extracted from open source projects. 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
/**
 * Retrieve the {@link TransactionConfigurationAttributes} for the
 * supplied {@link TestContext} whose {@linkplain Class test class}
 * may optionally declare or inherit
 * {@link TransactionConfiguration @TransactionConfiguration}.
 * <p>If {@code @TransactionConfiguration} is not present for the
 * supplied {@code TestContext}, a default instance of
 * {@code TransactionConfigurationAttributes} will be used instead.
 * @param testContext the test context for which the configuration
 * attributes should be retrieved
 * @return the TransactionConfigurationAttributes instance for this listener,
 * potentially cached
 * @see TransactionConfigurationAttributes#TransactionConfigurationAttributes()
 */
@SuppressWarnings("deprecation")
TransactionConfigurationAttributes retrieveConfigurationAttributes(TestContext testContext) {
	if (this.configurationAttributes == null) {
		Class<?> clazz = testContext.getTestClass();

		TransactionConfiguration txConfig = AnnotatedElementUtils.findMergedAnnotation(clazz,
			TransactionConfiguration.class);
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("Retrieved @TransactionConfiguration [%s] for test class [%s].",
				txConfig, clazz.getName()));
		}

		TransactionConfigurationAttributes configAttributes = (txConfig == null ? defaultTxConfigAttributes
				: new TransactionConfigurationAttributes(txConfig.transactionManager(), txConfig.defaultRollback()));

		if (logger.isDebugEnabled()) {
			logger.debug(String.format("Using TransactionConfigurationAttributes %s for test class [%s].",
				configAttributes, clazz.getName()));
		}
		this.configurationAttributes = configAttributes;
	}
	return this.configurationAttributes;
}
 
Example 2
/**
 * Perform the actual work for {@link #beforeTestClass} and {@link #afterTestClass}
 * by dirtying the context if appropriate (i.e., according to the required mode).
 * @param testContext the test context whose application context should
 * potentially be marked as dirty; never {@code null}
 * @param requiredClassMode the class mode required for a context to
 * be marked dirty in the current phase; never {@code null}
 * @throws Exception allows any exception to propagate
 * @since 4.2
 * @see #dirtyContext
 */
protected void beforeOrAfterTestClass(TestContext testContext, ClassMode requiredClassMode) throws Exception {
	Assert.notNull(testContext, "TestContext must not be null");
	Assert.notNull(requiredClassMode, "requiredClassMode must not be null");

	Class<?> testClass = testContext.getTestClass();
	Assert.notNull(testClass, "The test class of the supplied TestContext must not be null");

	DirtiesContext dirtiesContext = AnnotatedElementUtils.findMergedAnnotation(testClass, DirtiesContext.class);
	boolean classAnnotated = (dirtiesContext != null);
	ClassMode classMode = (classAnnotated ? dirtiesContext.classMode() : null);

	if (logger.isDebugEnabled()) {
		String phase = (requiredClassMode.name().startsWith("BEFORE") ? "Before" : "After");
		logger.debug(String.format(
			"%s test class: context %s, class annotated with @DirtiesContext [%s] with mode [%s].", phase,
			testContext, classAnnotated, classMode));
	}

	if (classMode == requiredClassMode) {
		dirtyContext(testContext, dirtiesContext.hierarchyMode());
	}
}
 
Example 3
Source Project: RestDoc   Source File: SpringMethodFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean isSupport(Method method) {
    if (method.isSynthetic() || method.isBridge())
        return false;



    // 如果方法和类上都没有ResponseBody,返回false
    if (!AnnotatedElementUtils.hasAnnotation(method, ResponseBody.class) &&
        !AnnotatedElementUtils.hasAnnotation(method.getDeclaringClass(), ResponseBody.class))
    {
            return false;
    }
    var annotations = method.getAnnotations();
    for (var annotation : annotations) {
        var annotationType = annotation.annotationType();

        if (_classes.contains(annotationType))
            return true;
    }
    return false;
}
 
Example 4
/**
 * Determine whether or not to rollback transactions for the supplied
 * {@linkplain TestContext test context} by taking into consideration the
 * {@linkplain #isDefaultRollback(TestContext) default rollback} flag and a
 * possible method-level override via the {@link Rollback @Rollback}
 * annotation.
 * @param testContext the test context for which the rollback flag
 * should be retrieved
 * @return the <em>rollback</em> flag for the supplied test context
 * @throws Exception if an error occurs while determining the rollback flag
 */
protected final boolean isRollback(TestContext testContext) throws Exception {
	boolean rollback = isDefaultRollback(testContext);
	Rollback rollbackAnnotation =
			AnnotatedElementUtils.findMergedAnnotation(testContext.getTestMethod(), Rollback.class);
	if (rollbackAnnotation != null) {
		boolean rollbackOverride = rollbackAnnotation.value();
		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
					"Method-level @Rollback(%s) overrides default rollback [%s] for test context %s.",
					rollbackOverride, rollback, testContext));
		}
		rollback = rollbackOverride;
	}
	else {
		if (logger.isDebugEnabled()) {
			logger.debug(String.format(
					"No method-level @Rollback override: using default rollback [%s] for test context %s.",
					rollback, testContext));
		}
	}
	return rollback;
}
 
Example 5
@Override
public Set<MethodMetadata> getAnnotatedMethods(String annotationName) {
	try {
		Method[] methods = getIntrospectedClass().getDeclaredMethods();
		Set<MethodMetadata> annotatedMethods = new LinkedHashSet<MethodMetadata>();
		for (Method method : methods) {
			if (!method.isBridge() && method.getAnnotations().length > 0 &&
					AnnotatedElementUtils.isAnnotated(method, annotationName)) {
				annotatedMethods.add(new StandardMethodMetadata(method, this.nestedAnnotationsAsMap));
			}
		}
		return annotatedMethods;
	}
	catch (Throwable ex) {
		throw new IllegalStateException("Failed to introspect annotated methods on " + getIntrospectedClass(), ex);
	}
}
 
Example 6
@Override
public final Object postProcessAfterInitialization(Object bean, final String beanName)
		throws BeansException {
	Class<?> targetClass = AopUtils.isAopProxy(bean) ? AopUtils.getTargetClass(bean)
			: bean.getClass();
	Method[] uniqueDeclaredMethods = ReflectionUtils
			.getUniqueDeclaredMethods(targetClass);
	for (Method method : uniqueDeclaredMethods) {
		StreamListener streamListener = AnnotatedElementUtils
				.findMergedAnnotation(method, StreamListener.class);
		if (streamListener != null && !method.isBridge()) {
			this.streamListenerPresent = true;
			this.streamListenerCallbacks.add(() -> {
				Assert.isTrue(method.getAnnotation(Input.class) == null,
						StreamListenerErrorMessages.INPUT_AT_STREAM_LISTENER);
				this.doPostProcess(streamListener, method, bean);
			});
		}
	}
	return bean;
}
 
Example 7
Source Project: albedo   Source File: ClassUtil.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 获取Annotation
 *
 * @param method         Method
 * @param annotationType 注解类
 * @param <A>            泛型标记
 * @return {Annotation}
 */
public <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
	Class<?> targetClass = method.getDeclaringClass();
	// The method may be on an interface, but we need attributes from the target class.
	// If the target class is null, the method will be unchanged.
	Method specificMethod = ClassUtil.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	// 先找方法,再找方法上的类
	A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
	if (null != annotation) {
		return annotation;
	}
	// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
	return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), annotationType);
}
 
Example 8
Source Project: spring4-understanding   Source File: CrossOriginTests.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
	RequestMapping annotation = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (annotation != null) {
		return new RequestMappingInfo(
				new PatternsRequestCondition(annotation.value(), getUrlPathHelper(), getPathMatcher(), true, true),
				new RequestMethodsRequestCondition(annotation.method()),
				new ParamsRequestCondition(annotation.params()),
				new HeadersRequestCondition(annotation.headers()),
				new ConsumesRequestCondition(annotation.consumes(), annotation.headers()),
				new ProducesRequestCondition(annotation.produces(), annotation.headers()), null);
	}
	else {
		return null;
	}
}
 
Example 9
@Override
protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
	HandlerMethod handlerMethod = createHandlerMethod(handler, method);
	CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), CrossOrigin.class);
	CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);

	if (typeAnnotation == null && methodAnnotation == null) {
		return null;
	}

	CorsConfiguration config = new CorsConfiguration();
	updateCorsConfig(config, typeAnnotation);
	updateCorsConfig(config, methodAnnotation);

	if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
		for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
			config.addAllowedMethod(allowedMethod.name());
		}
	}
	return config.applyPermitDefaultValues();
}
 
Example 10
Source Project: spring-analysis-note   Source File: ProfileValueChecker.java    License: MIT License 6 votes vote down vote up
/**
 * Determine if the test specified by arguments to the
 * {@linkplain #ProfileValueChecker constructor} is <em>enabled</em> in
 * the current environment, as configured via the {@link IfProfileValue
 * &#064;IfProfileValue} annotation.
 * <p>If the test is not annotated with {@code @IfProfileValue} it is
 * considered enabled.
 * <p>If a test is not enabled, this method will abort further evaluation
 * of the execution chain with a failed assumption; otherwise, this method
 * will simply evaluate the next {@link Statement} in the execution chain.
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Class)
 * @see ProfileValueUtils#isTestEnabledInThisEnvironment(Method, Class)
 * @throws AssumptionViolatedException if the test is disabled
 * @throws Throwable if evaluation of the next statement fails
 */
@Override
public void evaluate() throws Throwable {
	if (this.testMethod == null) {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testClass)) {
			Annotation ann = AnnotatedElementUtils.findMergedAnnotation(this.testClass, IfProfileValue.class);
			throw new AssumptionViolatedException(String.format(
					"Profile configured via [%s] is not enabled in this environment for test class [%s].",
					ann, this.testClass.getName()));
		}
	}
	else {
		if (!ProfileValueUtils.isTestEnabledInThisEnvironment(this.testMethod, this.testClass)) {
			throw new AssumptionViolatedException(String.format(
					"Profile configured via @IfProfileValue is not enabled in this environment for test method [%s].",
					this.testMethod));
		}
	}

	this.next.evaluate();
}
 
Example 11
@Override
@Nullable
protected ModelAndView doResolveException(
		HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

	try {
		if (ex instanceof ResponseStatusException) {
			return resolveResponseStatusException((ResponseStatusException) ex, request, response, handler);
		}

		ResponseStatus status = AnnotatedElementUtils.findMergedAnnotation(ex.getClass(), ResponseStatus.class);
		if (status != null) {
			return resolveResponseStatus(status, request, response, handler, ex);
		}

		if (ex.getCause() instanceof Exception) {
			return doResolveException(request, response, handler, (Exception) ex.getCause());
		}
	}
	catch (Exception resolveEx) {
		if (logger.isWarnEnabled()) {
			logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", resolveEx);
		}
	}
	return null;
}
 
Example 12
private HandlerMethod getMethodHandlerMethodFunction(Object consumer, Method method) {
    final EventMapping mapping = AnnotatedElementUtils.getMergedAnnotation(method, EventMapping.class);
    if (mapping == null) {
        return null;
    }

    Preconditions.checkState(method.getParameterCount() == 1,
                             "Number of parameter should be 1. But {}",
                             (Object[]) method.getParameterTypes());
    // TODO: Support more than 1 argument. Like MVC's argument resolver?

    final Type type = method.getGenericParameterTypes()[0];

    final Predicate<Event> predicate = new EventPredicate(type);
    return new HandlerMethod(predicate, consumer, method, getPriority(mapping, type));
}
 
Example 13
/**
 * Customize method parameter [ ].
 *
 * @param pNames the p names
 * @param parameters the parameters
 * @return the method parameter [ ]
 */
public static MethodParameter[] customize(String[] pNames, MethodParameter[] parameters) {
	List<MethodParameter> explodedParameters = new ArrayList<>();
	for (int i = 0; i < parameters.length; ++i) {
		MethodParameter p = parameters[i];
		Class<?> paramClass = AdditionalModelsConverter.getReplacement(p.getParameterType());
		if (p.hasParameterAnnotation(ParameterObject.class) || AnnotatedElementUtils.isAnnotated(paramClass, ParameterObject.class)) {
			MethodParameterPojoExtractor.extractFrom(paramClass).forEach(explodedParameters::add);
		}
		else {
			String name = pNames != null ? pNames[i] : p.getParameterName();
			explodedParameters.add(new DelegatingMethodParameter(p, name, null,false));
		}
	}
	return explodedParameters.toArray(new MethodParameter[0]);
}
 
Example 14
void resolveListenerMethod() {
    context.getBeansWithAnnotation(RocketMQListener.class).forEach((beanName, obj) -> {
        Map<Method, RocketMQMessage> annotatedMethods = MethodIntrospector.selectMethods(obj.getClass(),
                (MethodIntrospector.MetadataLookup<RocketMQMessage>) method -> AnnotatedElementUtils
                        .findMergedAnnotation(method, RocketMQMessage.class));
        initSubscriptionGroup(annotatedMethods, obj);
    });
    this.initSubscription = true;
}
 
Example 15
Source Project: mica   Source File: ClassUtil.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 判断是否有注解 Annotation
 *
 * @param method         Method
 * @param annotationType 注解类
 * @param <A>            泛型标记
 * @return {boolean}
 */
public static <A extends Annotation> boolean isAnnotated(Method method, Class<A> annotationType) {
	// 先找方法,再找方法上的类
	boolean isMethodAnnotated = AnnotatedElementUtils.isAnnotated(method, annotationType);
	if (isMethodAnnotated) {
		return true;
	}
	// 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
	Class<?> targetClass = method.getDeclaringClass();
	return AnnotatedElementUtils.isAnnotated(targetClass, annotationType);
}
 
Example 16
/**
 * Determine a suggested value from any of the given candidate annotations.
 */
@Nullable
protected Object findValue(Annotation[] annotationsToSearch) {
	if (annotationsToSearch.length > 0) {   // qualifier annotations have to be local
		AnnotationAttributes attr = AnnotatedElementUtils.getMergedAnnotationAttributes(
				AnnotatedElementUtils.forAnnotations(annotationsToSearch), this.valueAnnotationType);
		if (attr != null) {
			return extractValue(attr);
		}
	}
	return null;
}
 
Example 17
private static String getMethodRequestMapping(Method method) {
	Assert.notNull(method, "'method' must not be null");
	RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	if (requestMapping == null) {
		throw new IllegalArgumentException("No @RequestMapping on: " + method.toGenericString());
	}
	String[] paths = requestMapping.path();
	if (ObjectUtils.isEmpty(paths) || StringUtils.isEmpty(paths[0])) {
		return "/";
	}
	if (paths.length > 1 && logger.isWarnEnabled()) {
		logger.warn("Multiple paths on method " + method.toGenericString() + ", using first one");
	}
	return paths[0];
}
 
Example 18
private void applyPropertiesFromAnnotation(TestContext testContext, String annotationName) {
  Class<?> testClass = testContext.getTestClass();
  if (AnnotatedElementUtils.isAnnotated(testClass, annotationName)) {
    AnnotationAttributes annotationAttributes = AnnotatedElementUtils.getAnnotationAttributes(testClass,
        annotationName);
    addPropertySourceProperties(testContext, annotationAttributes.getStringArray("value"));
  }
}
 
Example 19
Source Project: venus-cloud-feign   Source File: VenusSpringMvcContract.java    License: Apache License 2.0 5 votes vote down vote up
private String defaultValue(Method method, String pathVariable) {
    Set<ApiImplicitParam> apiImplicitParams = AnnotatedElementUtils.findAllMergedAnnotations(method, ApiImplicitParam.class);
    for (ApiImplicitParam apiImplicitParam : apiImplicitParams) {
        if (pathVariable.equals(apiImplicitParam.name())) {
            return apiImplicitParam.allowableValues().split(",")[0].trim();
        }
    }
    throw new IllegalArgumentException("no default value for " + pathVariable);
}
 
Example 20
/**
 * Determine a suggested value from any of the given candidate annotations.
 */
@Nullable
protected Object findValue(Annotation[] annotationsToSearch) {
	if (annotationsToSearch.length > 0) {   // qualifier annotations have to be local
		AnnotationAttributes attr = AnnotatedElementUtils.getMergedAnnotationAttributes(
				AnnotatedElementUtils.forAnnotations(annotationsToSearch), this.valueAnnotationType);
		if (attr != null) {
			return extractValue(attr);
		}
	}
	return null;
}
 
Example 21
Source Project: onetwo   Source File: FixFeignClientsHandlerMapping.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isHandler(Class<?> beanType) {
	//避免springmvc 把抽象出来的带有RequestMapping注解的client接口扫描到controller注册
	boolean isFeignClient = AnnotatedElementUtils.hasAnnotation(beanType, FeignClient.class);
	if(BootCloudUtils.isNetflixFeignClientPresent() && isFeignClient){
		if(log.isInfoEnabled()){
			log.info("ignore FeignClient: {}", beanType);
		}
		return false;
	}
	return super.isHandler(beanType);
}
 
Example 22
Source Project: java-technology-stack   Source File: WebTestContextBootstrapper.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a {@link WebMergedContextConfiguration} if the test class in the
 * supplied {@code MergedContextConfiguration} is annotated with
 * {@link WebAppConfiguration @WebAppConfiguration} and otherwise returns
 * the supplied instance unmodified.
 */
@Override
protected MergedContextConfiguration processMergedContextConfiguration(MergedContextConfiguration mergedConfig) {
	WebAppConfiguration webAppConfiguration =
			AnnotatedElementUtils.findMergedAnnotation(mergedConfig.getTestClass(), WebAppConfiguration.class);
	if (webAppConfiguration != null) {
		return new WebMergedContextConfiguration(mergedConfig, webAppConfiguration.value());
	}
	else {
		return mergedConfig;
	}
}
 
Example 23
Source Project: java-technology-stack   Source File: MvcAnnotationPredicates.java    License: MIT License 5 votes vote down vote up
@Override
public boolean test(Method method) {
	RequestMapping annot = AnnotatedElementUtils.findMergedAnnotation(method, RequestMapping.class);
	return annot != null &&
			Arrays.equals(this.path, annot.path()) &&
			Arrays.equals(this.method, annot.method()) &&
			(this.params == null || Arrays.equals(this.params, annot.params()));
}
 
Example 24
@Nullable
private RequestMappingInfo getApiVersionMappingInfo(Method method, Class<?> handlerType) {
	// url 上的版本,优先获取方法上的版本
	UrlVersion urlVersion = AnnotatedElementUtils.findMergedAnnotation(method, UrlVersion.class);
	// 再次尝试类上的版本
	if (urlVersion == null || StringUtil.isBlank(urlVersion.value())) {
		urlVersion = AnnotatedElementUtils.findMergedAnnotation(handlerType, UrlVersion.class);
	}
	// Media Types 版本信息
	ApiVersion apiVersion = AnnotatedElementUtils.findMergedAnnotation(method, ApiVersion.class);
	// 再次尝试类上的版本
	if (apiVersion == null || StringUtil.isBlank(apiVersion.value())) {
		apiVersion = AnnotatedElementUtils.findMergedAnnotation(handlerType, ApiVersion.class);
	}
	boolean nonUrlVersion = urlVersion == null || StringUtil.isBlank(urlVersion.value());
	boolean nonApiVersion = apiVersion == null || StringUtil.isBlank(apiVersion.value());
	// 先判断同时不纯在
	if (nonUrlVersion && nonApiVersion) {
		return null;
	}
	// 如果 header 版本不存在
	RequestMappingInfo.Builder mappingInfoBuilder = null;
	if (nonApiVersion) {
		mappingInfoBuilder = RequestMappingInfo.paths(urlVersion.value());
	} else {
		mappingInfoBuilder = RequestMappingInfo.paths(StringPool.EMPTY);
	}
	// 如果url版本不存在
	if (nonUrlVersion) {
		String vsersionMediaTypes = new BladeMediaType(apiVersion.value()).toString();
		mappingInfoBuilder.produces(vsersionMediaTypes);
	}
	return mappingInfoBuilder.build();
}
 
Example 25
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	if (bean instanceof AopInfrastructureBean || bean instanceof JmsListenerContainerFactory ||
			bean instanceof JmsListenerEndpointRegistry) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}

	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
	if (!this.nonAnnotatedClasses.contains(targetClass)) {
		Map<Method, Set<JmsListener>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
				(MethodIntrospector.MetadataLookup<Set<JmsListener>>) method -> {
					Set<JmsListener> listenerMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
							method, JmsListener.class, JmsListeners.class);
					return (!listenerMethods.isEmpty() ? listenerMethods : null);
				});
		if (annotatedMethods.isEmpty()) {
			this.nonAnnotatedClasses.add(targetClass);
			if (logger.isTraceEnabled()) {
				logger.trace("No @JmsListener annotations found on bean type: " + targetClass);
			}
		}
		else {
			// Non-empty set of methods
			annotatedMethods.forEach((method, listeners) ->
					listeners.forEach(listener -> processJmsListener(listener, method, bean)));
			if (logger.isDebugEnabled()) {
				logger.debug(annotatedMethods.size() + " @JmsListener methods processed on bean '" + beanName +
						"': " + annotatedMethods);
			}
		}
	}
	return bean;
}
 
Example 26
Source Project: spring-cloud-sockets   Source File: ServiceMethodInfo.java    License: Apache License 2.0 5 votes vote down vote up
public ServiceMethodInfo(Method method) {
	this.method = method;
	ReactiveSocket annotated = AnnotatedElementUtils.findMergedAnnotation(method, ReactiveSocket.class);
	if(annotated == null){
		throw new IllegalStateException("Service methods must be annotated with a one of {@OneWayMapping, @RequestOneMapping, @RequestManyMapping, @RequestStreamMapping} ");
	}
	this.mappingInfo = new ServiceMappingInfo(annotated.value(), annotated.mimeType(), annotated.exchangeMode());
	this.returnType = ResolvableType.forMethodReturnType(method);
	findPayloadParameter();
	validate();

}
 
Example 27
@Override
protected void processAnnotationOnMethod(MethodMetadata data, Annotation methodAnnotation, Method method) {
	if (RequestMapping.class.isInstance(methodAnnotation) || methodAnnotation.annotationType().isAnnotationPresent(RequestMapping.class)) {
		Class<?> targetType = method.getDeclaringClass();
		// url 上的版本,优先获取方法上的版本
		UrlVersion urlVersion = AnnotatedElementUtils.findMergedAnnotation(method, UrlVersion.class);
		// 再次尝试类上的版本
		if (urlVersion == null || StringUtil.isBlank(urlVersion.value())) {
			urlVersion = AnnotatedElementUtils.findMergedAnnotation(targetType, UrlVersion.class);
		}
		if (urlVersion != null && StringUtil.isNotBlank(urlVersion.value())) {
			String versionUrl = "/" + urlVersion.value();
			data.template().uri(versionUrl);
		}

		// 注意:在父类之前 添加 url版本,在父类之后,处理 Media Types 版本
		super.processAnnotationOnMethod(data, methodAnnotation, method);

		// 处理 Media Types 版本信息
		ApiVersion apiVersion = AnnotatedElementUtils.findMergedAnnotation(method, ApiVersion.class);
		// 再次尝试类上的版本
		if (apiVersion == null || StringUtil.isBlank(apiVersion.value())) {
			apiVersion = AnnotatedElementUtils.findMergedAnnotation(targetType, ApiVersion.class);
		}
		if (apiVersion != null && StringUtil.isNotBlank(apiVersion.value())) {
			BladeMediaType BladeMediaType = new BladeMediaType(apiVersion.value());
			data.template().header(HttpHeaders.ACCEPT, BladeMediaType.toString());
		}
	}
}
 
Example 28
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) {
	if (bean instanceof AopInfrastructureBean || bean instanceof TaskScheduler ||
			bean instanceof ScheduledExecutorService) {
		// Ignore AOP infrastructure such as scoped proxies.
		return bean;
	}

	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
	if (!this.nonAnnotatedClasses.contains(targetClass) &&
			AnnotationUtils.isCandidateClass(targetClass, Arrays.asList(Scheduled.class, Schedules.class))) {
		Map<Method, Set<Scheduled>> annotatedMethods = MethodIntrospector.selectMethods(targetClass,
				(MethodIntrospector.MetadataLookup<Set<Scheduled>>) method -> {
					Set<Scheduled> scheduledMethods = AnnotatedElementUtils.getMergedRepeatableAnnotations(
							method, Scheduled.class, Schedules.class);
					return (!scheduledMethods.isEmpty() ? scheduledMethods : null);
				});
		if (annotatedMethods.isEmpty()) {
			this.nonAnnotatedClasses.add(targetClass);
			if (logger.isTraceEnabled()) {
				logger.trace("No @Scheduled annotations found on bean class: " + targetClass);
			}
		}
		else {
			// Non-empty set of methods
			annotatedMethods.forEach((method, scheduledMethods) ->
					scheduledMethods.forEach(scheduled -> processScheduled(scheduled, method, bean)));
			if (logger.isTraceEnabled()) {
				logger.trace(annotatedMethods.size() + " @Scheduled methods processed on bean '" + beanName +
						"': " + annotatedMethods);
			}
		}
	}
	return bean;
}
 
Example 29
/**
 * Return the qualifier or bean name of the executor to be used when executing the
 * given method, specified via {@link Async#value} at the method or declaring
 * class level. If {@code @Async} is specified at both the method and class level, the
 * method's {@code #value} takes precedence (even if empty string, indicating that
 * the default executor should be used preferentially).
 * @param method the method to inspect for executor qualifier metadata
 * @return the qualifier if specified, otherwise empty string indicating that the
 * {@linkplain #setExecutor(Executor) default executor} should be used
 * @see #determineAsyncExecutor(Method)
 */
@Override
@Nullable
protected String getExecutorQualifier(Method method) {
	// Maintainer's note: changes made here should also be made in
	// AnnotationAsyncExecutionAspect#getExecutorQualifier
	Async async = AnnotatedElementUtils.findMergedAnnotation(method, Async.class);
	if (async == null) {
		async = AnnotatedElementUtils.findMergedAnnotation(method.getDeclaringClass(), Async.class);
	}
	return (async != null ? async.value() : null);
}
 
Example 30
Source Project: springdoc-openapi   Source File: SecurityParser.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get security requirements io . swagger . v 3 . oas . annotations . security . security requirement [ ].
 *
 * @param method the method
 * @return the io . swagger . v 3 . oas . annotations . security . security requirement [ ]
 */
public io.swagger.v3.oas.annotations.security.SecurityRequirement[] getSecurityRequirements(
		HandlerMethod method) {
	// class SecurityRequirements
	io.swagger.v3.oas.annotations.security.SecurityRequirements classSecurity = AnnotatedElementUtils.findMergedAnnotation(method.getBeanType(), io.swagger.v3.oas.annotations.security.SecurityRequirements.class);
	// method SecurityRequirements
	io.swagger.v3.oas.annotations.security.SecurityRequirements methodSecurity = AnnotatedElementUtils.findMergedAnnotation(method.getMethod(), io.swagger.v3.oas.annotations.security.SecurityRequirements.class);

	Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> allSecurityTags = null;

	if (classSecurity != null)
		allSecurityTags = new HashSet<>(Arrays.asList(classSecurity.value()));
	if (methodSecurity != null)
		allSecurityTags = addSecurityRequirements(allSecurityTags, new HashSet<>(Arrays.asList(methodSecurity.value())));

	if (CollectionUtils.isEmpty(allSecurityTags)) {
		// class SecurityRequirement
		Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> securityRequirementsClassList = AnnotatedElementUtils.findMergedRepeatableAnnotations(
				method.getBeanType(),
				io.swagger.v3.oas.annotations.security.SecurityRequirement.class);
		// method SecurityRequirement
		Set<io.swagger.v3.oas.annotations.security.SecurityRequirement> securityRequirementsMethodList = AnnotatedElementUtils.findMergedRepeatableAnnotations(method.getMethod(),
				io.swagger.v3.oas.annotations.security.SecurityRequirement.class);
		if (!CollectionUtils.isEmpty(securityRequirementsClassList))
			allSecurityTags = addSecurityRequirements(allSecurityTags, securityRequirementsClassList);
		if (!CollectionUtils.isEmpty(securityRequirementsMethodList))
			allSecurityTags = addSecurityRequirements(allSecurityTags, securityRequirementsMethodList);
	}

	return (allSecurityTags != null) ? allSecurityTags.toArray(new io.swagger.v3.oas.annotations.security.SecurityRequirement[0]) : null;
}