Example usage for org.aspectj.lang ProceedingJoinPoint getStaticPart

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

Introduction

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

Prototype

StaticPart getStaticPart();

Source Link

Usage

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

License:Open Source License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Around("call(@com.amazonaws.services.simpleworkflow.flow.annotations.Asynchronous * *(..)) && @annotation(asynchronousAnnotation)")
public Object makeAsynchronous(ProceedingJoinPoint pjp, Asynchronous asynchronousAnnotation) throws Throwable {
    final Signature signature = pjp.getStaticPart().getSignature();
    if (signature instanceof MethodSignature) {
        final MethodSignature methodSignature = (MethodSignature) signature;
        int i = 0;
        Object[] methodArguments = pjp.getArgs();
        Annotation[][] parameterAnnotations = methodSignature.getMethod().getParameterAnnotations();
        List<Promise> valueParams = new ArrayList<Promise>();
        for (final Class<?> parameterType : methodSignature.getParameterTypes()) {
            if ((isPromise(parameterType) || isPromiseArray(parameterType)
                    || (isCollection(parameterType) && hasWaitAnnotation(parameterAnnotations[i])))
                    && !hasNoWaitAnnotation(parameterAnnotations[i])) {
                Object param = methodArguments[i];
                if (isPromise(parameterType)) {
                    valueParams.add((Promise) param);
                } else if (isCollection(parameterType)) {
                    valueParams.add(new AndPromise((Collection) param));
                } else {
                    valueParams.add(new AndPromise((Promise[]) param));
                }//from   w w w  .j a va 2 s . c  o  m
            } else {
                valueParams.add(null);
            }
            i++;
        }

        Promise[] values = valueParams.toArray(new Promise[0]);
        Boolean daemon = asynchronousAnnotation.daemon() ? true : null;
        AsynchronousAspectTask task = new AsynchronousAspectTask(daemon, pjp, values);
        return task.getReturnValue();
    }

    return pjp.proceed();
}

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/*from  w  w w  .j a  v a2  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.crossbusiness.resiliency.aspect.AbstractCircuitBreakerAspect.java

License:Open Source License

public Object breakCircuit(final ProceedingJoinPoint pjp, CircuitBreaker circuitBreakerConfig)
        throws Throwable {
    Object result = null;//w w w. ja va 2s.  c om
    final String method = pjp.getSignature().toLongString();
    CircuitBreakerStatus status = null;
    try {
        final MethodSignature sig = (MethodSignature) pjp.getStaticPart().getSignature();
        registry.registeredMehtodIfnecessary(method, circuitBreakerConfig);
        status = registry.getStatusWithHalfOpenExclusiveLockTry(method);
        if (status.equals(CircuitBreakerStatus.OPEN)) {
            log.info("CIRCUIT STATUS: OPEN. Method {} can not be executed. try later!", method);
            throw new OpenCircuitException();
        } else if (status.equals(CircuitBreakerStatus.HALF_OPEN)) {
            log.info(
                    "CIRCUIT STATUS: HALF_OPEN. Another thread has the exclusive lock for half open. Method {} can not be executed.",
                    method);
            throw new OpenCircuitException();
        } else if (status.equals(CircuitBreakerStatus.CLOSED)) {
            log.info("CIRCUIT STATUS: CLOSED. execute method {}", method);
            result = proceed(pjp);
        } else if (status.equals(CircuitBreakerStatus.HALF_OPEN_EXCLUSIVE)) {
            log.info(
                    "CIRCUIT STATUS: HALF_OPEN_EXCLUSIVE. This thread win the exclusive lock for the half open call. execute method: {}",
                    method);
            result = proceed(pjp);
            log.info(
                    "CIRCUIT STATUS: HALF_OPEN_EXCLUSIVE. method execution was successfull. now close circuit for method {}",
                    method);
            registry.closeAndUnlock(method);
        }

    } catch (CircuitBreakerMethodExecutionException e) {
        Throwable throwable = e.getCause();
        for (Class<? extends Throwable> clazz : registry.getfailureIndications(method)) {
            if (clazz.isAssignableFrom(throwable.getClass())) {
                // detected a failure
                log.info("detected failure. failure indication: {} \nException:", clazz.getCanonicalName(),
                        throwable);
                if (status.equals(CircuitBreakerStatus.CLOSED)
                        && registry.sameClosedCycleInLocalAndGlobaleContext(method)) {
                    log.info("Valid failure: method call and failure are in the same CLOSED cycle.");
                    registry.addFailureAndOpenCircuitIfThresholdAchived(method);
                } else if (status.equals(CircuitBreakerStatus.HALF_OPEN_EXCLUSIVE)) {
                    registry.keepOpenAndUnlock(method);
                }
                throw throwable;
            }
        }
        // thrown exception is not a failureIndication
        if (status.equals(CircuitBreakerStatus.HALF_OPEN_EXCLUSIVE)) {
            log.info(
                    "CIRCUIT STATUS: HALF_OPEN_EXCLUSIVE. method execution was successfull. now close circuit for method {}",
                    method);
            registry.closeAndUnlock(method);
        }
        // throw the original method execution exception upper to the method invoker
        throw throwable;
    } finally {
        registry.cleanUp(method);
    }
    return result;
}

From source file:com.iisigroup.cap.aop.DBExecuteAdvice.java

License:Open Source License

@Around("execution(* com..dao.*.*(..))")
public Object spendTime(ProceedingJoinPoint pjp) throws Throwable {
    String targetName = pjp.getStaticPart().toShortString();
    long start = System.currentTimeMillis();
    Object obj = pjp.proceed();//from ww w  .ja va2s .co m
    long end = System.currentTimeMillis();
    logger.debug("DB execute time: " + (end - start) + "ms - " + targetName);
    return obj;

}

From source file:de.cosmocode.palava.core.aop.NegateAspect.java

License:Apache License

/**
 * An advice which blocks methods annotated with {@link Negate}.
 *
 * @since 2.9//from w w w .j  av  a  2  s  . com
 * @param point the proceeding join point
 * @return the new result
 */
