Example usage for org.aspectj.lang.reflect MethodSignature getReturnType

List of usage examples for org.aspectj.lang.reflect MethodSignature getReturnType

Introduction

In this page you can find the example usage for org.aspectj.lang.reflect MethodSignature getReturnType.

Prototype

Class getReturnType();

Source Link

Usage

From source file:com.amazonaws.services.simpleworkflow.flow.aspectj.ExponentialRetryAspect.java

License:Open Source License

@Around("execution(@com.amazonaws.services.simpleworkflow.flow.annotations.ExponentialRetry * *(..)) && @annotation(retryAnnotation)")
public Object retry(final ProceedingJoinPoint pjp, ExponentialRetry retryAnnotation) throws Throwable {
    ExponentialRetryPolicy retryPolicy = createExponentialRetryPolicy(retryAnnotation);

    @SuppressWarnings("rawtypes")
    RetryCallable retryCallable = new RetryCallable() {

        @Override/*w ww.j a va2  s.c o  m*/
        public Promise call() throws Throwable {
            return (Promise) pjp.proceed();
        }
    };

    boolean isVoidReturnType = false;
    final Signature signature = pjp.getStaticPart().getSignature();
    if (signature instanceof MethodSignature) {
        final MethodSignature methodSignature = (MethodSignature) signature;
        isVoidReturnType = (methodSignature != null) ? Void.TYPE.equals(methodSignature.getReturnType())
                : false;
    }

    RetryInterceptor interceptor = null;
    if (isVoidReturnType) {
        interceptor = new RetryInterceptorVoid(retryCallable, retryPolicy);
    } else {
        interceptor = new RetryInterceptorWithResult(retryCallable, retryPolicy);
    }

    return interceptor.execute();
}

From source file:com.joken.base.spring.aop.CacheableAop.java

License:Open Source License

/**
 * AOP?//from  www .  ja  v a  2 s .c  o  m
 * 
 * @param pjp
 *            ?
 * @param cache
 *            
 * @return ?
 * @throws Throwable
 * @date 2015-10-10 ?8:29:11
 */
@Around("@annotation(cache)")
public Object cached(final ProceedingJoinPoint pjp, Cacheable cache) throws Throwable {
    THREAD_CACHE_EXPIRE.remove();
    if (redisTemplate == null) {
        return pjp.proceed();
    }

    // ???
    String key = getCacheKey(pjp, cache);
    // ????
    if (StringUtils.isEmpty(key)) {
        return pjp.proceed();
    }
    logger.info("????" + key);

    // ?
    if (cache.handleMode() == CacheHandleMode.delete) {
        this.deleteCaceh(key, cache);
        return pjp.proceed();
    }

    MethodSignature method = (MethodSignature) pjp.getSignature();
    Class<?> clazz = method.getReturnType();

    Object value;
    if (!(cache.handleMode() == CacheHandleMode.append)) {
        // ??
        value = this.getCache(key, cache);
        if (value != null) {
            return this.castValue(clazz, value);
        }
    }

    // ,??
    value = pjp.proceed();

    // ??
    if (value != null && cache.handleMode() != CacheHandleMode.nil) {
        // 
        Object cacheValue = value;
        if (value instanceof ResponseModel) {
            cacheValue = ((ResponseModel) value).getData();
        }

        // ??
        if (cacheValue != null) {
            logger.info("??" + key);
            this.setCache(key, cacheValue, cache);
        }
    }

    return value;
}

From source file:fi.mikah.log.LoggingAspect.java

License:Open Source License

/**
 * Return logging.//from  w  ww. j ava2 s.c o m
 *
 * @param joinPoint The join point for the method.
 * @param callLogging The call logging annotation.
 * @param returnValue The return value of the called method.
 */
