Example usage for org.aspectj.lang ProceedingJoinPoint proceed

List of usage examples for org.aspectj.lang ProceedingJoinPoint proceed

Introduction

In this page you can find the example usage for org.aspectj.lang ProceedingJoinPoint proceed.

Prototype

public Object proceed() throws Throwable;

Source Link

Document

Proceed with the next advice or target method invocation

Usage

From source file:com.google.code.ssm.aop.ReadThroughMultiCacheAdvice.java

License:Open Source License

@Around("getMulti()")
@SuppressWarnings("unchecked")
public Object cacheMulti(final ProceedingJoinPoint pjp) throws Throwable {
    if (isDisabled()) {
        getLogger().info("Cache disabled");
        return pjp.proceed();
    }/*from ww w.  ja v a2 s.co  m*/

    // This is injected caching. If anything goes wrong in the caching, LOG
    // the crap outta it, but do not let it surface up past the AOP injection itself.
    final ReadThroughMultiCache annotation;
    final MultiCacheCoordinator coord;
    final AnnotationData data;
    final SerializationType serializationType;

    Object[] args = pjp.getArgs();
    try {
        // Get the target method being invoked, and make sure it returns the correct info.
        final Method methodToCache = getCacheBase().getMethodToCache(pjp);
        getCacheBase().verifyReturnTypeIsList(methodToCache, ReadThroughMultiCache.class);

        // Get the annotation associated with this method, and make sure the values are valid.
        annotation = methodToCache.getAnnotation(ReadThroughMultiCache.class);
        serializationType = getCacheBase().getSerializationType(methodToCache);

        data = AnnotationDataBuilder.buildAnnotationData(annotation, ReadThroughMultiCache.class,
                methodToCache);
        coord = new MultiCacheCoordinator(methodToCache, data);
        setMultiCacheOptions(coord, annotation.option());

        // Create key->object and object->key mappings.
        coord.setHolder(createObjectIdCacheKeyMapping(data, args, coord.getMethod()));

        List<Object> listKeyObjects = (List<Object>) Utils.getMethodArg(data.getListIndexInMethodArgs(), args,
                coord.getMethod().toString());
        coord.setListKeyObjects(listKeyObjects);

        // Get the full list of cache keys and ask the cache for the corresponding values.
        coord.setInitialKey2Result(
                getCacheBase().getCache(data).getBulk(coord.getKey2Obj().keySet(), serializationType));

        // We've gotten all positive cache results back, so build up a results list and return it.
        if (coord.getMissedObjects().isEmpty()) {
            return coord.generateResultList();
        }

        // Create the new list of arguments with a subset of the key objects that aren't in the cache. Do not modify
        // directly argument array from join point!
        args = coord.createModifiedArgumentList(args);
    } catch (Exception ex) {
        warn(ex, "Caching on %s aborted due to an error.", pjp.toShortString());
        return pjp.proceed();
    }

    /*
     * Call the target method with the new subset of arguments. We are calling this outside of the try/catch block
     * in case there are some 'not our fault' problems with the target method. (Connection issues, etc...) Though,
     * this decision could go either way, really.
     */
    final List<Object> results = (List<Object>) pjp.proceed(args);

    try {
        // there are no results
        if (results == null || results.isEmpty()) {
            if (coord.isAddNullsToCache()) {
                addNullValues(coord.getMissedObjects(), coord, serializationType);
            }
            return coord.generatePartialResultList();
        }

        if (coord.isGenerateKeysFromResult()) {
            return generateByKeysFromResult(results, coord, serializationType);
        } else {
            return generateByKeysProviders(results, coord, serializationType);
        }
    } catch (Exception ex) {
        warn(ex, "Caching on %s aborted due to an error. The underlying method will be called twice.",
                pjp.toShortString());
        // invoke underlying method again using unmodified arguments array
        return pjp.proceed(pjp.getArgs());
    }
}

From source file:com.google.code.ssm.aop.SingleReadCacheAdvice.java

License:Open Source License