@Around("call(@de.cosmocode.palava.core.aop.Negate * *.*())")
public Boolean block(ProceedingJoinPoint point) {
    checkInjected();
    LOG.trace("Negating {}", point.getStaticPart());

    try {
        return invert(point.proceed());
        /* CHECKSTYLE:OFF */
    } catch (Throwable e) {
        /* CHECKSTYLE:ON */
        throw Throwables.sneakyThrow(e);
    }
}

From source file:de.cosmocode.palava.core.aop.NoopAspect.java

License:Apache License

@Around("call(@de.cosmocode.palava.core.aop.Noop * *())")
public Boolean block(ProceedingJoinPoint point) {
    checkNotInjected();//www.  j  a v  a2 s.co m
    LOG.trace("Noop-ing {}", point.getStaticPart());

    try {
        return null;
        /* CHECKSTYLE:OFF */
    } catch (Throwable e) {
        /* CHECKSTYLE:ON */
        throw Throwables.sneakyThrow(e);
    }
}

From source file:de.cosmocode.palava.scope.AbstractUnitOfWorkScopeAspect.java

License:Apache License

/**
 * An advice around all join points selected by {@link #unitOfWork()} which
 * handles the correct usage of the {@link UnitOfWorkScope}.
 *
 * @since 2.0//from   ww w  .j a  v  a  2  s  .  com
 * @param point the proceeding join point
 * @return the result returned by the proceeding join point execution
 */
@Around("unitOfWork()")
public final Object aroundUnitOfWork(ProceedingJoinPoint point) {
    checkState();
    log.trace("Handling UnitOfWorkScope at {}", point.getStaticPart());
    if (scope.isActive()) {
        log.trace("UnitOfWorkScope already in progress");
        return proceed(point);
    } else {
        log.trace("Beginning managed UnitOfWorkScope");
        scope.begin();
        try {
            return proceed(point);
        } finally {
            scope.end();
            log.trace("Ended managed UnitOfWorkScope");
        }
    }
}

From source file:de.escidoc.core.common.util.aop.TraceInterceptor.java

License:Open Source License

@Around("execution(public * de.escidoc.core..*.* (..))" + " && !within(de.escidoc.core.common.util.aop..*)")
public Object traceMethod(final ProceedingJoinPoint joinPoint) throws Throwable, Exception {
    if (LOGGER.isDebugEnabled()) {
        final StaticPart staticPart = joinPoint.getStaticPart();
        final Signature signature = staticPart.getSignature();
        final String depthString = getDepthString();
        try {// w  w  w . j a v  a 2  s  . c  om
            LOGGER.debug(createMessage(true, depthString, signature));
            final Object returnValue = joinPoint.proceed();
            LOGGER.debug(createMessage(false, depthString, signature));
            return returnValue;
        } catch (final Exception e) {
            LOGGER.debug(createExceptionMessage(depthString, e));
            throw e;
        }
    }
    return joinPoint.proceed();
}

From source file:de.kaiserpfalzEdv.commons.jee.spring.ServiceLogging.java

License:Apache License

private String retrieveMethodNameFromSignature(ProceedingJoinPoint joinPoint) {
    return joinPoint.getStaticPart().getSignature().getDeclaringTypeName() + "."
            + joinPoint.getStaticPart().getSignature().getName();
}

From source file:fr.xebia.management.statistics.ProfileAspect.java

