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

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

Introduction

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

Prototype

Method getMethod();

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.ja v  a2  s.c  om*/
            } 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.astonish.metrics.aspectj.MetricAdvice.java

License:Apache License

/**
 * Retrieves the {@link Method} from the {@link ProceedingJoinPoint}.
 * @param pjp//from   www .  j  a  v a 2s.  co  m
 *            the {@link ProceedingJoinPoint}
 * @return the {@link Method}
 */
private Method retrieveMethod(ProceedingJoinPoint pjp) {
    final MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();

    if (method.getDeclaringClass().isInterface()) {
        try {
            method = pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(),
                    method.getParameterTypes());
        } catch (final SecurityException e) {
            LOGGER.warn("Could not retrieve method[{}] for metric interrogation.", method.getName(), e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Could not retrieve method[{}] for metric interrogation.", method.getName(), e);
        }
    }

    return method;
}

From source file:com.att.ajsc.common.trace.TrailLoggerAspect.java

License:BSD License

@Around("pointcut()")
public Object logTrail(ProceedingJoinPoint joinPoint) throws Throwable {

    long startTimeInMilliseconds = System.currentTimeMillis();
    TransactionTrail transactionTrail;/*from  w ww .  ja v a  2  s  . c o m*/
    long endTimeInMilliseconds;
    long durationInMilliseconds;
    String message = null;
    String finalMessage = "";
    String executionDepth = "-";
    String identifier = "";
    String placeholder = "";
    try {
        transactionTrail = (TransactionTrail) context.getBean(TRANSACTION_TRAIL);
    } catch (Exception e1) {
        logger.error(InterceptorMessages.INTERCEPTOR_TRAIL_LOGGER_MESSAGE, e1,
                ((MethodSignature) joinPoint.getSignature()).getMethod().getName());
        return joinPoint.proceed();
    }

    try {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        identifier = method.getDeclaringClass().toString() + method.getName();
        transactionTrail.addInCompleteMethod(identifier);
        long line = transactionTrail.getTrail().split("\n").length + 1;
        placeholder = LINE + line + ":";
        transactionTrail.setTrail(transactionTrail.getTrail() + "\n" + placeholder);
        Tracable tracable = method.getAnnotation(Tracable.class);
        message = tracable.message();
        if (message.length() == 0) {
            message = signature.toString();
        }

        Object result = joinPoint.proceed();
        endTimeInMilliseconds = System.currentTimeMillis();
        int inCompleteMethods = incompleteMethods(transactionTrail.getInCompleteMethods());
        if (inCompleteMethods > 0) {
            for (int i = 0; i < inCompleteMethods; i++) {
                executionDepth = executionDepth + "-";
            }

        }
        durationInMilliseconds = endTimeInMilliseconds - startTimeInMilliseconds;
        finalMessage = executionDepth + durationInMilliseconds + MILLIS + message;
        transactionTrail.setTrail(transactionTrail.getTrail().replace(placeholder, finalMessage));
        transactionTrail.getInCompleteMethods().remove(identifier);
        return result;
    } catch (Throwable e) {
        logger.error(InterceptorMessages.INTERCEPTOR_TRAIL_LOGGER_MESSAGE, e,
                joinPoint.getSignature().toString());
        endTimeInMilliseconds = System.currentTimeMillis();
        int inCompleteMethods = incompleteMethods(transactionTrail.getInCompleteMethods());
        if (inCompleteMethods > 0) {
            for (int i = 0; i < inCompleteMethods; i++) {
                executionDepth = executionDepth + "-";
            }

        }
        durationInMilliseconds = endTimeInMilliseconds - startTimeInMilliseconds;
        finalMessage = executionDepth + durationInMilliseconds + MILLIS + message;
        transactionTrail.setTrail(transactionTrail.getTrail().replace(placeholder, finalMessage));
        transactionTrail.getInCompleteMethods().remove(identifier);
        throw e;
    }

}

From source file:com.autentia.tnt.tracking.annotation.ChangesHistoryAspect.java

License:Open Source License

/**
 * Returns the intercepted method/*from  w  w w . j a  va  2 s  .co  m*/
 * @param call
 * @return
 */