@AfterReturning(value = "@annotation(callLogging)", argNames = "joinPoint, callLogging, returnValue", returning = "returnValue")
public void logExitAfterReturn(final JoinPoint joinPoint, CallLogging callLogging, Object returnValue) {
    Logger log = getLogger(joinPoint);
    Level level = Level.toLevel(callLogging.value().toString());

    if (log.isEnabledFor(level)) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> returnType = signature.getReturnType();
        if (returnType.getName().equals("void")) {
            log.log(level, "Exiting method " + joinPoint.getSignature().getName() + "[void]");
        } else {
            log.log(level, "Exiting method " + joinPoint.getSignature().getName() + "[" + returnValue + "]");
        }
    }
}

From source file:gov.fda.open.demo.service.loggable.LoggingAspect.java

License:Open Source License

/**
 * ************.//  ww w .  j av  a 2 s.  c o  m
 *
 * @param joinPoint
 *            the join point
 * @param loggable
 *            the loggable
 * @param returnValue
 *            the return value
 */
private void afterReturningLog(final JoinPoint joinPoint, final Loggable loggable, final Object returnValue) {

    Class<? extends Object> clazz = joinPoint.getTarget().getClass();
    String name = joinPoint.getSignature().getName();

    if (joinPoint.getSignature() instanceof MethodSignature) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class<?> returnType = signature.getReturnType();
        if (returnType.getName().compareTo("void") == 0) {
            logger.log(loggable.value(), clazz, null, AFTER_RETURNING_VOID, name,
                    constructArgumentsString(returnValue));
            return;
        }
    }
    logger.log(loggable.value(), clazz, null, AFTER_RETURNING, name, constructArgumentsString(returnValue));
}

From source file:kieker.monitoring.probe.aspectj.AbstractAspectJProbe.java

License:Apache License

/**
 * Better handling of AspectJ Signature.toLongString (especially with constructors).
 * //from www .j  av  a2  s.  co  m
 * @param sig
 *            an AspectJ Signature
 * @return LongString representation of the signature
 */
protected String signatureToLongString(final Signature sig) {
    String signatureString = this.signatureCache.get(sig);
    if (null != signatureString) {
        return signatureString;
    } else {
        if (sig instanceof MethodSignature) {
            final MethodSignature signature = (MethodSignature) sig;
            final StringBuilder sb = new StringBuilder(256);
            // modifiers
            final String modString = Modifier.toString(signature.getModifiers());
            sb.append(modString);
            if (modString.length() > 0) {
                sb.append(' ');
            }
            // return
            this.addType(sb, signature.getReturnType());
            sb.append(' ');
            // component
            sb.append(signature.getDeclaringTypeName());
            sb.append('.');
            // name
            sb.append(signature.getName());
            // parameters
            sb.append('(');
            this.addTypeList(sb, signature.getParameterTypes());
            sb.append(')');
            // throws
            // this.addTypeList(sb, signature.getExceptionTypes());
            signatureString = sb.toString();
        } else if (sig instanceof ConstructorSignature) {
            final ConstructorSignature signature = (ConstructorSignature) sig;
            final StringBuilder sb = new StringBuilder(256);
            // modifiers
            final String modString = Modifier.toString(signature.getModifiers());
            sb.append(modString);
            if (modString.length() > 0) {
                sb.append(' ');
            }
            // component
            sb.append(signature.getDeclaringTypeName());
            sb.append('.');
            // name
            sb.append(signature.getName());
            // parameters
            sb.append('(');
            this.addTypeList(sb, signature.getParameterTypes());
            sb.append(')');
            // throws
            // this.addTypeList(sb, signature.getExceptionTypes());
            signatureString = sb.toString();
        } else {
            signatureString = sig.toLongString();
        }
    }
    this.signatureCache.putIfAbsent(sig, signatureString);
    return signatureString;
}

From source file:org.esupportail.portlet.filemanager.crudlog.CrudLogService.java

License:Apache License

