Example usage for org.springframework.aop.framework AopProxyUtils ultimateTargetClass

List of usage examples for org.springframework.aop.framework AopProxyUtils ultimateTargetClass

Introduction

In this page you can find the example usage for org.springframework.aop.framework AopProxyUtils ultimateTargetClass.

Prototype

public static Class<?> ultimateTargetClass(Object candidate) 

Source Link

Document

Determine the ultimate target class of the given bean instance, traversing not only a top-level proxy but any number of nested proxies as well — as long as possible without side effects, that is, just for singleton targets.

Usage

From source file:grails.plugin.cache.web.ProxyAwareMixedGrailsControllerHelper.java

@Override
protected Object retrieveAction(GroovyObject controller, String actionName, HttpServletResponse response) {

    Method method = ReflectionUtils.findMethod(AopProxyUtils.ultimateTargetClass(controller), actionName,
            MethodGrailsControllerHelper.NOARGS);

    if (method != null) {
        ReflectionUtils.makeAccessible(method);
        if (method.getAnnotation(Action.class) != null) {
            return method;
        }//from  ww w  . j av a2s.co m
    }

    return super.retrieveAction(controller, actionName, response);
}

From source file:com.developmentsprint.spring.breaker.interceptor.AopAllianceInvoker.java

public AopAllianceInvoker(MethodInvocation invocation, CircuitBreakerAttributeSource source) {
    this.invocation = invocation;

    target = invocation.getThis();//from  ww w  . j  av  a2 s. c o  m

    // get backing class
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    if (targetClass == null && target != null) {
        targetClass = target.getClass();
    }
    this.targetClass = targetClass;

    method = invocation.getMethod();

    arguments = invocation.getArguments();

    circuitBreakerAttribute = source.getCircuitBreakerAttribute(method, targetClass);
}

From source file:jrouter.spring.SpringObjectFactory.java

@Override
public Class<?> getClass(Object obj) {
    return AopProxyUtils.ultimateTargetClass(obj);
}

From source file:grails.plugin.cache.CustomCacheKeyGenerator.java

public Object generate(Object target, Method method, Object... params) {
    Class<?> objClass = AopProxyUtils.ultimateTargetClass(target);

    return new CacheKey(objClass.getName().intern(), method.toString().intern(), target.hashCode(),
            innerKeyGenerator.generate(target, method, params));
}

From source file:grails.plugin.cache.web.filter.PageFragmentCachingFilter.java

