Java Code Examples for org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass()

The following examples show how to use org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass() . 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: RocketMQTemplate.java    From rocketmq-spring with 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 2
Source File: ExtProducerResetConfiguration.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
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 3
Source File: DefaultRocketMQListenerContainer.java    From rocketmq-spring with Apache License 2.0 6 votes vote down vote up
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 4
Source File: DynamicTaskManager.java    From uncode-schedule with GNU General Public License v2.0 6 votes vote down vote up
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 5
Source File: RaftAnnotationBeanPostProcessor.java    From sofa-registry with Apache License 2.0 6 votes vote down vote up
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 6
Source File: DcsSchedulingConfiguration.java    From schedule-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: AbstractCacheAnnotationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
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 8
Source File: CacheAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private Class<?> getTargetClass(Object target) {
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
	if (targetClass == null && target != null) {
		targetClass = target.getClass();
	}
	return targetClass;
}
 
Example 9
Source File: DefaultRocketMQListenerContainer.java    From rocketmq-spring with Apache License 2.0 5 votes vote down vote up
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 10
Source File: MethodJmsListenerEndpoint.java    From java-technology-stack with 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 11
Source File: JmsListenerAnnotationBeanPostProcessor.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 12
Source File: JCacheAspectSupport.java    From java-technology-stack with 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 13
Source File: CacheAspectSupport.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private Class<?> getTargetClass(Object target) {
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
	if (targetClass == null && target != null) {
		targetClass = target.getClass();
	}
	return targetClass;
}
 
Example 14
Source File: AbstractCacheAnnotationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public void testRootVars(CacheableService<?> service) {
	Object key = new Object();
	Object r1 = service.rootVars(key);
	assertSame(r1, service.rootVars(key));
	Cache cache = cm.getCache("testCache");
	// assert the method name is used
	String expectedKey = "rootVarsrootVars" + AopProxyUtils.ultimateTargetClass(service) + service;
	assertNotNull(cache.get(expectedKey));
}
 
Example 15
Source File: LimiterAspectSupport.java    From Limiter with 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 16
Source File: JCacheAspectSupport.java    From spring-analysis-note with 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 17
Source File: AbstractCacheAnnotationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
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 18
Source File: JCacheAspectSupport.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
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 19
Source File: ListenerContainerConfiguration.java    From rocketmq-spring with Apache License 2.0 4 votes vote down vote up
private void registerContainer(String beanName, Object bean) {
    Class<?> clazz = AopProxyUtils.ultimateTargetClass(bean);

    if (RocketMQListener.class.isAssignableFrom(bean.getClass()) && RocketMQReplyListener.class.isAssignableFrom(bean.getClass())) {
        throw new IllegalStateException(clazz + " cannot be both instance of " + RocketMQListener.class.getName() + " and " + RocketMQReplyListener.class.getName());
    }

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

    RocketMQMessageListener annotation = clazz.getAnnotation(RocketMQMessageListener.class);

    String consumerGroup = this.environment.resolvePlaceholders(annotation.consumerGroup());
    String topic = this.environment.resolvePlaceholders(annotation.topic());

    boolean listenerEnabled =
        (boolean) rocketMQProperties.getConsumer().getListeners().getOrDefault(consumerGroup, Collections.EMPTY_MAP)
            .getOrDefault(topic, true);

    if (!listenerEnabled) {
        log.debug(
            "Consumer Listener (group:{},topic:{}) is not enabled by configuration, will ignore initialization.",
            consumerGroup, topic);
        return;
    }
    validate(annotation);

    String containerBeanName = String.format("%s_%s", DefaultRocketMQListenerContainer.class.getName(),
        counter.incrementAndGet());
    GenericApplicationContext genericApplicationContext = (GenericApplicationContext) applicationContext;

    genericApplicationContext.registerBean(containerBeanName, DefaultRocketMQListenerContainer.class,
        () -> createRocketMQListenerContainer(containerBeanName, bean, annotation));
    DefaultRocketMQListenerContainer container = genericApplicationContext.getBean(containerBeanName,
        DefaultRocketMQListenerContainer.class);
    if (!container.isRunning()) {
        try {
            container.start();
        } catch (Exception e) {
            log.error("Started container failed. {}", container, e);
            throw new RuntimeException(e);
        }
    }

    log.info("Register the listener to container, listenerBeanName:{}, containerBeanName:{}", beanName, containerBeanName);
}
 
Example 20
Source File: BeanUtils.java    From servicecomb-java-chassis with Apache License 2.0 2 votes vote down vote up
/**
 * Get the implemented class of the given instance
 * @param bean the instance to get implemented class from
 * @return the implemented class (if the checked class is proxied, return the ultimate target class)
 * @see org.springframework.aop.framework.AopProxyUtils#ultimateTargetClass
 */
public static Class<?> getImplClassFromBean(Object bean) {
  return AopProxyUtils.ultimateTargetClass(bean);
}