Example usage for org.aspectj.lang ProceedingJoinPoint getTarget

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

Introduction

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

Prototype

Object getTarget();

Source Link

Document

Returns the target object.

Usage

From source file:com.vladmihalcea.util.ReflectionUtils.java

License:Apache License

public static <T extends Annotation> T getAnnotation(ProceedingJoinPoint pjp, Class<T> annotationClass)
        throws NoSuchMethodException {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    T annotation = AnnotationUtils.findAnnotation(method, annotationClass);

    if (annotation != null) {
        return annotation;
    }//from  w  ww .ja v a 2s  . co m

    Class[] argClasses = new Class[pjp.getArgs().length];
    for (int i = 0; i < pjp.getArgs().length; i++) {
        argClasses[i] = pjp.getArgs()[i].getClass();
    }
    method = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), argClasses);
    return AnnotationUtils.findAnnotation(method, annotationClass);
}

From source file:com.vmware.bdd.aop.tx.RetryTransactionAdvice.java

License:Open Source License

public void retry(ProceedingJoinPoint pjp) throws Throwable {
    logger.info("retry transaction");
    int retriesLeft = 5;
    String methodName = pjp.getSignature().getName();
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    if (method.getDeclaringClass().isInterface()) {
        method = pjp.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
    }//from   w  ww.  j ava 2 s.  co m
    Annotation[] annotations = method.getDeclaredAnnotations();
    for (Annotation a : annotations) {
        if (a instanceof RetryTransaction) {
            RetryTransaction retryAnno = (RetryTransaction) a;
            retriesLeft = retryAnno.value();
        }
    }

    RetryTransaction retryTrx = AnnotationUtils.findAnnotation(method, RetryTransaction.class);
    retriesLeft = retryTrx.value();
    Throwable rootCause = null;
    boolean success = false;
    while (!success) {
        try {
            pjp.proceed();
            success = true;
        } catch (Throwable ex) {
            rootCause = (ex instanceof BddException) ? ex.getCause() : ex;
            if (isRetryable(rootCause)) {
                if (retriesLeft > 0) {
                    retriesLeft--;
                } else {
                    throw TxRetryException.wrap(rootCause, false);
                }
            } else if (isUniqViolation(rootCause)) {
                throw UniqueConstraintViolationException.wrap((ConstraintViolationException) rootCause);
            } else {
                throw BddException.wrapIfNeeded(ex, "Exception in a DAL transaction.");
            }
        }
    }
    if (!success) {
        if (rootCause != null) {
            logger.warn("retry transaction failed.", rootCause);
            throw rootCause;
        } else {
            logger.warn("retry transction failed.");
            throw new Exception("retry transaction failed");
        }
    } else {
        if (rootCause != null) {
            logger.warn("retry transaction completed. Failure root cause:" + rootCause.getMessage());
        } else {
            logger.info("normal operation");
        }
    }
}

From source file:com.vsct.supervision.notification.log.LoggingAspect.java

License:Open Source License