License:Apache License

@Around(value = "execution(* *(..)) && @annotation(profiled)", argNames = "pjp,profiled")
public Object profileInvocation(ProceedingJoinPoint pjp, Profiled profiled) throws Throwable {

    logger.trace("> profileInvocation({},{}", pjp, profiled);

    MethodSignature jointPointSignature = (MethodSignature) pjp.getStaticPart().getSignature();

    // COMPUTE SERVICE STATISTICS NAME
    Expression nameAsExpression = profiledMethodNameAsExpressionByMethod.get(jointPointSignature.getMethod());
    if (nameAsExpression == null) {
        if (StringUtils.hasLength(profiled.name())) {
            String nameAsStringExpression = profiled.name();
            nameAsExpression = expressionParser.parseExpression(nameAsStringExpression, parserContext);
        } else {/*from w  w  w  . j  ava 2  s.c om*/
            String fullyQualifiedMethodName = getFullyQualifiedMethodName(//
                    jointPointSignature.getDeclaringTypeName(), //
                    jointPointSignature.getName(), //
                    this.classNameStyle);
            nameAsExpression = new LiteralExpression(fullyQualifiedMethodName);
        }
    }

    String serviceStatisticsName;
    if (nameAsExpression instanceof LiteralExpression) {
        // Optimization : prevent useless objects instantiations
        serviceStatisticsName = nameAsExpression.getExpressionString();
    } else {
        serviceStatisticsName = nameAsExpression.getValue(new RootObject(pjp), String.class);
    }

    // LOOKUP SERVICE STATISTICS
    ServiceStatistics serviceStatistics = serviceStatisticsByName.get(serviceStatisticsName);

    if (serviceStatistics == null) {
        // INSTIANCIATE NEW SERVICE STATISTICS
        ServiceStatistics newServiceStatistics = new ServiceStatistics(//
                new ObjectName(this.jmxDomain + ":type=ServiceStatistics,name=" + serviceStatisticsName), //
                profiled.businessExceptionsTypes(), profiled.communicationExceptionsTypes());

        newServiceStatistics.setSlowInvocationThresholdInMillis(profiled.slowInvocationThresholdInMillis());
        newServiceStatistics
                .setVerySlowInvocationThresholdInMillis(profiled.verySlowInvocationThresholdInMillis());
        int maxActive;
        if (StringUtils.hasLength(profiled.maxActiveExpression())) {
            maxActive = expressionParser.parseExpression(profiled.maxActiveExpression(), parserContext)
                    .getValue(new RootObject(pjp), Integer.class);
        } else {
            maxActive = profiled.maxActive();
        }
        newServiceStatistics.setMaxActive(maxActive);
        newServiceStatistics.setMaxActiveSemaphoreAcquisitionMaxTimeInNanos(TimeUnit.NANOSECONDS
                .convert(profiled.maxActiveSemaphoreAcquisitionMaxTimeInMillis(), TimeUnit.MILLISECONDS));

        ServiceStatistics previousServiceStatistics = serviceStatisticsByName.putIfAbsent(serviceStatisticsName,
                newServiceStatistics);
        if (previousServiceStatistics == null) {
            serviceStatistics = newServiceStatistics;
            mbeanExporter.registerManagedResource(serviceStatistics);
        } else {
            serviceStatistics = previousServiceStatistics;
        }
    }

    // INVOKE AND PROFILE INVOCATION
    long nanosBefore = System.nanoTime();

    Semaphore semaphore = serviceStatistics.getMaxActiveSemaphore();
    if (semaphore != null) {
        boolean acquired = semaphore.tryAcquire(
                serviceStatistics.getMaxActiveSemaphoreAcquisitionMaxTimeInNanos(), TimeUnit.NANOSECONDS);
        if (!acquired) {
            serviceStatistics.incrementServiceUnavailableExceptionCount();
            throw new ServiceUnavailableException("Service '" + serviceStatisticsName + "' is unavailable: "
                    + serviceStatistics.getCurrentActive() + " invocations of are currently running");
        }
    }
    serviceStatistics.incrementCurrentActiveCount();
    try {

        Object returned = pjp.proceed();

        return returned;
    } catch (Throwable t) {
        serviceStatistics.incrementExceptionCount(t);
        throw t;
    } finally {
        if (semaphore != null) {
            semaphore.release();
        }
        serviceStatistics.decrementCurrentActiveCount();
        long deltaInNanos = System.nanoTime() - nanosBefore;
        serviceStatistics.incrementInvocationCounterAndTotalDurationWithNanos(deltaInNanos);
        if (logger.isDebugEnabled()) {
            logger.debug("< profileInvocation({}): {}ns", serviceStatisticsName, deltaInNanos);
        }
    }
}