Java Code Examples for org.springframework.aop.framework.AopProxyUtils

The following examples show how to use org.springframework.aop.framework.AopProxyUtils. 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
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
    if (this.nonAnnotatedClasses.contains(targetClass)) return bean;
    Method[] methods = ReflectionUtils.getAllDeclaredMethods(bean.getClass());
    if (methods == null) return bean;
    for (Method method : methods) {
        DcsScheduled dcsScheduled = AnnotationUtils.findAnnotation(method, DcsScheduled.class);
        if (null == dcsScheduled || 0 == method.getDeclaredAnnotations().length) continue;
        List<ExecOrder> execOrderList = Constants.execOrderMap.computeIfAbsent(beanName, k -> new ArrayList<>());
        ExecOrder execOrder = new ExecOrder();
        execOrder.setBean(bean);
        execOrder.setBeanName(beanName);
        execOrder.setMethodName(method.getName());
        execOrder.setDesc(dcsScheduled.desc());
        execOrder.setCron(dcsScheduled.cron());
        execOrder.setAutoStartup(dcsScheduled.autoStartup());
        execOrderList.add(execOrder);
        this.nonAnnotatedClasses.add(targetClass);
    }
    return bean;
}
 
Example 2
Source Project: spring-analysis-note   Source File: BeanValidationPostProcessor.java    License: MIT License 6 votes vote down vote up
/**
 * Perform validation of the given bean.
 * @param bean the bean instance to validate
 * @see javax.validation.Validator#validate
 */
protected void doValidate(Object bean) {
	Assert.state(this.validator != null, "No Validator set");
	Object objectToValidate = AopProxyUtils.getSingletonTarget(bean);
	if (objectToValidate == null) {
		objectToValidate = bean;
	}
	Set<ConstraintViolation<Object>> result = this.validator.validate(objectToValidate);

	if (!result.isEmpty()) {
		StringBuilder sb = new StringBuilder("Bean state is invalid: ");
		for (Iterator<ConstraintViolation<Object>> it = result.iterator(); it.hasNext();) {
			ConstraintViolation<Object> violation = it.next();
			sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
			if (it.hasNext()) {
				sb.append("; ");
			}
		}
		throw new BeanInitializationException(sb.toString());
	}
}
 
Example 3
private void processRaftService(Object bean, String beanName) {

        final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);

        RaftService raftServiceAnnotation = beanClass.getAnnotation(RaftService.class);

        if (raftServiceAnnotation == null) {
            return;
        }

        Class<?> interfaceType = raftServiceAnnotation.interfaceType();

        if (interfaceType.equals(void.class)) {
            Class<?>[] interfaces = beanClass.getInterfaces();

            if (interfaces == null || interfaces.length == 0 || interfaces.length > 1) {
                throw new RuntimeException(
                    "Bean " + beanName
                            + " does not has any interface or has more than one interface.");
            }

            interfaceType = interfaces[0];
        }
        String serviceUniqueId = getServiceId(interfaceType, raftServiceAnnotation.uniqueId());
        Processor.getInstance().addWorker(serviceUniqueId, interfaceType, bean);
    }
 
Example 4
/**
 * Perform validation of the given bean.
 * @param bean the bean instance to validate
 * @see javax.validation.Validator#validate
 */
protected void doValidate(Object bean) {
	Assert.state(this.validator != null, "No Validator set");
	Object objectToValidate = AopProxyUtils.getSingletonTarget(bean);
	if (objectToValidate == null) {
		objectToValidate = bean;
	}
	Set<ConstraintViolation<Object>> result = this.validator.validate(objectToValidate);

	if (!result.isEmpty()) {
		StringBuilder sb = new StringBuilder("Bean state is invalid: ");
		for (Iterator<ConstraintViolation<Object>> it = result.iterator(); it.hasNext();) {
			ConstraintViolation<Object> violation = it.next();
			sb.append(violation.getPropertyPath()).append(" - ").append(violation.getMessage());
			if (it.hasNext()) {
				sb.append("; ");
			}
		}
		throw new BeanInitializationException(sb.toString());
	}
}
 