@Around(value = "@within(com.vsct.supervision.notification.log.Loggable) || @annotation(com.vsct.supervision.notification.log.Loggable)")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    final MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    final Method method = signature.getMethod();
    final Class clazz = signature.getClass();
    final Loggable loggableMethod = method.getAnnotation(Loggable.class);

    final Loggable loggableClass = proceedingJoinPoint.getTarget().getClass().getAnnotation(Loggable.class);

    //get current log level
    final LogLevel logLevel = loggableMethod != null ? loggableMethod.value() : loggableClass.value();

    final String service = StringUtils.isNotBlank(loggableClass.service()) ? loggableClass.service()
            : clazz.getName();/*from   www .  j  av a  2 s .co m*/
    final String methodName = StringUtils.isNotBlank(loggableClass.method()) ? loggableClass.method()
            : method.getName();

    final String star = "**********";
    //before
    LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
            star + service + "." + methodName + "() start execution" + star);

    //show traceParams
    final boolean showParams = loggableMethod != null ? loggableMethod.traceParams()
            : loggableClass.traceParams();
    if (showParams) {

        if (proceedingJoinPoint.getArgs() != null && proceedingJoinPoint.getArgs().length > 0) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < proceedingJoinPoint.getArgs().length; i++) {
                sb.append(method.getParameterTypes()[i].getName() + ":" + proceedingJoinPoint.getArgs()[i]);
                if (i < proceedingJoinPoint.getArgs().length - 1)
                    sb.append(", ");
            }

            LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
                    service + "." + methodName + "() args " + sb);
        }

    }

    final long startTime = System.currentTimeMillis();
    //start method execution
    final Object result = proceedingJoinPoint.proceed();

    final long endTime = System.currentTimeMillis();

    //show results
    if (result != null) {
        boolean showResults = loggableMethod != null ? loggableMethod.traceResult()
                : loggableClass.traceResult();
        if (showResults) {
            LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel,
                    service + "." + methodName + "() Result : " + result);
        }
    }

    //show after
    LogWriter.write(proceedingJoinPoint.getTarget().getClass(), logLevel, star + service + "." + methodName
            + "() finished execution and takes " + (endTime - startTime) + " millis time to execute " + star);

    return result;
}

From source file:com.yoho.core.trace.instrument.async.TraceAsyncAspect.java

License:Apache License

@Around("execution (@org.springframework.scheduling.annotation.Async  * *.*(..))")
public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable {
    Span span = this.tracer.createSpan(pjp.getSignature().getName());
    this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, ASYNC_COMPONENT);
    this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getClassNameKey(),
            pjp.getTarget().getClass().getSimpleName());
    this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getMethodNameKey(),
            pjp.getSignature().getName());
    try {//from   w ww.  j a  v a 2  s .  com
        return pjp.proceed();
    } finally {
        this.tracer.close(span);
    }
}

From source file:com.yoho.core.trace.instrument.scheduling.TraceSchedulingAspect.java

License:Apache License

@Around("execution (@org.springframework.scheduling.annotation.Scheduled  * *.*(..))")
public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable {
    String spanName = pjp.getSignature().getName();
    Span span = this.tracer.createSpan(spanName);
    this.tracer.addTag(Span.SPAN_LOCAL_COMPONENT_TAG_NAME, SCHEDULED_COMPONENT);
    this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getClassNameKey(),
            pjp.getTarget().getClass().getSimpleName());
    this.tracer.addTag(this.traceKeys.getAsync().getPrefix() + this.traceKeys.getAsync().getMethodNameKey(),
            pjp.getSignature().getName());
    try {/*  ww w  .  j  a  v  a  2  s .  c o m*/
        return pjp.proceed();
    } finally {
        this.tracer.close(span);
    }
}

From source file:com.zhaimi.message.aop.AbstractSendMessageAdvice.java

License:Apache License

/**
 * Get method of joinpoint//from www .ja  va2  s.  c  o  m
 * @param pjp
 * @return
 */
protected Method getMethod(ProceedingJoinPoint pjp) {

    Class<?> clazz = pjp.getTarget().getClass();
    String methodName = pjp.getSignature().getName();
    Method method = null;

    int argCount = pjp.getArgs().length;
    //      Object[] args = pjp.getArgs();
    //      Class<?>[] argClasses = new Class[args.length];
    //      for (int i = 0; i < args.length; i++) {
    //         Class<?> argClass = args[i].getClass();
    //         
    //         argClass = convertActualClass( argClass );
    //         argClasses[i] = args[i]!=null ? args[i].getClass() : null;
    //      }
    try {
        String key = clazz.getName() + "." + methodName + "#" + argCount;
        if ((method = methodCache.get(key)) == null) {
            method = getMethodFromClass(clazz, methodName, argCount);

            if (method != null) {
                methodCache.put(key, method);
            } else {
                log.error("AOP pointcut method not found! methodName={},argCount={}", methodName, argCount);
            }
        }

    } catch (Exception e) {
        throw new RuntimeException("Method not found!" + clazz.getName() + "." + methodName, e);
    }
    return method;
}