@AfterReturning(value = "@annotation(loggable)", returning = "returnValue", argNames = "joinPoint, loggable, returnValue")
public void afterReturning(JoinPoint joinPoint, CrudLoggable loggable, Object returnValue) {

    CrudLogLevel logLevel = loggable.value();

    if (CrudLogLevel.DEBUG.equals(logLevel) && log.isDebugEnabled()
            || CrudLogLevel.INFO.equals(logLevel) && log.isInfoEnabled()) {

        Class<? extends Object> clazz = joinPoint.getTarget().getClass();
        String name = joinPoint.getSignature().getName();

        Map<String, String> userInfos = this.getUserInfos(joinPoint);
        String username = userInfos.get("username");
        String clientIpAdress = userInfos.get("clientIpAdress");

        if (joinPoint.getSignature() instanceof MethodSignature) {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Class<?> returnType = signature.getReturnType();
            if (returnType.getName().compareTo("void") == 0) {
                this.log(logLevel, clazz, AFTER_RETURNING_VOID, name, clientIpAdress, username,
                        constructArgumentsString(clazz, joinPoint.getArgs()),
                        constructArgumentsString(clazz, returnValue));

                return;
            }/*from   w  w  w .  j a  va  2 s . c  o m*/
        }

        this.log(logLevel, clazz, AFTER_RETURNING, name, clientIpAdress, username,
                constructArgumentsString(clazz, joinPoint.getArgs()),
                constructArgumentsString(clazz, returnValue));
    }
}

From source file:org.hoteia.qalingo.core.aop.cache.CacheManagementAspect.java

License:Apache License

