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:es.frnd.logging.MethodLoggingAdvice.java

License:Open Source License

/**
 * Emits the log message from a {@link Logging} annotation, using the method
 * call's parameter list as the formatting parameters.
 *
 * @param call the method call being intercepted.
 * @param logAnnotation the log annotation.
 *///from   w w w .j  a v  a  2s.c  o  m
@Before(value = "execution(* *(..)) and @annotation(logAnnotation)", argNames = "logAnnotation")
public void logBefore(JoinPoint call, Logging logAnnotation) {
    Logger logger = extractLogger(call);
    final Severity severity = logAnnotation.severity();
    if (!severity.isEnabled(logger)) {
        return;
    }
    MethodSignature signature = (MethodSignature) call.getSignature();
    Annotation[][] annotations = signature.getMethod().getParameterAnnotations();
    String methodName = signature.getName();
    String message = messageCache.getMessage(MessageType.BEFORE, logAnnotation, methodName, annotations);
    final Object[] args = messageCache.extractArguments(call.getArgs(), annotations);
    severity.log(logger, message, methodName, args);
}

From source file:es.frnd.logging.MethodLoggingAdvice.java

License:Open Source License

/**
 * Emits the log message from a {@link Logging} annotation, using the
 * method's return value as the (sole) formatting parameter.
 *
 * @param call the method call being intercepted.
 * @param logAnnotation the log annotation.
 *///w w w . j  av a2 s.c  om
@AfterReturning(pointcut = "execution(* *(..)) and @annotation(logAnnotation)", returning = "returnValue", argNames = "logAnnotation, returnValue")
public void logReturn(JoinPoint call, Logging logAnnotation, Object returnValue) {
    Logger logger = extractLogger(call);
    final Severity severity = logAnnotation.severity();
    if (!severity.isEnabled(logger)) {
        return;
    }
    MethodSignature signature = (MethodSignature) call.getSignature();
    Annotation[][] annotations = signature.getMethod().getParameterAnnotations();
    String methodName = signature.getName();
    String message = messageCache.getMessage(MessageType.AFTER, logAnnotation, methodName, annotations);
    severity.log(logger, message, methodName, returnValue);
}

From source file:es.frnd.logging.MethodLoggingAdvice.java

License:Open Source License

/**
 * Emits the log message from a {@link Logging} annotation, including the
 * method call's thrown exception.//from  w  w  w. j a  v a2 s  .  c om
 *
 * @param call the method call being intercepted.
 * @param logAnnotation the log annotation.
 */
@AfterThrowing(pointcut = "execution(* *(..)) and @annotation(logAnnotation)", throwing = "exception", argNames = "logAnnotation, exception")
public void logException(JoinPoint call, Logging logAnnotation, Throwable exception) {
    Logger logger = extractLogger(call);
    final Severity severity = logAnnotation.severity();
    if (!severity.isEnabled(logger)) {
        return;
    }
    MethodSignature signature = (MethodSignature) call.getSignature();
    Annotation[][] annotations = signature.getMethod().getParameterAnnotations();
    String methodName = signature.getName();
    String message = messageCache.getMessage(MessageType.EXCEPTION, logAnnotation, methodName, annotations);
    severity.logException(logger, message, methodName, exception);
}

From source file:fi.helsinki.opintoni.aop.logging.LoggingAspect.java

License:Open Source License

private List<Annotation> getMethodAnnotations(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    String methodName = signature.getMethod().getName();
    Class<?>[] parameterTypes = signature.getMethod().getParameterTypes();
    return Lists.newArrayList(
            joinPoint.getTarget().getClass().getMethod(methodName, parameterTypes).getAnnotations());
}

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 ww  w  .  jav a 2  s  .  co m*/
            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);
        }
    }
}

From source file:gov.nih.nci.cabig.ctms.acegi.csm.authorization.JoinPointPrivilegeAndObjectIdGenerator.java

License:BSD License

@Override
protected String[] getObjectPrivilege(Object object) {
    String[] objectPrivilege = null;
    if (object != null) {
        assertSupports(object);/*from  ww w.  j a v a 2  s  . c  om*/
        JoinPoint joinPoint = (JoinPoint) object;
        MethodSignature sig = (MethodSignature) joinPoint.getSignature();
        Class klass = sig.getDeclaringType();
        Method method = sig.getMethod();
        Object[] params = joinPoint.getArgs();
        for (AspectJExpressionPointcut pointcut : this.internalObjectPrivilegeMap.keySet()) {
            if (pointcut.matches(method, klass, params)) {
                objectPrivilege = this.internalObjectPrivilegeMap.get(pointcut);
                break;
            }
        }
    }
    return objectPrivilege;
}