private Method getCallMethod(JoinPoint call) {
    Method metodo = null;
    MethodSignature sig = (MethodSignature) call.getSignature();
    metodo = sig.getMethod();

    return metodo;
}

From source file:com.betfair.tornjak.monitor.aop.MonitorAOP.java

License:Apache License

private MonitorMethod getAnnotation(final ProceedingJoinPoint pjp) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    MonitorMethod fromSignature = signature.getMethod().getAnnotation(MonitorMethod.class);
    if (fromSignature != null) {
        return fromSignature;
    }//from   w w w . ja  v a  2 s  . co m
    // right, couldn't find it on the method signature, but we might be looking at an implementation of an interface
    // so now look at the target object/class
    try {
        Method m = pjp.getTarget().getClass().getDeclaredMethod(signature.getName(),
                signature.getParameterTypes());
        return m.getAnnotation(MonitorMethod.class);
    } catch (NoSuchMethodException e) {
        // hmm, not sure we should ever see this
        throw new IllegalStateException("Couldn't find method that was called on the object it was called on");
    }
}

From source file:com.brienwheeler.lib.monitor.work.impl.MonitoredWorkAspect.java

License:Open Source License

@SuppressWarnings({ "unchecked", "rawtypes" })
@Around("monitoredWorkPointcut()")
public Object aroundMonitoredWork(final ProceedingJoinPoint joinPoint) throws InterruptedException {
    ValidationUtils.assertTrue(joinPoint.getTarget() instanceof IWorkMonitorProvider,
            "@MonitoredWork target must be subclass of IWorkMonitorProvider");
    ValidationUtils.assertTrue(joinPoint.getSignature() instanceof MethodSignature,
            "@MonitoredWork signature must be a method");

    final WorkMonitor workMonitor = ((IWorkMonitorProvider) joinPoint.getTarget()).getWorkMonitor();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    MonitoredWork annotation = signature.getMethod().getAnnotation(MonitoredWork.class);

    final String workName = annotation != null && !annotation.value().isEmpty() ? annotation.value()
            : signature.getName();/*ww w  .  ja v a2s  .co m*/

    long start = System.currentTimeMillis();
    try {
        Object ret = joinPoint.proceed();
        workMonitor.recordWorkOk(workName, System.currentTimeMillis() - start);
        return ret;
    } catch (InterruptedException e) {
        workMonitor.recordWorkError(workName, System.currentTimeMillis() - start);
        Thread.currentThread().interrupt();
        throw e;
    } catch (RuntimeException e) {
        workMonitor.recordWorkError(workName, System.currentTimeMillis() - start);
        throw e;
    } catch (Error e) {
        workMonitor.recordWorkError(workName, System.currentTimeMillis() - start);
        throw e;
    } catch (Throwable e) {
        workMonitor.recordWorkError(workName, System.currentTimeMillis() - start);
        throw new RuntimeException(e);
    }
}

From source file:com.canelmas.let.RuntimePermissionRequest.java

License:Apache License