public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Object returnObject = null;/* w ww .  j  av a2s .  c  o m*/
    try {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class classTarget = signature.getReturnType();
        Object[] args = joinPoint.getArgs();
        String suffix = "";
        FetchPlan askedFetchPlan = null;
        FetchPlan loadedFetchPlan = null;
        String cacheType = CACHE_TYPE_MISC;

        // TOD : Denis : blind le code pour tester les arg differement entre une method get* et find* et autre

        if (joinPoint.getSignature().toShortString().contains("ById")) {
            // FIRST ARG IS A LONG FOR THE GET METHOD : SO THIS A GET BY ID
            cacheType = CACHE_BY_ID;
        } else if (joinPoint.getSignature().toShortString().contains("ByCode")) {
            // FIRST ARG IS A STRING FOR THE GET METHOD : SO THIS A GET BY CODE
            cacheType = CACHE_BY_CODE;
        }

        for (int i = 0; i < args.length; i++) {
            Object arg = args[i];
            if (arg instanceof Object[]) {
                Object[] objects = (Object[]) arg;
                for (int j = 0; j < objects.length; j++) {
                    Object object = (Object) objects[j];
                    if (object instanceof FetchPlan) {
                        FetchPlan fetchPlan = (FetchPlan) object;
                        if (fetchPlan != null && !fetchPlan.getFetchModes().isEmpty()) {
                            askedFetchPlan = fetchPlan;
                        }
                    }
                }
            }
            if (arg instanceof RequestData) {
                RequestData requestData = (RequestData) arg;
                if (!suffix.endsWith("_")) {
                    suffix = suffix + "_";
                }
                suffix = suffix + requestData.getMarketPlace().getCode() + "_"
                        + requestData.getMarket().getCode() + "_" + requestData.getMarketArea().getCode() + "_"
                        + requestData.getMarketAreaLocalization().getCode() + "_"
                        + requestData.getMarketAreaRetailer().getCode() + "_"
                        + requestData.getMarketAreaCurrency().getCode();

            } else if (arg instanceof AbstractEntity) {
                AbstractEntity argEntity = (AbstractEntity) arg;
                if (!suffix.endsWith("_")) {
                    suffix = suffix + "_";
                }
                Method[] methods = argEntity.getClass().getMethods();
                for (int j = 0; j < methods.length; j++) {
                    Method methodIt = methods[j];
                    if (methodIt.getName().equals("getId")) {
                        Long id = (Long) methodIt.invoke(argEntity);
                        suffix = suffix + id;
                    }
                }

            } else {
                if (arg != null && !(arg instanceof java.lang.Object[]) && !(arg instanceof AbstractEntity)) {
                    if (!suffix.endsWith("_")) {
                        suffix = suffix + "_";
                    }
                    suffix = suffix + arg.toString();
                }
            }
        }
        String key = null;
        String cacheName = DEFAULT_CACHE_NAME;
        if (classTarget != null) {
            try {
                Field cacheField = null;
                Field[] fields = classTarget.getFields();
                for (int i = 0; i < fields.length; i++) {
                    Field fieldIt = fields[i];
                    if (fieldIt.getName().equals(CACHE_NAME)) {
                        cacheField = fieldIt;
                    }
                }
                if (cacheField != null) {
                    cacheName = (String) cacheField.get(CACHE_NAME);
                }
            } catch (IllegalAccessException e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("IllegalAccessException code.", e);
                }
            }
        }

        // CACHE TYPE
        if (cacheType.equals(CACHE_TYPE_MISC)) {
            key = joinPoint.getSignature().toShortString() + suffix;
            if (!cacheName.contains("_misc")) {
                cacheName = cacheName + "_misc";
            }
        } else if (cacheType.equals(CACHE_BY_CODE)) {
            // TODO : Denis : utiliser un cache de type cacheName_link_code_id pour avoir l'id en fonction du code
            key = classTarget.getName() + suffix;
            cacheName = cacheName + "_link_code_id";
        } else {
            key = classTarget.getName() + suffix;
        }

        Cache cache = getCacheManager() != null && StringUtils.isNotEmpty(cacheName)
                ? getCacheManager().getCache(cacheName)
                : null;
        if (cache != null) {
            if (cache.isKeyInCache(key)) {
                Element element = cache.get(key);
                if (element != null && !element.isExpired()) {
                    // WE TEST IF THE FETCH PLAN ARE EQUALS
                    returnObject = element.getObjectValue();
                    if (returnObject instanceof AbstractEntity) {
                        AbstractEntity entity = (AbstractEntity) returnObject;
                        if (entity.getFetchPlan() != null) {
                            loadedFetchPlan = entity.getFetchPlan();
                        }

                        if (cacheType.equals(CACHE_BY_ID)) {
                            // ENTITY : UPDATE THE CACHE LINK ID CODE
                            String cacheNameIdCodeLink = cacheName + "_link_code_id";
                            Cache cacheLinkIdCode = getCacheManager() != null
                                    && StringUtils.isNotEmpty(cacheNameIdCodeLink)
                                            ? getCacheManager().getCache(cacheNameIdCodeLink)
                                            : null;
                            if (cacheLinkIdCode != null) {
                                String newKey = null;
                                String codeValue = null;
                                try {
                                    Method[] methods = classTarget.getMethods();
                                    for (int i = 0; i < methods.length; i++) {
                                        Method methodIt = methods[i];
                                        if (methodIt.getName().equals("getId")) {
                                            Long id = (Long) methodIt.invoke(returnObject);
                                            newKey = classTarget.getName() + "_" + id;
                                        }
                                        if (methodIt.getName().equals("getCode")) {
                                            codeValue = (String) methodIt.invoke(returnObject);
                                        }
                                        if (newKey != null && codeValue != null) {
                                            break;
                                        }
                                    }
                                } catch (Exception e) {
                                    if (logger.isDebugEnabled()) {
                                        logger.debug("IllegalAccessException.", e);
                                    }
                                }
                                if (newKey != null) {
                                    cacheLinkIdCode.put(new Element(newKey, codeValue));
                                }
                            }
                        }

                        if (cacheType.equals(CACHE_BY_CODE)) {
                            String cacheNameEntityById = cacheName.replace("_link_code_id", "");
                            Cache cacheEntityById = getCacheManager() != null
                                    && StringUtils.isNotEmpty(cacheNameEntityById)
                                            ? getCacheManager().getCache(cacheNameEntityById)
                                            : null;

                            String newKey = null;
                            Method[] methods = classTarget.getMethods();
                            for (int i = 0; i < methods.length; i++) {
                                Method methodIt = methods[i];
                                if (methodIt.getName().equals("getId")) {
                                    Long id = (Long) methodIt.invoke(returnObject);
                                    newKey = classTarget.getName() + "_" + id;
                                    break;
                                }
                            }

                            if (cacheEntityById != null) {
                                if (cacheEntityById.isKeyInCache(newKey)) {
                                    Element elementEntityById = cacheEntityById.get(newKey);
                                    if (elementEntityById != null && !elementEntityById.isExpired()) {
                                        returnObject = elementEntityById.getObjectValue();
                                    }
                                }
                            }

                        }
                    } else if (returnObject instanceof Long) {
                        if (cacheType.equals(CACHE_BY_CODE)) {
                            String cacheNameEntityById = cacheName.replace("_link_code_id", "");
                            Cache cacheEntityById = getCacheManager() != null
                                    && StringUtils.isNotEmpty(cacheNameEntityById)
                                            ? getCacheManager().getCache(cacheNameEntityById)
                                            : null;
                            String newKey = classTarget.getName() + "_" + returnObject;
                            if (cacheEntityById.isKeyInCache(newKey)) {
                                Element finalElement = cacheEntityById.get(newKey);
                                if (finalElement != null && !finalElement.isExpired()) {
                                    // WE WILL TEST IF THE FETCH PLAN ARE EQUALS
                                    returnObject = finalElement.getObjectValue();
                                }
                            } else {
                                // WE RESET THE returnObject WHICH HAS THE LONG VALUE - THIS WILL TRIGGER THE LOAD BY DAO
                                returnObject = null;
                            }
                        }
                    }
                }
            }
            if (returnObject == null) {
                if (loadedFetchPlan != null) {
                    args = ArrayUtils.add(args, loadedFetchPlan);
                    returnObject = joinPoint.proceed(args);
                } else {
                    returnObject = joinPoint.proceed();
                }
                if (returnObject != null && cacheType.equals(CACHE_BY_CODE)) {
                    // PUT IN THE RIGHT ENTITY CACHE
                    String cacheNameEntityById = cacheName.replace("_link_code_id", "");
                    Cache cacheEntityById = getCacheManager() != null
                            && StringUtils.isNotEmpty(cacheNameEntityById)
                                    ? getCacheManager().getCache(cacheNameEntityById)
                                    : null;
                    String newKey = null;
                    Method[] methods = classTarget.getMethods();
                    Long value = null;
                    for (int i = 0; i < methods.length; i++) {
                        Method methodIt = methods[i];
                        if (methodIt.getName().equals("getId")) {
                            Long id = (Long) methodIt.invoke(returnObject);
                            newKey = classTarget.getName() + "_" + id;
                            value = id;
                            break;
                        }
                    }
                    if (cacheEntityById != null) {
                        cacheEntityById.put(new Element(newKey, returnObject));
                    }

                    cache.put(new Element(key, value));

                } else {
                    cache.put(new Element(key, returnObject));
                }
            } else {
                if (returnObject instanceof AbstractEntity) {
                    AbstractEntity entity = (AbstractEntity) returnObject;
                    if (entity.getFetchPlan() != null) {
                        loadedFetchPlan = entity.getFetchPlan();
                    }
                    if (askedFetchPlan != null) {
                        if (loadedFetchPlan != null
                                && !loadedFetchPlan.containAllTargetFetchPlans(askedFetchPlan)) {
                            // ENTITY IS LOAD WITHOUT FETCHPLAN - WE RESET THE returnObject TO TRIGGER THE RELOAD WITH THE FETCHPLAN
                            // WE WILL ADD LOADED FETCH PLAN AND ASKED FETCH PLAN TO THE INVOCATED METHOD
                            returnObject = null;

                        }

                        //                            for (Iterator<SpecificFetchMode> iterator = askedFetchPlan.iterator(); iterator.hasNext();) {
                        //                                SpecificFetchMode specificFetchMode = (SpecificFetchMode) iterator.next();
                        //                                if(loadedFetchPlan == null){
                        //                                    // ENTITY IS LOAD WITHOUT FETCHPLAN - WE RESET THE returnObject TO TRIGGER THE RELOAD WITH THE FETCHPLAN
                        //                                    returnObject = null;
                        //                                    break;
                        //                                } else if (!loadedFetchPlan.contains(specificFetchMode)){
                        //                                    // ENTITY IS LOAD WITH A DIFF FETCHPLAN - WE RESET THE returnObject TO TRIGGER THE RELOAD
                        //                                    returnObject = null;
                        //                                    break;
                        //                                }
                        //                            }

                        if (returnObject == null) {
                            if (loadedFetchPlan != null) {
                                for (int i = 0; i < args.length; i++) {
                                    Object arg = args[i];
                                    if (arg instanceof Object[]) {
                                        Object[] objects = (Object[]) arg;
                                        for (int j = 0; j < objects.length; j++) {
                                            Object object = (Object) objects[j];
                                            if (object instanceof FetchPlan) {
                                                // WE ARE IN THE FETCHPLAN OBJECT ARRAY
                                                objects = ArrayUtils.add(objects, entity.getFetchPlan());
                                                args = ArrayUtils.remove(args, i);
                                                args = ArrayUtils.add(args, objects);
                                                break;
                                            }
                                        }
                                    }
                                }

                                returnObject = joinPoint.proceed(args);
                            }
                            //                                else {
                            //                                    returnObject = joinPoint.proceed();
                            //                                }

                            if (returnObject != null) {
                                if (cacheType.equals(CACHE_BY_CODE)) {
                                    // PUT IN THE RIGHT ENTITY CACHE
                                    String cacheNameEntityById = cacheName.replace("_link_code_id", "");
                                    Cache cacheEntityById = getCacheManager() != null
                                            && StringUtils.isNotEmpty(cacheNameEntityById)
                                                    ? getCacheManager().getCache(cacheNameEntityById)
                                                    : null;
                                    String newKey = null;
                                    Method[] methods = classTarget.getMethods();
                                    Long value = null;
                                    for (int i = 0; i < methods.length; i++) {
                                        Method methodIt = methods[i];
                                        if (methodIt.getName().equals("getId")) {
                                            Long id = (Long) methodIt.invoke(returnObject);
                                            newKey = classTarget.getName() + "_" + id;
                                            value = id;
                                            break;
                                        }
                                    }
                                    if (cacheEntityById != null) {
                                        cacheEntityById.put(new Element(newKey, returnObject));
                                    }

                                    cache.put(new Element(key, value));

                                } else {
                                    cache.put(new Element(key, returnObject));
                                }
                            }
                        }
                    }
                }
            }

        }

    } catch (Exception e) {
        logger.error("Failed to load datas with Cache AOP!", e);
    }
    return returnObject;
}