Example 5
private MethodParameter getMethodParameter() {
    Class<?> targetClass;
    if (rocketMQListener != null) {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQListener);
    } else {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQReplyListener);
    }
    Type messageType = this.getMessageType();
    Class clazz = null;
    if (messageType instanceof ParameterizedType && messageConverter instanceof SmartMessageConverter) {
        clazz = (Class) ((ParameterizedType) messageType).getRawType();
    } else if (messageType instanceof Class) {
        clazz = (Class) messageType;
    } else {
        throw new RuntimeException("parameterType:" + messageType + " of onMessage method is not supported");
    }
    try {
        final Method method = targetClass.getMethod("onMessage", clazz);
        return new MethodParameter(method, 0);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
        throw new RuntimeException("parameterType:" + messageType + " of onMessage method is not supported");
    }
}
 
Example 6
private void registerTemplate(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (!RocketMQTemplate.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " is not instance of " + RocketMQTemplate.class.getName());
    }

    ExtRocketMQTemplateConfiguration annotation = clazz.getAnnotation(ExtRocketMQTemplateConfiguration.class);
    GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext;
    validate(annotation, genericApplicationContext);

    DefaultMQProducer mqProducer = createProducer(annotation);
    // Set instanceName same as the beanName
    mqProducer.setInstanceName(beanName);
    try {
        mqProducer.start();
    } catch (MQClientException e) {
        throw new BeanDefinitionValidationException(String.format("Failed to startup MQProducer for RocketMQTemplate {}",
            beanName), e);
    }
    RocketMQTemplate rocketMQTemplate = (RocketMQTemplate) bean;
    rocketMQTemplate.setProducer(mqProducer);
    rocketMQTemplate.setMessageConverter(rocketMQMessageConverter.getMessageConverter());
    log.info("Set real producer to :{} {}", beanName, annotation.value());
}
 
Example 7
private void registerTransactionListener(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (!RocketMQLocalTransactionListener.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " is not instance of " + RocketMQLocalTransactionListener.class.getName());
    }
    RocketMQTransactionListener annotation = clazz.getAnnotation(RocketMQTransactionListener.class);
    RocketMQTemplate rocketMQTemplate = (RocketMQTemplate) applicationContext.getBean(annotation.rocketMQTemplateBeanName());
    if (((TransactionMQProducer) rocketMQTemplate.getProducer()).getTransactionListener() != null) {
        throw new IllegalStateException(annotation.rocketMQTemplateBeanName() + " already exists RocketMQLocalTransactionListener");
    }
    ((TransactionMQProducer) rocketMQTemplate.getProducer()).setExecutorService(new ThreadPoolExecutor(annotation.corePoolSize(), annotation.maximumPoolSize(),
        annotation.keepAliveTime(), TimeUnit.MILLISECONDS, new LinkedBlockingDeque<>(annotation.blockingQueueSize())));
    ((TransactionMQProducer) rocketMQTemplate.getProducer()).setTransactionListener(RocketMQUtil.convert((RocketMQLocalTransactionListener) bean));
    log.debug("RocketMQLocalTransactionListener {} register to {} success", clazz.getName(), annotation.rocketMQTemplateBeanName());
}
 
Example 8
Source Project: rocketmq-spring   Source File: RocketMQTemplate.java    License: Apache License 2.0 6 votes vote down vote up
private Type getMessageType(RocketMQLocalRequestCallback rocketMQLocalRequestCallback) {
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(rocketMQLocalRequestCallback);
    Type matchedGenericInterface = null;
    while (Objects.nonNull(targetClass)) {
        Type[] interfaces = targetClass.getGenericInterfaces();
        if (Objects.nonNull(interfaces)) {
            for (Type type : interfaces) {
                if (type instanceof ParameterizedType && (Objects.equals(((ParameterizedType) type).getRawType(), RocketMQLocalRequestCallback.class))) {
                    matchedGenericInterface = type;
                    break;
                }
            }
        }
        targetClass = targetClass.getSuperclass();
    }
    if (Objects.isNull(matchedGenericInterface)) {
        return Object.class;
    }

    Type[] actualTypeArguments = ((ParameterizedType) matchedGenericInterface).getActualTypeArguments();
    if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
        return actualTypeArguments[0];
    }
    return Object.class;
}
 
