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:org.qifu.base.aspect.ServiceAuthorityCheckAspect.java

License:Apache License

@Around(AspectConstants.LOGIC_SERVICE_PACKAGE)
public Object logicServiceProcess(ProceedingJoinPoint pjp)
        throws AuthorityException, ServiceException, Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Annotation[] annotations = pjp.getTarget().getClass().getAnnotations();
    String serviceId = AspectConstants.getServiceId(annotations);
    Subject subject = SecurityUtils.getSubject();
    Method method = signature.getMethod();
    if (subject.hasRole(Constants.SUPER_ROLE_ALL) || subject.hasRole(Constants.SUPER_ROLE_ADMIN)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }//from ww  w . ja va 2 s. c om
    if (StringUtils.isBlank(serviceId)) { //  service id  
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    if (!this.isServiceAuthorityCheck(annotations)) { //  ServiceAuthority  check=false ? 
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    Annotation[] methodAnnotations = method.getAnnotations();
    if (this.isServiceMethodAuthority(serviceId, methodAnnotations, subject)) {
        SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
                this.getEventId(serviceId, method.getName()), true);
        return pjp.proceed();
    }
    logger.warn("[decline] user[" + subject.getPrincipal() + "] " + pjp.getTarget().getClass().getName() + " - "
            + signature.getMethod().getName());
    SysEventLogSupport.log((String) subject.getPrincipal(), Constants.getSystem(),
            this.getEventId(serviceId, method.getName()), false);
    throw new AuthorityException(SysMessageUtil.get(SysMsgConstants.NO_PERMISSION));
}

From source file:org.raspinloop.fmi.RILLogingAspect.java

License:Apache License

@Around("org.raspinloop.fmi.RILLogingAspect.rilTraceCall()")
public Object myTrace(ProceedingJoinPoint joinPoint) throws Throwable {

    StringBuilder sb = new StringBuilder("ril:--> " + joinPoint.getTarget().getClass().getName() + "."
            + joinPoint.getSignature().getName() + ": ");
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();
    Annotation[][] annotations = method.getParameterAnnotations();
    for (int i = 0; i < annotations.length; ++i) {
        sb.append(joinPoint.getArgs()[i]);
        if (i != annotations.length - 1)
            sb.append(", ");
    }//from  w w w.  j  av a2  s. c  om
    logger.trace(sb.toString());

    Object retVal = null;
    try {
        retVal = joinPoint.proceed();
    } finally {

        logger.trace("ril:<-- " + joinPoint.getTarget().getClass().getName() + "."
                + joinPoint.getSignature().getName() + " retval=" + retVal);
    }
    return retVal;
}

From source file:org.slc.sli.dal.repository.tenancy.apsect.TenantAwareCallAspect.java

License:Apache License

private String extractTenant(JoinPoint jp) {
    MethodSignature ms = (MethodSignature) jp.getSignature();

    String[] params = ms.getParameterNames();

    TenantCall tenantParam = ms.getMethod().getAnnotation(TenantCall.class);

    for (int i = 0; i < params.length; i++) {
        if (tenantParam.param().equals(params[i])) {
            return (String) jp.getArgs()[i];
        }/*  w  w  w . j a v a2  s  .  c o  m*/
    }

    throw new IllegalStateException("Expected method parameter [" + tenantParam.param() + "] was not found");
}

From source file:org.slc.sli.dashboard.web.util.ControllerInputValidatorAspect.java

License:Apache License

/**
 * Around for pointcut defined by controllerMethodInvocation
 * @param joinPoint/*from w  w w  . java2s.c  o m*/
 * @return
 * @throws Throwable
 */
@Around("controllerMethodInvocation()")
public Object aroundController(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
    String[] paramNames = methodSignature.getParameterNames();
    Object[] args = joinPoint.getArgs();

    for (int i = 0; i < args.length; i++) {
        if (checkAnnotations(annotations[i])) {
            validateArg(args[i], paramNames[i]);
        }
    }
    return joinPoint.proceed(args);
}

From source file:org.smallmind.persistence.cache.aop.ORMBasedCacheAsAspect.java

License:Open Source License