From source file:org.rapharino.base.api.result.ResultUtil.java

License:Open Source License

public static Object createErrorResult(ProceedingJoinPoint pjp, String requestIp, int code, String msg) {
    Signature signature = pjp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Class<?> clazz = methodSignature.getReturnType();
    Object object = null;/*from w  w w .ja va 2 s .  c o m*/
    try {
        object = clazz.newInstance();
    } catch (InstantiationException e) {
        LOGGER.error("createErrorResult-InstantiationException", e);
        throw new ApiException(ResultCode.INTERNAL_ERROR);
    } catch (IllegalAccessException e) {
        LOGGER.error("createErrorResult-IllegalAccessException", e);
        throw new ApiException(ResultCode.INTERNAL_ERROR);
    }
    if (object instanceof BaseResult) {
        ((BaseResult) object).setErrorMessage(code, msg);
        ((BaseResult) object).setRequestIp(requestIp);
    }
    return object;
}

From source file:org.smallmind.persistence.cache.aop.ORMBasedCacheAsAspect.java

License:Open Source License

@Around(value = "execution(@CacheAs * * (..)) && @annotation(cacheAs) && this(ormDao)", argNames = "thisJoinPoint, cacheAs, ormDao")
public Object aroundCacheAsMethod(ProceedingJoinPoint thisJoinPoint, CacheAs cacheAs, ORMDao ormDao)
        throws Throwable {

    Annotation instrumentedAnnotation;
    MethodSignature methodSignature;
    Method executedMethod = null;
    String metricSource = null;//from  w ww.  j  av a 2 s.c  om
    boolean timingEnabled;
    long start = 0;
    long stop;

    instrumentedAnnotation = ormDao.getClass().getAnnotation(Instrumented.class);
    if (timingEnabled = (instrumentedAnnotation != null) && ((Instrumented) instrumentedAnnotation).value()) {
        start = System.currentTimeMillis();
    }

    methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    try {

        Type returnType;

        if (cacheAs.time().value() < 0) {
            throw new CacheAutomationError(
                    "The base time(%d) value of a @CacheAs annotation can not be negative",
                    cacheAs.time().value());
        }

        if (cacheAs.time().stochastic() < 0) {
            throw new CacheAutomationError(
                    "The stochastic(%d) attribute of a @CacheAs annotation can not be negative",
                    cacheAs.time().stochastic());
        }

        if (ormDao.getManagedClass().equals(methodSignature.getReturnType())) {
            if (cacheAs.ordered()) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type can't be ordered",
                        cacheAs.comparator().getClass().getName());
            } else if (cacheAs.max() > 0) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type may not define a maximum size",
                        cacheAs.comparator().getClass().getName());
            } else if (!cacheAs.comparator().equals(Comparator.class)) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type can not register a comparator(%s)",
                        cacheAs.comparator().getClass().getName());
            }

            VectoredDao vectoredDao;

            if ((vectoredDao = ormDao.getVectoredDao()) == null) {
                metricSource = ormDao.getMetricSource();

                return thisJoinPoint.proceed();
            } else {

                VectorKey vectorKey;
                DurableVector vector;

                vectorKey = new VectorKey(VectorCalculator.getVectorArtifact(cacheAs.value(), thisJoinPoint),
                        ormDao.getManagedClass(),
                        Classifications.get(CacheAs.class, thisJoinPoint, cacheAs.value()));

                if ((vector = vectoredDao.getVector(vectorKey)) != null) {
                    if (!vector.isAlive()) {
                        vectoredDao.deleteVector(vectorKey);
                    } else {
                        metricSource = vectoredDao.getMetricSource();

                        return vector.head();
                    }
                }

                Durable durable;

                metricSource = ormDao.getMetricSource();

                if ((durable = (Durable) thisJoinPoint.proceed()) != null) {

                    return vectoredDao.persistVector(vectorKey,
                            vectoredDao.createSingularVector(vectorKey, durable, getTimeToLiveSeconds(cacheAs)))
                            .head();
                }

                return null;
            }
        } else if (Iterable.class.isAssignableFrom(methodSignature.getReturnType())) {
            if ((!cacheAs.comparator().equals(Comparator.class)) && (!cacheAs.ordered())) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs has registered a comparator(%s) but is not ordered",
                        cacheAs.comparator().getClass().getName());
            }

            if ((!((returnType = (executedMethod = methodSignature.getMethod())
                    .getGenericReturnType()) instanceof ParameterizedType))
                    || (!ormDao.getManagedClass()
                            .equals(((ParameterizedType) returnType).getActualTypeArguments()[0]))) {
                throw new CacheAutomationError(
                        "Methods annotated with @CacheAs which return an Iterable type must be parameterized to <? extends Iterable<%s>>",
                        ormDao.getManagedClass().getSimpleName());
            }

            VectoredDao vectoredDao;

            if ((vectoredDao = ormDao.getVectoredDao()) == null) {
                metricSource = ormDao.getMetricSource();

                return thisJoinPoint.proceed();
            } else {

                VectorKey vectorKey;
                DurableVector vector;

                vectorKey = new VectorKey(VectorCalculator.getVectorArtifact(cacheAs.value(), thisJoinPoint),
                        ormDao.getManagedClass(),
                        Classifications.get(CacheAs.class, thisJoinPoint, cacheAs.value()));

                if ((vector = vectoredDao.getVector(vectorKey)) != null) {
                    if (!vector.isAlive()) {
                        vectoredDao.deleteVector(vectorKey);
                    } else {
                        metricSource = vectoredDao.getMetricSource();

                        return List.class.isAssignableFrom(methodSignature.getReturnType())
                                ? vector.asBestEffortPreFetchedList()
                                : vector.asBestEffortLazyList();
                    }
                }

                Iterable iterable;

                metricSource = ormDao.getMetricSource();

                if ((iterable = (Iterable) thisJoinPoint.proceed()) != null) {
                    vector = vectoredDao.persistVector(vectorKey,
                            vectoredDao.createVector(vectorKey, iterable,
                                    cacheAs.comparator().equals(Comparator.class) ? null
                                            : cacheAs.comparator().newInstance(),
                                    cacheAs.max(), getTimeToLiveSeconds(cacheAs), cacheAs.ordered()));

                    return List.class.isAssignableFrom(methodSignature.getReturnType())
                            ? vector.asBestEffortPreFetchedList()
                            : vector.asBestEffortLazyList();
                }

                return null;
            }
        } else {
            throw new CacheAutomationError(
                    "Methods annotated with @CacheAs must either return their managed type(%s), or an Iterable parameterized to their managed type <? extends Iterable<%s>>",
                    ormDao.getManagedClass().getSimpleName(), ormDao.getManagedClass().getSimpleName());
        }
    } catch (Throwable throwable) {
        timingEnabled = false;

        throw throwable;
    } finally {
        if (timingEnabled) {
            stop = System.currentTimeMillis();

            if (executedMethod == null) {
                executedMethod = methodSignature.getMethod();
            }

            InstrumentationManager.instrumentWithChronometer(PersistenceManager.getPersistence(), stop - start,
                    TimeUnit.MILLISECONDS,
                    new MetricProperty("durable", ormDao.getManagedClass().getSimpleName()),
                    new MetricProperty("method", executedMethod.getName()),
                    new MetricProperty("source", metricSource));
        }
    }
}