Example 9
Source Project: jim-framework   Source File: CachingAnnotationsAspect.java    License: Apache License 2.0 6 votes vote down vote up
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// 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.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example 10
Source Project: Taroco-Scheduler   Source File: TaskManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 封装ScheduledMethodRunnable对象
 */
private ScheduledMethodRunnable buildScheduledRunnable(Object bean, String targetMethod, String params, String extKeySuffix, String scheduleKey) {
    Method method;
    Class<?> clazz;
    if (AopUtils.isAopProxy(bean)) {
        clazz = AopProxyUtils.ultimateTargetClass(bean);
    } else {
        clazz = bean.getClass();
    }
    if (params != null) {
        method = ReflectionUtils.findMethod(clazz, targetMethod, String.class);
    } else {
        method = ReflectionUtils.findMethod(clazz, targetMethod);
    }
    if (ObjectUtils.isEmpty(method)) {
        zkClient.getTaskGenerator().getScheduleTask().saveRunningInfo(scheduleKey, ScheduleServer.getInstance().getUuid(), "method not found");
        log.error("启动动态任务失败: {}, 失败原因: {}", scheduleKey, "method not found");
        return null;
    }
    return new ScheduledMethodRunnable(bean, method, params, extKeySuffix);
}
 
Example 11
private static ScheduledMethodRunnable _buildScheduledRunnable(Object bean, String targetMethod, String params) throws Exception {

		Assert.notNull(bean, "target object must not be null");
		Assert.hasLength(targetMethod, "Method name must not be empty");

		Method method;
		ScheduledMethodRunnable scheduledMethodRunnable;

		Class<?> clazz;
		if (AopUtils.isAopProxy(bean)) {
			clazz = AopProxyUtils.ultimateTargetClass(bean);
		} else {
			clazz = bean.getClass();
		}
		if (params != null) {
			method = ReflectionUtils.findMethod(clazz, targetMethod, String.class);
		} else {
			method = ReflectionUtils.findMethod(clazz, targetMethod);
		}

		Assert.notNull(method, "can not find method named " + targetMethod);
		scheduledMethodRunnable = new ScheduledMethodRunnable(bean, method, params);
		return scheduledMethodRunnable;
	}
 
Example 12
/**
 * Finds out the most specific method when the execution reference is an
 * interface or a method with generic parameters
 * 
 * @param pjp
 * @return
 */
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// 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.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example 13
Source Project: spring-boot-netty   Source File: SpringNettyConfiguration.java    License: MIT License 6 votes vote down vote up
private Map<String, List<ChannelHandler>> buildFilterHandlers(final Map<String, Object> filters) {
    final Map<String, List<ChannelHandler>> filterHandlers = new HashMap<>();
    filters.forEach((ignored, bean) -> {
        final Class<?> beanClass = AopProxyUtils.ultimateTargetClass(bean);
        if (!ChannelHandler.class.isAssignableFrom(beanClass)) {
            throw new IllegalStateException("Bean annotated with @NettyFilter doesn't implement ChannelHandler: " + bean);
        }

        final NettyFilter annotation = findAnnotation(beanClass, NettyFilter.class);
        if (annotation != null) {
            final String serverName = annotation.serverName();
            filterHandlers.computeIfAbsent(serverName, k -> new ArrayList<>())
                    .add((ChannelHandler) bean);
        }
    });

    //noinspection NestedMethodCall
    filterHandlers.values().forEach(l -> l.sort(FILTER_BEAN_COMPARATOR));

    return filterHandlers;
}
 