protected Object cache(final ProceedingJoinPoint pjp) throws Throwable {
    if (isDisabled()) {
        getLogger().info("Cache disabled");
        return pjp.proceed();
    }// w w w  . j a v  a2  s.  c  o m
    // This is injected caching. If anything goes wrong in the caching, LOG
    // the crap outta it, but do not let it surface up past the AOP injection itself.
    final T annotation;
    final AnnotationData data;
    final SerializationType serializationType;
    String cacheKey = null;
    try {
        final Method methodToCache = getCacheBase().getMethodToCache(pjp);
        getCacheBase().verifyReturnTypeIsNoVoid(methodToCache, annotationClass);
        annotation = methodToCache.getAnnotation(annotationClass);
        serializationType = getCacheBase().getSerializationType(methodToCache);
        data = AnnotationDataBuilder.buildAnnotationData(annotation, annotationClass, methodToCache);

        cacheKey = getCacheKey(data, pjp.getArgs(), methodToCache.toString());

        final Object result = getCacheBase().getCache(data).get(cacheKey, serializationType);
        if (result != null) {
            getLogger().debug("Cache hit.");
            return getCacheBase().getResult(result);
        }
    } catch (Exception ex) {
        warn(ex, "Caching on method %s and key [%s] aborted due to an error.", pjp.toShortString(), cacheKey);
        return pjp.proceed();
    }

    final Object result = pjp.proceed();

    // This is injected caching. If anything goes wrong in the caching, LOG
    // the crap outta it, but do not let it surface up past the AOP injection itself.
    try {
        final Object submission = getCacheBase().getSubmission(result);
        getCacheBase().getCache(data).set(cacheKey, data.getExpiration(), submission, serializationType);
    } catch (Exception ex) {
        warn(ex, "Caching on method %s and key [%s] aborted due to an error.", pjp.toShortString(), cacheKey);
    }
    return result;
}

From source file:com.googlecode.commonspringaspects.aspects.CachingAspect.java

License:Apache License

/**
 * This advice caches the results of the advised method invocation and returns cached object whenever possible.
 * /*from   w w  w.  j  a  va2s. co m*/
 * @param joinPoint
 * @return
 * @throws Throwable
 */
public Object cachedObject(ProceedingJoinPoint joinPoint) throws Throwable {
    if (!enabled) {
        return joinPoint.proceed();
    }

    Object value;
    String cacheKey = getCacheKey(joinPoint);

    synchronized (this) {
        Element element = (Element) cache.get(cacheKey);

        if (element != null) {

            value = element.getObjectValue();

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Got from cache: key = " + cacheKey + ", value = " + value);
            }

        } else {

            value = joinPoint.proceed();
            cache.put(new Element(cacheKey, value));

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Added to cache: key = " + cacheKey + ", value = " + value);
            }
        }
    }
    return value;
}

From source file:com.googlecode.commonspringaspects.aspects.ForkingAspect.java

License:Apache License

public void fork(final ProceedingJoinPoint joinPoint) throws Throwable {
    if (!enabled) {
        joinPoint.proceed();
        return;// ww  w  .  j  av a 2  s.co m
    }

    taskExecutor.execute(new Runnable() {
        public void run() {
            try {
                joinPoint.proceed();
            } catch (Throwable t) {
                throw new RuntimeException(t);
            }
        }
    });
}

From source file:com.googlecode.commonspringaspects.aspects.JamonAspect.java

License:Apache License

/**
 * Monitors method calls using Jamon.//from   w  w w.  j av  a 2s.com
 * 
 * @param pjp
 * @return
 * @throws Throwable
 */
public Object monitor(ProceedingJoinPoint pjp) throws Throwable {
    if (!isEnabled()) {
        return pjp.proceed();
    }

    String methodSignature = createInvocationTraceName(pjp);
    Monitor monitor = MonitorFactory.start(methodSignature);
    try {
        return pjp.proceed();
    } finally {
        monitor.stop();
        if (monitor.getLastValue() > getLogThresholdMilliseconds()) {
            LOGGER.warn(monitor.getLastValue() + " ms. " + monitor);
        } else if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(monitor.getLastValue() + " ms. " + monitor);
        }
    }
}

From source file:com.googlecode.easiest.cache.ever.CacheAspect.java

License:Apache License

private Object aroundAdvice(ProceedingJoinPoint joinPoint, CacheReturnValue cacheAnnotation) throws Throwable {
    final MethodCall methodCall = buildMethodCall(joinPoint);
    final String cacheId = keyGenerator.generateMethodKey(methodCall);
    final String key = keyGenerator.generateParameterKey(methodCall.getParameters());

    final CacheConfig cacheConfig = buildCacheConfig(cacheAnnotation, methodCall.getParameters().size());
    cacheService.createCacheIfNecessary(cacheId, cacheConfig);

    final CachedValue cachedValue = cacheService.retrieve(cacheId, key);

    if (cachedValue.wasFound()) {
        return cachedValue.value();
    } else {/* w  w w.ja  va  2  s . co m*/
        final Object returnValue = joinPoint.proceed();
        cacheService.add(cacheId, key, returnValue);
        return returnValue;
    }
}

From source file:com.gramercysoftware.persistence.transactions.TransactionalAspect.java

License:Open Source License