From source file:org.springframework.aop.aspectj.MethodInvocationProceedingJoinPointTests.java

License:Apache License

@Test
public void testCanGetMethodSignatureFromJoinPoint() {
    final Object raw = new TestBean();
    // Will be set by advice during a method call
    final int newAge = 23;

    ProxyFactory pf = new ProxyFactory(raw);
    pf.setExposeProxy(true);//www .j a  v a 2  s  .  c  om
    pf.addAdvisor(ExposeInvocationInterceptor.ADVISOR);
    pf.addAdvice(new MethodBeforeAdvice() {
        private int depth;

        @Override
        public void before(Method method, Object[] args, Object target) throws Throwable {
            JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();
            assertTrue("Method named in toString", jp.toString().contains(method.getName()));
            // Ensure that these don't cause problems
            jp.toShortString();
            jp.toLongString();

            assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget());
            assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget()));

            ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis();
            assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis()));

            assertNotSame(target, thisProxy);

            // Check getting again doesn't cause a problem
            assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis());

            // Try reentrant call--will go through this advice.
            // Be sure to increment depth to avoid infinite recursion
            if (depth++ == 0) {
                // Check that toString doesn't cause a problem
                thisProxy.toString();
                // Change age, so this will be returned by invocation
                thisProxy.setAge(newAge);
                assertEquals(newAge, thisProxy.getAge());
            }

            assertSame(AopContext.currentProxy(), thisProxy);
            assertSame(target, raw);

            assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName());
            assertEquals(method.getModifiers(),
                    AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers());

            MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature();
            assertSame("Return same MethodSignature repeatedly", msig,
                    AbstractAspectJAdvice.currentJoinPoint().getSignature());
            assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(),
                    AbstractAspectJAdvice.currentJoinPoint());
            assertEquals(method.getDeclaringClass(), msig.getDeclaringType());
            assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes()));
            assertEquals(method.getReturnType(), msig.getReturnType());
            assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes()));
            msig.toLongString();
            msig.toShortString();
        }
    });
    ITestBean itb = (ITestBean) pf.getProxy();
    // Any call will do
    assertEquals("Advice reentrantly set age", newAge, itb.getAge());
}