Example 14
@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 15
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
	synchronized (this.retrievalMutex) {
		// Explicitly remove target for a proxy, if registered already,
		// in order to avoid double invocations of the same listener.
		Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
		if (singletonTarget instanceof ApplicationListener) {
			this.defaultRetriever.applicationListeners.remove(singletonTarget);
		}
		this.defaultRetriever.applicationListeners.add(listener);
		this.retrieverCache.clear();
	}
}
 
Example 16
public void testRootVars(CacheableService<?> service) {
	Object key = new Object();
	Object r1 = service.rootVars(key);
	assertSame(r1, service.rootVars(key));
	Cache cache = this.cm.getCache("testCache");
	// assert the method name is used
	String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
	assertNotNull(cache.get(expectedKey));
}
 
Example 17
Source Project: spring-analysis-note   Source File: JCacheAspectSupport.java    License: MIT License 5 votes vote down vote up
@Nullable
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
	// Check whether aspect is enabled to cope with cases where the AJ is pulled in automatically
	if (this.initialized) {
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
		JCacheOperation<?> operation = getCacheOperationSource().getCacheOperation(method, targetClass);
		if (operation != null) {
			CacheOperationInvocationContext<?> context =
					createCacheOperationInvocationContext(target, args, operation);
			return execute(context, invoker);
		}
	}

	return invoker.invoke();
}
 
Example 18
@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) &&
			AnnotationUtils.isCandidateClass(targetClass, JmsListener.class)) {
		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 19
Source Project: spring-analysis-note   Source File: MethodJmsListenerEndpoint.java    License: MIT License 5 votes vote down vote up
@Nullable
public Method getMostSpecificMethod() {
	if (this.mostSpecificMethod != null) {
		return this.mostSpecificMethod;
	}
	Method method = getMethod();
	if (method != null) {
		Object bean = getBean();
		if (AopUtils.isAopProxy(bean)) {
			Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
			method = AopUtils.getMostSpecificMethod(method, targetClass);
		}
	}
	return method;
}
 
Example 20
Source Project: swagger-more   Source File: ApiRequestHandlerProvider.java    License: Apache License 2.0 5 votes vote down vote up
private BiFunction<List<HandlerMethod>, ? super ServiceBean,
        List<HandlerMethod>> toMappingEntries() {
    return (list, bean) -> {
        Object object = AopUtils.isAopProxy(bean.getRef())
                ? AopProxyUtils.getSingletonTarget(bean.getRef()) : bean.getRef();
        list.addAll(Arrays.stream(bean.getInterfaceClass().getDeclaredMethods())
                .filter(method -> !Modifier.isStatic(method.getModifiers()))
                .filter(method -> AnnotatedElementUtils.hasAnnotation(method, ApiMethod.class))
                .map(method -> new HandlerMethod(object, method))
                .collect(Collectors.toList()));
        return list;
    };
}
 
Example 21
Source Project: sofa-acts   Source File: ObjectUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * 
 * @param methodName
 * @param testedObj
 * @return
 */
public static Method findMethod(String methodName, Object testedObj) {

    Class<?>[] clazzes = AopProxyUtils.proxiedUserInterfaces(testedObj);

    for (Class<?> clazz : clazzes) {
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (StringUtils.equals(method.getName(), methodName)) {
                return method;
            }
        }
    }
    return null;
}
 
Example 22
@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)) {
		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 23
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
	synchronized (this.retrievalMutex) {
		// Explicitly remove target for a proxy, if registered already,
		// in order to avoid double invocations of the same listener.
		Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
		if (singletonTarget instanceof ApplicationListener) {
			this.defaultRetriever.applicationListeners.remove(singletonTarget);
		}
		this.defaultRetriever.applicationListeners.add(listener);
		this.retrieverCache.clear();
	}
}
 
Example 24
public void testRootVars(CacheableService<?> service) {
	Object key = new Object();
	Object r1 = service.rootVars(key);
	assertSame(r1, service.rootVars(key));
	Cache cache = this.cm.getCache("testCache");
	// assert the method name is used
	String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
	assertNotNull(cache.get(expectedKey));
}
 