From source file:io.opencensus.contrib.spring.aop.CensusSpringAspect.java

License:Apache License

/**
 * trace handles methods executed with the `@Traced` annotation. A new span will be created with
 * an optionally customizable span name.
 *
 * @param call the join point to execute
 * @return the result of the invocation// w w w .  ja  va 2s. com
 * @throws Throwable if the underlying target throws an exception
 * @since 0.16.0
 */
@Around("@annotation(io.opencensus.contrib.spring.aop.Traced)")
public Object trace(ProceedingJoinPoint call) throws Throwable {
    MethodSignature signature = (MethodSignature) call.getSignature();
    Method method = signature.getMethod();

    Traced annotation = method.getAnnotation(Traced.class);
    if (annotation == null) {
        return call.proceed();
    }
    String spanName = annotation.name();
    if (spanName.isEmpty()) {
        spanName = method.getName();
    }

    return Handler.proceed(call, tracer, spanName);
}

From source file:io.renren.common.aspect.DataFilterAspect.java

License:Apache License

/**
 * ??SQL//from ww w  . j a v  a 2 s .  c  o m
 */
private String getSQLFilter(SysUserEntity user, JoinPoint point) {
    MethodSignature signature = (MethodSignature) point.getSignature();
    DataFilter dataFilter = signature.getMethod().getAnnotation(DataFilter.class);
    //???
    String tableAlias = dataFilter.tableAlias();
    if (StringUtils.isNotBlank(tableAlias)) {
        tableAlias += ".";
    }

    //ID
    Set<Long> deptIdList = new HashSet<>();

    //ID
    List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
    if (roleIdList.size() > 0) {
        List<Long> userDeptIdList = sysRoleDeptService
                .queryDeptIdList(roleIdList.toArray(new Long[roleIdList.size()]));
        deptIdList.addAll(userDeptIdList);
    }

    //?ID
    if (dataFilter.subDept()) {
        List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(user.getDeptId());
        deptIdList.addAll(subDeptIdList);
    }

    StringBuilder sqlFilter = new StringBuilder();
    sqlFilter.append(" (");

    if (deptIdList.size() > 0) {
        sqlFilter.append(tableAlias).append(dataFilter.deptId()).append(" in(")
                .append(StringUtils.join(deptIdList, ",")).append(")");
    }

    //????
    if (dataFilter.user()) {
        if (deptIdList.size() > 0) {
            sqlFilter.append(" or ");
        }
        sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getUserId());
    }

    sqlFilter.append(")");

    return sqlFilter.toString();
}

From source file:io.renren.common.aspect.SysLogAspect.java

License:Apache License

private void saveSysLog(ProceedingJoinPoint joinPoint, long time) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();

    SysLogEntity sysLog = new SysLogEntity();
    SysLog syslog = method.getAnnotation(SysLog.class);
    if (syslog != null) {
        //??/*from ww w  .  ja  va2 s .c  o m*/
        sysLog.setOperation(syslog.value());
    }

    //??
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = signature.getName();
    sysLog.setMethod(className + "." + methodName + "()");

    //?
    Object[] args = joinPoint.getArgs();
    try {
        String params = new Gson().toJson(args[0]);
        sysLog.setParams(params);
    } catch (Exception e) {

    }

    //?request
    HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
    //IP?
    sysLog.setIp(IPUtils.getIpAddr(request));

    //??
    String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername();
    sysLog.setUsername(username);

    sysLog.setTime(time);
    sysLog.setCreateDate(new Date());
    //?
    sysLogService.insert(sysLog);
}

From source file:it.tidalwave.northernwind.aspect.DebugProfilingAspect.java

License:Apache License

@Nonnull
private static <T extends Annotation> T getAnnotation(final @Nonnull ProceedingJoinPoint pjp,
        final @Nonnull Class<T> annotationClass) throws NoSuchMethodException {
    final MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();

    if (method.getDeclaringClass().isInterface()) // FIXME && annotation inheritance -- FIXME also ancestor class
    {/*from  ww w.  ja  va2  s .  c  o m*/
        final String methodName = pjp.getSignature().getName();
        method = pjp.getTarget().getClass().getDeclaredMethod(methodName, method.getParameterTypes());
    }

    return method.getAnnotation(annotationClass);
}