private Object proceed(final boolean retry) {

    MethodSignature signature = (MethodSignature) joinPoint.getSignature();

    Method method = signature.getMethod();

    final String[] permissionList = method.getAnnotation(AskPermission.class).value();

    Logger.log(">>> " + signature.getName() + "() requires " + permissionList.length + " permission");

    //  Permissions to ask and to show rationales
    final List<String> permissionsToAsk = new ArrayList<>();
    final List<String> permissionsToExplain = new ArrayList<>();

    final LetContext letContext = new LetContext(source);

    for (String permission : permissionList) {

        Logger.log("\t" + permission);

        if (!isPermissionValid(permission)) {
            throw new LetException("Permission name not valid!");
        } else {//from   w  ww .j a va  2s  .c om

            final int permissionResult = ContextCompat.checkSelfPermission(letContext.getActivity(),
                    permission);

            Logger.log("\t\talreadyGranted=" + String.valueOf(permissionResult != -1));

            if (permissionResult != PackageManager.PERMISSION_GRANTED) {

                final boolean showRationale = ActivityCompat
                        .shouldShowRequestPermissionRationale(letContext.getActivity(), permission);
                Logger.log("\t\tshowRationale=" + showRationale);

                if (showRationale && !retry) {
                    permissionsToExplain.add(permission);
                } else {
                    permissionsToAsk.add(permission);
                }

            }

        }

    }

    /**
     *  -Show rationales if necessary and return, before making any permission request
     *  -Trigger necessary permission request and return
     *  -Permissions needed already granted, no need to make request; proceed with the actual method
     */
    RuntimePermissionListener listener = RuntimePermissionListener.class.isInstance(source)
            ? (RuntimePermissionListener) source
            : null;

    if (!permissionsToExplain.isEmpty()) {

        Logger.log("<<< Should show Rationale");

        if (null != listener) {
            listener.onShowPermissionRationale(permissionsToExplain,
                    new RuntimePermissionRequest(joinPoint, source));
        } else {
            throw new LetException(source + " or its parent should implement RuntimePermissionListener");
        }

        return null;

    } else if (!permissionsToAsk.isEmpty()) {

        Logger.log("<<< Making permission request");

        final int requestCode = PERMISSIONS_REQUEST_CODE.getAndIncrement() & 0xff;

        DelayedTasks.add(new DelayedTasks.Task(permissionsToAsk, requestCode, joinPoint));

        letContext.requestPermissions(permissionsToAsk.toArray(new String[] {}), requestCode);

        return null;

    } else {

        Logger.log("<<< Permissions granted");

        try {
            return joinPoint.proceed();
        } catch (Throwable t) {
            throw new LetException("Proceeding with the annotated method failed!", t);
        }

    }

}

From source file:com.cloud.event.ActionEventInterceptor.java

License:Apache License

public Object AroundAnyMethod(ProceedingJoinPoint call) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) call.getSignature();
    Method targetMethod = methodSignature.getMethod();
    if (needToIntercept(targetMethod)) {
        EventVO event = interceptStart(targetMethod);

        boolean success = true;
        Object ret = null;/*  ww w  . j av a  2 s . co  m*/
        try {
            ret = call.proceed();
        } catch (Throwable e) {
            success = false;
            interceptException(targetMethod, event);
            throw e;
        } finally {
            if (success) {
                interceptComplete(targetMethod, event);
            }
        }
        return ret;
    }
    return call.proceed();
}

From source file:com.cloud.utils.db.TransactionContextBuilder.java

License:Apache License

public Object AroundAnyMethod(ProceedingJoinPoint call) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) call.getSignature();
    Method targetMethod = methodSignature.getMethod();
    if (needToIntercept(targetMethod)) {
        Transaction txn = Transaction.open(call.getSignature().getName());
        Object ret = null;/*from www .  jav  a  2  s .c o  m*/
        try {
            ret = call.proceed();
        } finally {
            txn.close();
        }
        return ret;
    }
    return call.proceed();
}

From source file:com.crossbusiness.resiliency.aspect.AbstractAsyncAspect.java

License:Open Source License

/**
 * Intercept the given method invocation, submit the actual calling of the method to
 * the correct task executor and return immediately to the caller.
 * @return {@link Future} if the original method returns {@code Future}; {@code null}
 * otherwise./*  w ww. j av a  2  s.  c  o  m*/
 */
// @Around("asyncMethodExecution()")
private Object doAsync(final ProceedingJoinPoint point, Async asyncConfig) throws Throwable {
    log.debug(point + " -> " + asyncConfig);

    String qualifier = asyncConfig.value();
    MethodSignature targetMethodSig = (MethodSignature) point.getSignature();
    AsyncTaskExecutor executor = getExecutor(targetMethodSig.getMethod(), qualifier);

    if (executor == null) {
        return point.proceed();
    }

    Callable<Object> callable = new Callable<Object>() {
        public Object call() throws Exception {
            try {
                Object result = point.proceed();
                if (result instanceof Future) {
                    return ((Future<?>) result).get();
                }
            } catch (Throwable ex) {
                ReflectionUtils.rethrowException(ex);
            }
            return null;
        }
    };

    Future<?> result = executor.submit(callable);

    if (Future.class.isAssignableFrom(targetMethodSig.getMethod().getReturnType())) {
        return result;
    } else {
        return null;
    }
}