From source file:curly.commons.logging.MethodExecutionAspectInterceptor.java

License:Apache License

@Around(value = "execution(* *(..)) && @annotation(loggable)) ", argNames = "joinPoint, loggable")
public Object invoke(ProceedingJoinPoint joinPoint, Loggable loggable) throws Throwable {
    if (executionEnabled) {
        StopWatch watch = new StopWatch(joinPoint.toShortString());
        watch.start();//  w  ww . j  a  v  a2  s .  c  om
        try {
            return joinPoint.proceed();
        } finally {
            watch.stop();
            synchronized (this) {
                if (actuatorEnabled && (gaugeService != null)) {
                    String gagueName = "gauge.execution." + joinPoint.getTarget() + "."
                            + joinPoint.getSignature().getName();
                    gaugeService.submit(gagueName, watch.getLastTaskTimeMillis());
                }
                log(loggable.value(), joinPoint.getTarget().getClass(), "Executed method {} in {} ms",
                        joinPoint.getSignature().getName(), watch.getLastTaskTimeMillis());
            }
        }

    }
    return joinPoint.proceed();
}

From source file:de.accso.performancetesting.tools.PerformanceLogger.java

License:Apache License

private Object measureTime(ProceedingJoinPoint thisJoinPoint, String tag) throws Throwable {
    StopWatch sp = new StopWatch();
    sp.start();/*  ww  w .j a  va  2s.  c  om*/
    Object result = thisJoinPoint.proceed();
    sp.stop();
    logger.info(append("durationinmillis", sp.getTotalTimeMillis()).and(append("tag", tag))
            .and(append("req_id", CTX_HOLDER.get().reqId)).and(append("url", getCtxUrl()))
            .and(append("servicename", thisJoinPoint.getTarget().getClass().getCanonicalName() + "."
                    + thisJoinPoint.getSignature().getName())),
            "Performance");

    return result;
}

From source file:de.alexandria.cms.frontend.webapp.aop.AopMethodLogger.java

License:Apache License

/**
 *
 * Protokolliert die Laufzeit des join points. Das logging ist nur aktiv, wenn {@link #logger} mindestens
 * debug-Level hat./*from   www.ja v  a2s  . co  m*/
 *
 * @param call
 * @return
 * @throws Throwable
 */
@Around("methodsToBeLogged()")
public Object logMethodDuration(ProceedingJoinPoint call) throws Throwable { // NOSONAR
    // proceed bentigt das Weiterreichen der Exception (throws Throwable)...
    Object returnValue;
    if (logger.isDebugEnabled()) {
        String targetClassName = call.getTarget().getClass().getName();
        String targetMethodName = call.getSignature().getName();
        Logger targetLog = LoggerFactory.getLogger(targetClassName);
        if (targetLog.isDebugEnabled()) {
            StopWatch clock = new StopWatch(getClass().getName());
            try {
                clock.start(call.toShortString());
                returnValue = call.proceed();
            } finally {
                clock.stop();
                String msg = createMsgForLogMethodDuration(targetMethodName, clock.getTotalTimeMillis());
                targetLog.debug(msg);
            }
        } else {
            returnValue = call.proceed();
        }
    } else {
        returnValue = call.proceed();
    }
    return returnValue;
}

From source file:de.beyondjava.examples.scopes.spring.LoggingAspect.java

License:Open Source License

@Around("execution(public java.lang.String *.getCounter(..))")
public Object logBefore(ProceedingJoinPoint joinPoint) throws Throwable {
    String msg = "(null) -> ";
    Object target = joinPoint.getTarget();
    try {/*  ww w  .j av  a  2  s .  co  m*/
        Field counterField = target.getClass().getDeclaredField("counter");
        int counter = (int) counterField.get(target);
        msg = String.valueOf(counter) + " -> ";
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String s = (String) joinPoint.proceed();
    return msg + s;
}