Example 25
Source Project: java-technology-stack   Source File: JCacheAspectSupport.java    License: MIT License 5 votes vote down vote up
@Nullable
protected Object execute(CacheOperationInvoker invoker, Object target, Method method, Object[] args) {
	// Check whether aspect is enabled to cope with cases where the AJ is pulled in automatically
	if (this.initialized) {
		Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
		JCacheOperation<?> operation = getCacheOperationSource().getCacheOperation(method, targetClass);
		if (operation != null) {
			CacheOperationInvocationContext<?> context =
					createCacheOperationInvocationContext(target, args, operation);
			return execute(context, invoker);
		}
	}

	return invoker.invoke();
}
 
Example 26
@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 27
Source Project: java-technology-stack   Source File: MethodJmsListenerEndpoint.java    License: MIT License 5 votes vote down vote up
@Nullable
public Method getMostSpecificMethod() {
	if (this.mostSpecificMethod != null) {
		return this.mostSpecificMethod;
	}
	Method method = getMethod();
	if (method != null) {
		Object bean = getBean();
		if (AopUtils.isAopProxy(bean)) {
			Class<?> targetClass = AopProxyUtils.ultimateTargetClass(bean);
			method = AopUtils.getMostSpecificMethod(method, targetClass);
		}
	}
	return method;
}
 
Example 28
private Type getMessageType() {
    Class<?> targetClass;
    if (rocketMQListener != null) {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQListener);
    } else {
        targetClass = AopProxyUtils.ultimateTargetClass(rocketMQReplyListener);
    }
    Type matchedGenericInterface = null;
    while (Objects.nonNull(targetClass)) {
        Type[] interfaces = targetClass.getGenericInterfaces();
        if (Objects.nonNull(interfaces)) {
            for (Type type : interfaces) {
                if (type instanceof ParameterizedType &&
                    (Objects.equals(((ParameterizedType) type).getRawType(), RocketMQListener.class) || Objects.equals(((ParameterizedType) type).getRawType(), RocketMQReplyListener.class))) {
                    matchedGenericInterface = type;
                    break;
                }
            }
        }
        targetClass = targetClass.getSuperclass();
    }
    if (Objects.isNull(matchedGenericInterface)) {
        return Object.class;
    }

    Type[] actualTypeArguments = ((ParameterizedType) matchedGenericInterface).getActualTypeArguments();
    if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
        return actualTypeArguments[0];
    }
    return Object.class;
}
 
Example 29
Source Project: Limiter   Source File: LimiterAspectSupport.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param invocation
 * @param target
 * @param method
 * @param args
 * @return
 * @throws Throwable
 */
protected Object execute(final MethodInvocation invocation, Object target, Method method, Object[] args) throws Throwable {

    if (this.initialized) {
        Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
        LimitedResourceSource limitedResourceSource = getLimitedResourceSource();
        if (limitedResourceSource != null) {
            Collection<LimitedResource> limitedResources = limitedResourceSource.getLimitedResource(targetClass, method);
            if (!CollectionUtils.isEmpty(limitedResources)) {
                Collection<LimiterExecutionContext> contexts = getLimiterOperationContexts(limitedResources, method, args, target, targetClass);
                LimitContextsValueWrapper limitContextsValueWrapper = limitContexts(contexts);
                if (limitContextsValueWrapper.value()) {
                    try {
                        return invocation.proceed();
                    } catch (Throwable e) {
                        throw e;
                    } finally {
                        releaseContexts(contexts);
                    }
                } else {
                    return limitContextsValueWrapper.getLimiterFailResolveResult();
                }

            }
        }
    }
    return invocation.proceed();
}
 
Example 30
@Override
public void addApplicationListener(ApplicationListener<?> listener) {
	synchronized (this.retrievalMutex) {
		// Explicitly remove target for a proxy, if registered already,
		// in order to avoid double invocations of the same listener.
		Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
		if (singletonTarget instanceof ApplicationListener) {
			this.defaultRetriever.applicationListeners.remove(singletonTarget);
		}
		this.defaultRetriever.applicationListeners.add(listener);
		this.retrieverCache.clear();
	}
}