@Around(value = "execution(@CacheAs * * (..)) && @annotation(cacheAs) && this(ormDao)", argNames = "thisJoinPoint, cacheAs, ormDao")
public Object aroundCacheAsMethod(ProceedingJoinPoint thisJoinPoint, CacheAs cacheAs, ORMDao ormDao)
        throws Throwable {

    Annotation instrumentedAnnotation;
    MethodSignature methodSignature;
    Method executedMethod = null;
    String metricSource = null;/*from www  . ja v a2  s. c  o m*/
    boolean timingEnabled;
    long start = 0;
    long stop;

    instrumentedAnnotation = ormDao.getClass().getAnnotation(Instrumented.class);
    if (timingEnabled = (instrumentedAnnotation != null) && ((Instrumented) instrumentedAnnotation).value()) {
        start = System.currentTimeMillis();
    }

    methodSignature = (MethodSignature) thisJoinPoint.getSignature();

    try {

        Type returnType;

        if (cacheAs.time().value() < 0) {
            throw new CacheAutomationError(
                    "The base time(%d) value of a @CacheAs annotation can not be negative",
                    cacheAs.time().value());
        }

        if (cacheAs.time().stochastic() < 0) {
            throw new CacheAutomationError(
                    "The stochastic(%d) attribute of a @CacheAs annotation can not be negative",
                    cacheAs.time().stochastic());
        }

        if (ormDao.getManagedClass().equals(methodSignature.getReturnType())) {
            if (cacheAs.ordered()) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type can't be ordered",
                        cacheAs.comparator().getClass().getName());
            } else if (cacheAs.max() > 0) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type may not define a maximum size",
                        cacheAs.comparator().getClass().getName());
            } else if (!cacheAs.comparator().equals(Comparator.class)) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs which does not return an Iterable type can not register a comparator(%s)",
                        cacheAs.comparator().getClass().getName());
            }

            VectoredDao vectoredDao;

            if ((vectoredDao = ormDao.getVectoredDao()) == null) {
                metricSource = ormDao.getMetricSource();

                return thisJoinPoint.proceed();
            } else {

                VectorKey vectorKey;
                DurableVector vector;

                vectorKey = new VectorKey(VectorCalculator.getVectorArtifact(cacheAs.value(), thisJoinPoint),
                        ormDao.getManagedClass(),
                        Classifications.get(CacheAs.class, thisJoinPoint, cacheAs.value()));

                if ((vector = vectoredDao.getVector(vectorKey)) != null) {
                    if (!vector.isAlive()) {
                        vectoredDao.deleteVector(vectorKey);
                    } else {
                        metricSource = vectoredDao.getMetricSource();

                        return vector.head();
                    }
                }

                Durable durable;

                metricSource = ormDao.getMetricSource();

                if ((durable = (Durable) thisJoinPoint.proceed()) != null) {

                    return vectoredDao.persistVector(vectorKey,
                            vectoredDao.createSingularVector(vectorKey, durable, getTimeToLiveSeconds(cacheAs)))
                            .head();
                }

                return null;
            }
        } else if (Iterable.class.isAssignableFrom(methodSignature.getReturnType())) {
            if ((!cacheAs.comparator().equals(Comparator.class)) && (!cacheAs.ordered())) {
                throw new CacheAutomationError(
                        "A method annotated with @CacheAs has registered a comparator(%s) but is not ordered",
                        cacheAs.comparator().getClass().getName());
            }

            if ((!((returnType = (executedMethod = methodSignature.getMethod())
                    .getGenericReturnType()) instanceof ParameterizedType))
                    || (!ormDao.getManagedClass()
                            .equals(((ParameterizedType) returnType).getActualTypeArguments()[0]))) {
                throw new CacheAutomationError(
                        "Methods annotated with @CacheAs which return an Iterable type must be parameterized to <? extends Iterable<%s>>",
                        ormDao.getManagedClass().getSimpleName());
            }

            VectoredDao vectoredDao;

            if ((vectoredDao = ormDao.getVectoredDao()) == null) {
                metricSource = ormDao.getMetricSource();

                return thisJoinPoint.proceed();
            } else {

                VectorKey vectorKey;
                DurableVector vector;

                vectorKey = new VectorKey(VectorCalculator.getVectorArtifact(cacheAs.value(), thisJoinPoint),
                        ormDao.getManagedClass(),
                        Classifications.get(CacheAs.class, thisJoinPoint, cacheAs.value()));

                if ((vector = vectoredDao.getVector(vectorKey)) != null) {
                    if (!vector.isAlive()) {
                        vectoredDao.deleteVector(vectorKey);
                    } else {
                        metricSource = vectoredDao.getMetricSource();

                        return List.class.isAssignableFrom(methodSignature.getReturnType())
                                ? vector.asBestEffortPreFetchedList()
                                : vector.asBestEffortLazyList();
                    }
                }

                Iterable iterable;

                metricSource = ormDao.getMetricSource();

                if ((iterable = (Iterable) thisJoinPoint.proceed()) != null) {
                    vector = vectoredDao.persistVector(vectorKey,
                            vectoredDao.createVector(vectorKey, iterable,
                                    cacheAs.comparator().equals(Comparator.class) ? null
                                            : cacheAs.comparator().newInstance(),
                                    cacheAs.max(), getTimeToLiveSeconds(cacheAs), cacheAs.ordered()));

                    return List.class.isAssignableFrom(methodSignature.getReturnType())
                            ? vector.asBestEffortPreFetchedList()
                            : vector.asBestEffortLazyList();
                }

                return null;
            }
        } else {
            throw new CacheAutomationError(
                    "Methods annotated with @CacheAs must either return their managed type(%s), or an Iterable parameterized to their managed type <? extends Iterable<%s>>",
                    ormDao.getManagedClass().getSimpleName(), ormDao.getManagedClass().getSimpleName());
        }
    } catch (Throwable throwable) {
        timingEnabled = false;

        throw throwable;
    } finally {
        if (timingEnabled) {
            stop = System.currentTimeMillis();

            if (executedMethod == null) {
                executedMethod = methodSignature.getMethod();
            }

            InstrumentationManager.instrumentWithChronometer(PersistenceManager.getPersistence(), stop - start,
                    TimeUnit.MILLISECONDS,
                    new MetricProperty("durable", ormDao.getManagedClass().getSimpleName()),
                    new MetricProperty("method", executedMethod.getName()),
                    new MetricProperty("source", metricSource));
        }
    }
}