@Override
protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws Exception {
    // TODO need blocking cache stuff from CachingFilter
    initContext();/*from  w  w  w. j ava 2 s. co m*/

    try {

        Object controller = lookupController(getContext().getControllerClass());
        if (controller == null) {
            log.debug("Not a controller request {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }

        Class<?> controllerClass = AopProxyUtils.ultimateTargetClass(controller);
        if (controllerClass == null) {
            controllerClass = controller.getClass();
        }
        Method method = getContext().getMethod();
        if (method == null) {
            log.debug("No cacheable method found for {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }
        Collection<CacheOperation> cacheOperations = cacheOperationSource.getCacheOperations(method,
                controllerClass, true);

        if (CollectionUtils.isEmpty(cacheOperations)) {
            log.debug("No cacheable annotation found for {}:{} {}",
                    new Object[] { request.getMethod(), request.getRequestURI(), getContext() });
            chain.doFilter(request, response);
            return;
        }

        Map<String, Collection<CacheOperationContext>> operationsByType = createOperationContext(
                cacheOperations, method, controllerClass, request);

        // start with evictions
        if (inspectBeforeCacheEvicts(operationsByType.get(EVICT))) {
            chain.doFilter(request, response);
            return;
        }

        // follow up with cacheable
        CacheStatus status = inspectCacheables(operationsByType.get(CACHEABLE));

        Map<CacheOperationContext, Object> updates = inspectCacheUpdates(operationsByType.get(UPDATE));

        if (status != null) {
            if (status.updateRequired) {
                updates.putAll(status.updates);
            }
            // render cached response
            else {
                logRequestDetails(request, getContext(), "Caching enabled for request");
                PageInfo pageInfo = buildCachedPageInfo(request, response, status);
                writeResponse(request, response, pageInfo);
                return;
            }
        }

        logRequestDetails(request, getContext(), "Caching enabled for request");
        PageInfo pageInfo = buildNewPageInfo(request, response, chain, status, operationsByType);
        writeResponse(request, response, pageInfo);

        inspectAfterCacheEvicts(operationsByType.get(EVICT));

        if (!updates.isEmpty()) {
            Collection<Cache> caches = new ArrayList<Cache>();
            for (Map.Entry<CacheOperationContext, Object> entry : updates.entrySet()) {
                for (Cache cache : entry.getKey().getCaches()) {
                    caches.add(cache);
                }
            }
            update(caches, pageInfo, status, calculateKey(request));
        }
    } finally {
        destroyContext();
    }
}

From source file:org.apache.rave.synchronization.SynchronizingAspect.java

@Around("synchronizePointcut()")
public Object synchronizeInvocation(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = methodSignature.getMethod();
    Object target = proceedingJoinPoint.getTarget();
    Object[] args = proceedingJoinPoint.getArgs();
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    Synchronized annotation = getAnnotation(targetClass, method);
    Validate.notNull(annotation, "Could not find @Synchronized annotation!");

    Lock lock = getLock(targetClass, method, args, annotation);
    if (lock == null) {
        logger.debug(// w  w w. jav a2 s . c  o  m
                "No lock obtained for call [{}] on targetClass [{}] - proceeding without synchronization on "
                        + "thread {}",
                new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() });
        return proceedingJoinPoint.proceed();
    } else {
        try {
            logger.debug(
                    "Lock obtained for call [{}] on targetClass [{}] - proceeding with synchronization on thread {}",
                    new Object[] { method.getName(), targetClass.getName(), Thread.currentThread().getId() });
            lock.lock();
            return proceedingJoinPoint.proceed();
        } finally {
            lock.unlock();
            lockService.returnLock(lock);
        }
    }
}

From source file:org.apereo.portal.events.aggr.PortalRawEventsAggregatorImpl.java

@SuppressWarnings("unchecked")
protected final <T> Class<T> getClass(T object) {
    return (Class<T>) AopProxyUtils.ultimateTargetClass(object);
}

From source file:org.springframework.aop.framework.JdkDynamicAopProxy.java

/**
 * Implementation of {@code InvocationHandler.invoke}.
 * <p>Callers will see exactly the exception thrown by the target,
 * unless a hook method throws an exception.
 *//*from  w  w w .ja va  2 s  .c o  m*/
@Override
@Nullable
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MethodInvocation invocation;
    Object oldProxy = null;
    boolean setProxyContext = false;

    TargetSource targetSource = this.advised.targetSource;
    Object target = null;

    try {
        if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
            // The target does not implement the equals(Object) method itself.
            return equals(args[0]);
        } else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
            // The target does not implement the hashCode() method itself.
            return hashCode();
        } else if (method.getDeclaringClass() == DecoratingProxy.class) {
            // There is only getDecoratedClass() declared -> dispatch to proxy config.
            return AopProxyUtils.ultimateTargetClass(this.advised);
        } else if (!this.advised.opaque && method.getDeclaringClass().isInterface()
                && method.getDeclaringClass().isAssignableFrom(Advised.class)) {
            // Service invocations on ProxyConfig with the proxy config...
            return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
        }

        Object retVal;

        if (this.advised.exposeProxy) {
            // Make invocation available if necessary.
            oldProxy = AopContext.setCurrentProxy(proxy);
            setProxyContext = true;
        }

        // Get as late as possible to minimize the time we "own" the target,
        // in case it comes from a pool.
        target = targetSource.getTarget();
        Class<?> targetClass = (target != null ? target.getClass() : null);

        // Get the interception chain for this method.
        List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);

        // Check whether we have any advice. If we don't, we can fallback on direct
        // reflective invocation of the target, and avoid creating a MethodInvocation.
        if (chain.isEmpty()) {
            // We can skip creating a MethodInvocation: just invoke the target directly
            // Note that the final invoker must be an InvokerInterceptor so we know it does
            // nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
            Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
            retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
        } else {
            // We need to create a method invocation...
            invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
            // Proceed to the joinpoint through the interceptor chain.
            retVal = invocation.proceed();
        }

        // Massage return value if necessary.
        Class<?> returnType = method.getReturnType();
        if (retVal != null && retVal == target && returnType != Object.class && returnType.isInstance(proxy)
                && !RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
            // Special case: it returned "this" and the return type of the method
            // is type-compatible. Note that we can't help if the target sets
            // a reference to itself in another returned object.
            retVal = proxy;
        } else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
            throw new AopInvocationException(
                    "Null return value from advice does not match primitive return type for: " + method);
        }
        return retVal;
    } finally {
        if (target != null && !targetSource.isStatic()) {
            // Must have come from TargetSource.
            targetSource.releaseTarget(target);
        }
        if (setProxyContext) {
            // Restore old proxy.
            AopContext.setCurrentProxy(oldProxy);
        }
    }
}

From source file:org.springframework.cache.interceptor.CacheAspectSupport.java

private Class<?> getTargetClass(Object target) {
    return AopProxyUtils.ultimateTargetClass(target);
}

From source file:org.springframework.cache.interceptor.YJFCacheAspectSupport.java

protected Object execute(Invoker 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) {
        return invoker.invoke();
    }//from w  w  w .  j a v a  2 s .co m

    // get backing class
    Class<?> targetClass = AopProxyUtils.ultimateTargetClass(target);
    if (targetClass == null && target != null) {
        targetClass = target.getClass();
    }
    final Collection<CacheOperation> cacheOp = getCacheOperationSource().getCacheOperations(method,
            targetClass);

    // analyze caching information
    if (!CollectionUtils.isEmpty(cacheOp)) {
        Map<String, Collection<CacheOperationContext>> ops = createOperationContext(cacheOp, method, args,
                target, targetClass);

        // start with evictions
        inspectBeforeCacheEvicts(ops.get(EVICT));

        // follow up with cacheable
        CacheStatus status = inspectCacheables(ops.get(CACHEABLE));

        Object retVal = null;
        Map<CacheOperationContext, Object> updates = inspectCacheUpdates(ops.get(UPDATE));

        if (status != null) {
            if (status.updateRequired) {
                updates.putAll(status.cUpdates);
            }
            // return cached object
            else {
                return status.retVal;
            }
        }

        retVal = invoker.invoke();
        inspectAfterCacheEvicts(ops.get(EVICT));

        if (!updates.isEmpty()) {
            //?webservice ?
            if (getWebServiceEnable()) {
                if (retVal instanceof Result) {
                    Result result = (Result) retVal;
                    if (result.isSuccess()) {
                        update(updates, retVal);
                    }
                } else {
                    update(updates, retVal);
                }
            } else {
                update(updates, retVal);
            }
        }

        return retVal;
    }

    return invoker.invoke();
}