@Around("transactionalPoint() && !within(com.enstream.transactions.TransactionalAspect)")
public Object transactional(ProceedingJoinPoint pjp) throws Throwable {
    EntityManager entityManager = null;/*from  ww w  .j  a v a2s  .  c  om*/
    EntityTransaction entityTransaction = null;
    boolean isActive = true;
    try {
        entityManager = entityManagerUtil.getEntityManager();

        entityTransaction = entityManager.getTransaction();
        isActive = entityTransaction.isActive();

        if (!isActive) {
            log.debug("Starting a database transaction at ------------->" + pjp);
            entityManagerUtil.closeEntityManager();
            entityManager = entityManagerUtil.getEntityManager();
            entityTransaction = entityManager.getTransaction();
            entityTransaction.begin();
        } else {
            log.debug("transaction already active so won't start at  ------------->" + pjp);
        }

        Object result = pjp.proceed();

        // Commit and cleanup
        if (!isActive) {
            boolean rollbackOnly = entityTransaction.getRollbackOnly();

            if (!rollbackOnly) {
                log.debug("Committing the database transaction at -------------> " + pjp + ",rollbackOnly:"
                        + rollbackOnly);
                entityTransaction.commit();
            } else {
                log.debug("Rolling back the database transaction at ------------->:" + pjp + ",rollbackOnly:"
                        + rollbackOnly);
                entityTransaction.rollback();
            }
        } else {
            log.debug(" transaction already active so won't commit at this stage at -------------> " + pjp);
        }
        return result;
    } catch (Throwable ex) {
        // Rollback only
        try {
            if (entityTransaction != null) {
                log.debug(
                        " Trying to rollback database transaction after exception during transactional operation  at -------------> "
                                + pjp,
                        ex);
                try {
                    if (entityTransaction.isActive()) {
                        entityTransaction.rollback();
                        log.debug("transaction rolled back ..");
                    }
                } catch (Throwable t) {
                    log.debug("unable to rollback!!!", t);
                }
            } else {
                log.debug(" entityTransaction was null, so could not call rollback on entityTransaction ", ex);
            }
            if (entityManager != null) {
                entityManagerUtil.closeEntityManager();
            }
        } catch (Throwable rbEx) {
            log.debug("Could not rollback transaction after exception!", rbEx);
        }
        // Let others handle it
        throw ex;
    } finally {
        if (!isActive) {
            entityManagerUtil.closeEntityManager();
        }
    }
}

From source file:com.hasitha.aop.aspect.KeyCheckAspect.java

/**
 * This is the method which I would like to execute after a selected method
 * execution./*from w  w  w .  java2  s.com*/
 *
 * @param called
 * @param pass_user_name
 * @param pass_password
 * @param account_id
 * @return
 */
@Around("registerOnlinepc() && args(pass_user_name, pass_password, account_id)")
public String aroundAdvice_registerOnlinepc(ProceedingJoinPoint called, String pass_user_name,
        String pass_password, int account_id) throws Throwable {
    System.out.println("AOP1 end");
    System.out.println(pass_user_name);
    Access newa = accessDao.getAccess(pass_user_name);
    if (newa.getPass_user_name() == null) {
        AccountHolder ah = accountHolderDao.getAccountHolder(account_id);
        if (ah.getAcch_name() != null) {
            called.proceed();
            return "{\"msg\":\"success\"}";
        } else {
            return "{\"msg\":\"Account Holder ID is Incorrect\"}";
        }
    } else {
        System.out.println(pass_user_name);
        return "{\"msg\":\"User Name is Already Exsist\"}";
    }
}

From source file:com.hasitha.aop.aspect.KeyCheckAspect.java

/**
 *
 * @param called// w  w w.  j  a va2  s .co  m
 * @param tra_acc_from
 * @param tra_amount
 * @param tra_acc_to
 * @return
 * @throws Throwable
 */
@Around("transferMoneypc() && args(tra_acc_from, tra_amount, tra_acc_to)")
public String aroundAdvice_transferMoneypc(ProceedingJoinPoint called, int tra_acc_from, double tra_amount,
        int tra_acc_to) throws Throwable {
    System.out.println("AOP1 end");
    AccountHolder acch = accountHolderDao.getAccountHolder(tra_acc_from);
    Account acc1 = accountDao.getAccount(tra_acc_to);
    System.out.println(acc1.toString());
    if (acc1.getAcc_state() == 1) {
        Account acc = accountDao.getAccount(acch.getAcch_id());
        if (acc.getAcc_balance() > tra_amount + acc.getAcc_min_balance()) {
            called.proceed();
            return "{\"msg\":\"success\"}";
        } else {
            return "{\"msg\":\"Account Balance is Insuffisent\"}";
        }
    } else {
        return "{\"msg\":\"Tranfer Account Number is Invalid\"}";
    }
}

From source file:com.haulmont.cuba.core.sys.MBeanInterceptor.java

License:Apache License

@SuppressWarnings("UnusedDeclaration")
private Object aroundInvoke(ProceedingJoinPoint ctx) throws Throwable {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());

    if (log.isTraceEnabled())
        log.trace("Invoking: " + ctx.getSignature());

    try {//w  w w  .  j  av a  2  s .  com
        Object res = ctx.proceed();
        return res;
    } catch (Throwable e) {
        log.error("MBeanInterceptor caught exception: ", e);
        throw e;
    }
}