From source file:org.springframework.cloud.sleuth.instrument.async.TraceAsyncAspect.java

License:Apache License

private Method getMethod(ProceedingJoinPoint pjp, Object object) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    return ReflectionUtils.findMethod(object.getClass(), method.getName(), method.getParameterTypes());
}

From source file:org.springframework.cloud.sleuth.instrument.async.TraceAsyncAspectTest.java

License:Apache License

@Before
public void setup() throws NoSuchMethodException {
    MethodSignature signature = Mockito.mock(MethodSignature.class);
    BDDMockito.given(signature.getName()).willReturn("fooBar");
    BDDMockito.given(signature.getMethod()).willReturn(TraceAsyncAspectTest.class.getMethod("setup"));
    BDDMockito.given(this.point.getSignature()).willReturn(signature);
    BDDMockito.given(this.point.getTarget()).willReturn("");
}

From source file:org.squashtest.tm.service.annotation.PreventConcurrentAspect.java

License:Open Source License

private <T> T findAnnotatedParam(ProceedingJoinPoint pjp, Class<? extends Annotation> expected) {
    MethodSignature sig = (MethodSignature) pjp.getSignature();
    Method meth = sig.getMethod();
    Annotation[][] annotations = meth.getParameterAnnotations();
    LOGGER.trace("Advising method {}{}.", pjp.getSignature().getDeclaringTypeName(), meth.getName());

    T annotatedParam = null;//ww  w  . j av a  2  s. com

    argsLoop: for (int iArg = 0; iArg < annotations.length; iArg++) {
        Annotation[] curArg = annotations[iArg];

        annLoop: for (int jAnn = 0; jAnn < curArg.length; jAnn++) {
            if (curArg[jAnn].annotationType().equals(expected)) {
                LOGGER.trace("Found required @{} on arg #{} of method {}",
                        new Object[] { expected.getSimpleName(), iArg, meth.getName() });
                annotatedParam = (T) pjp.getArgs()[iArg];
                break argsLoop;
            }
        }
    }

    if (annotatedParam == null) {
        throw new IllegalArgumentException("I coult not find any arg annotated @" + expected.getSimpleName()
                + " in @PreventConcurrent method '" + pjp.getSignature().getDeclaringTypeName() + '.'
                + meth.getName() + "' This must be a structural programming error");

    }
    return annotatedParam;
}

From source file:org.squashtest.tm.service.annotation.PreventConcurrentAspect.java

License:Open Source License

private <T> T findIdForNamedParam(ProceedingJoinPoint pjp, String paramName,
        Class<? extends Annotation> expected) {
    MethodSignature sig = (MethodSignature) pjp.getSignature();
    Method meth = sig.getMethod();
    Annotation[][] annotations = meth.getParameterAnnotations();
    LOGGER.debug("Prevent Concurency - Advising method {}{}.", pjp.getSignature().getDeclaringTypeName(),
            meth.getName());//from  ww  w  .j  a v  a  2 s  .c  om

    T annotatedParam = null;

    argsLoop: for (int iArg = 0; iArg < annotations.length; iArg++) {
        Annotation[] curArg = annotations[iArg];

        annLoop: for (int jAnn = 0; jAnn < curArg.length; jAnn++) {
            if (curArg[jAnn].annotationType().equals(expected)) {
                String annoValue = findAnnotationParamName(curArg[jAnn]);
                if (annoValue.equals(paramName)) {
                    LOGGER.trace("Found required @{} on arg #{} of method {}",
                            new Object[] { expected.getSimpleName(), iArg, meth.getName() });
                    annotatedParam = (T) pjp.getArgs()[iArg];
                } else {
                    throw new IllegalArgumentException("I coult not find any arg annotated @"
                            + expected.getSimpleName() + " with a value of " + paramName
                            + " in @PreventConcurrent method '" + pjp.getSignature().getDeclaringTypeName()
                            + '.' + meth.getName() + ". Instead an @Id was found with a value of " + annoValue
                            + "' This must be a structural programming error");
                }
                break argsLoop;
            }
        }
    }

    if (annotatedParam == null) {
        throw new IllegalArgumentException("I coult not find any arg annotated @" + expected.getSimpleName()
                + " in @PreventConcurrent method '" + pjp.getSignature().getDeclaringTypeName() + '.'
                + meth.getName() + "' This must be a structural programming error");
    }
    return annotatedParam;
}

From source file:org.talend.daikon.security.access.RequiresAuthorityAspect.java

License:Open Source License

/**
 * The interceptor method for method annotated with {@link RequiresAuthority}.
 *
 * @param pjp The method invocation./*from w w  w.  j a v a 2 s  .  c  om*/
 * @return The object
 * @throws Throwable Throws {@link org.springframework.security.access.AccessDeniedException} in case of denied
 *                   access to the invoked method.
 */
@Around("@annotation(org.talend.daikon.security.access.RequiresAuthority)")
public Object requires(ProceedingJoinPoint pjp) throws Throwable {
    final Authentication authentication = ofNullable(getContext().getAuthentication()).orElse(ANONYMOUS);
    LOGGER.debug("Checking @Required access on {} for user {}.", pjp, authentication);

    final MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    final Method method = methodSignature.getMethod();

    final RequiresAuthority annotation = method.getAnnotation(RequiresAuthority.class);
    if (annotation == null) {
        throw new IllegalArgumentException("Missing @RequiresAuthority annotation."); // Rather unexpected
    }

    final String[] authorityArray = annotation.authority();
    final Supplier<Stream<String>> authorityStreamSupplier = () -> Stream.of(authorityArray)
            .filter(StringUtils::isNotBlank);

    final String[] valueArray = annotation.value();
    final Supplier<Stream<String>> valueStreamSupplier = () -> Stream.of(valueArray)
            .filter(StringUtils::isNotBlank);

    Supplier<Stream<String>> streamSupplier = null;

    if (authorityStreamSupplier.get().count() > 0) {
        streamSupplier = authorityStreamSupplier;
    } else if (valueStreamSupplier.get().count() > 0) {
        streamSupplier = valueStreamSupplier;
    }

    if (streamSupplier != null && streamSupplier.get().noneMatch(RequiresAuthorityAspect::isAllowed)) {
        LOGGER.debug("Access denied for user {} on {}.", authentication, method);
        final Class<? extends AccessDenied> onDeny = annotation.onDeny();
        final AccessDenied accessDenied;
        try {
            accessDenied = onDeny.newInstance();
            return accessDenied.onDeny(annotation, method, pjp.getArgs());
        } catch (InstantiationException noInstance) {
            LOGGER.error("Unable to use on deny custom class {}", onDeny.getName(), noInstance);
            throw new AccessDeniedException("Access denied for " + method.getName() + ".", noInstance);
        }
    }

    LOGGER.debug("Access allowed for user {} on {}.", authentication, method);
    return pjp.proceed();
}