Java Examples for org.aspectj.lang.reflect.MethodSignature

The following java examples will help you to understand the usage of org.aspectj.lang.reflect.MethodSignature. These source code samples are taken from different open source projects.

Example 1
Project: jcloudscale-master  File: JUnitTestSeparatorAspect.java View source code
@Before("execution(@org.junit.Test void *.*(..))")
public void runTest(JoinPoint jp) {
    MethodSignature method = (MethodSignature) jp.getSignature();
    Object that = jp.getThis();
    System.err.println("############################################################");
    System.err.println("############################################################");
    System.err.println("Launching test " + that.getClass().getCanonicalName() + "." + method.getName() + "()");
    System.err.println("############################################################");
    System.err.println("############################################################");
}
Example 2
Project: jforth-config-master  File: DynamicPropertyAspect.java View source code
@Around("execution(public * get*()) && @annotation(org.xforth.config.aop.DynamicValue)")
public Object dynamicValueSet(ProceedingJoinPoint pjp) throws Throwable {
    final MethodSignature signature = (MethodSignature) pjp.getSignature();
    DynamicValue valueAno = signature.getMethod().getAnnotation(DynamicValue.class);
    if (valueAno != null) {
        String propKey = valueAno.value();
        if (logger.isDebugEnabled()) {
            logger.debug("xforth dynamicValueSet propKey key:" + propKey + " value:" + configBundle.get(propKey));
        }
        try {
            return configBundle.get(propKey);
        } catch (Throwable e) {
            logger.error("Method name:{} dynamicValueSet error:{}", signature.getMethod().getName(), e);
        }
    }
    Object result = pjp.proceed();
    return result;
}
Example 3
Project: redis-de-cache-a-nosql-master  File: RedisAnnotationHAAspect.java View source code
@Around("execution(* com.qconsp..*.*(..)) && @annotation(redisCached)")
private Object around(ProceedingJoinPoint pjp, final RedisCached redisCached) throws Throwable {
    String json = jedis.get(pjp.getArgs()[0].toString());
    Object o = null;
    if (json != null) {
        Envelope envelope = gson.fromJson(json, Envelope.class);
        Class type = ((MethodSignature) pjp.getSignature()).getReturnType();
        o = gson.fromJson(envelope.json, type);
        if (o != null && currentTimeMillis() <= envelope.expire) {
            System.out.println("&&& Recuperado pelo REDIS!");
            return o;
        }
    }
    try {
        o = pjp.proceed();
    } catch (DaoException e) {
        if (o != null) {
            System.out.println("&&& Recuperado pelo REDIS! Fonte não disponível!");
            return o;
        }
        throw e;
    }
    System.out.println("&&& Recuperado pelo BANCO! ");
    Envelope envelope = new Envelope(gson.toJson(o), o.getClass(), currentTimeMillis() + (redisCached.secondsToCache() * 1000));
    jedis.setex(pjp.getArgs()[0].toString(), 60 * 60 * 24 * 7, gson.toJson(envelope));
    return o;
}
Example 4
Project: SAF-AOP-master  File: TraceAspect.java View source code
private Object traceMethod(final ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    String className = methodSignature.getDeclaringType().getSimpleName();
    String methodName = methodSignature.getName();
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Object result = joinPoint.proceed();
    stopWatch.stop();
    L.i(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
    return result;
}
Example 5
Project: spring-boot-web-blank-master  File: ServiceLoggingAop.java View source code
@Around("execution(public * com.github.yingzhuo.service.impl.*.*(..))")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    if (!enabled) {
        return joinPoint.proceed();
    } else {
        final Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        long start = System.currentTimeMillis();
        final Object obj = joinPoint.proceed();
        long end = System.currentTimeMillis();
        LOGGER.info("{} - ({} millis)", method, end - start);
        return obj;
    }
}
Example 6
Project: alien4cloud-master  File: ToscaContextualAspect.java View source code
@Around("@annotation(alien4cloud.tosca.context.ToscaContextual)")
public Object ensureContext(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    Method m = ms.getMethod();
    boolean requireNew = m.getAnnotation(ToscaContextual.class).requiresNew();
    boolean initContext = false;
    ToscaContext.Context existingContext = ToscaContext.get();
    if (requireNew || existingContext == null) {
        initContext = true;
    }
    try {
        // try to find dependencies from parameters
        if (initContext) {
            Set<CSARDependency> dependencies = findDependencies(joinPoint.getArgs());
            log.debug("Initializing Tosca Context with dependencies {}", dependencies);
            ToscaContext.init(dependencies);
        }
        return joinPoint.proceed();
    } finally {
        if (initContext) {
            log.debug("Destroying Tosca Context");
            ToscaContext.destroy();
        }
        if (existingContext != null) {
            log.debug("Set back the existing context");
            ToscaContext.set(existingContext);
        }
    }
}
Example 7
Project: allure1-master  File: AllureStepsAspects.java View source code
@Before("anyMethod() && withStepAnnotation()")
public void stepStart(JoinPoint joinPoint) {
    String stepTitle = createTitle(joinPoint);
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    StepStartedEvent startedEvent = new StepStartedEvent(getName(methodSignature.getName(), joinPoint.getArgs()));
    if (!stepTitle.isEmpty()) {
        startedEvent.setTitle(stepTitle);
    }
    ALLURE.fire(startedEvent);
}
Example 8
Project: Android-AOPExample-master  File: TraceAspect.java View source code
@Around("methodAnnotatedWithDebugTrace() || constructorAnnotatedDebugTrace()")
public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    String className = methodSignature.getDeclaringType().getSimpleName();
    String methodName = methodSignature.getName();
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Object result = joinPoint.proceed();
    stopWatch.stop();
    DebugLog.log(className, buildLogMessage(methodName, stopWatch.getTotalTimeMillis()));
    return result;
}
Example 9
Project: aspectj-in-action-code-master  File: AnnotationDrivenTransactionManagementAspect.java View source code
public TransactionAttributeWithRollbackRules getTransactionAttribute(JoinPoint jp) {
    MethodSignature jpSignature = (MethodSignature) jp.getSignature();
    Transactional typeAnnotation = AnnotationUtils.findAnnotation(jpSignature.getDeclaringType(), Transactional.class);
    Transactional methodAnnotation = AnnotationUtils.findAnnotation(jpSignature.getMethod(), Transactional.class);
    return TransactionManagementUtil.createTransactionAttribute(typeAnnotation, methodAnnotation);
}
Example 10
Project: DataHubSystem-master  File: CacheAspectDefinition.java View source code
@AfterReturning("@annotation(fr.gael.dhus.spring.cache.IncrementCache)")
public void updateCache(JoinPoint joinPoint) {
    IncrementCache annotation = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(IncrementCache.class);
    Cache cache = cacheManager.getCache(annotation.name());
    if (cache != null) {
        synchronized (cache) {
            Integer old_value = cache.get(annotation.key(), Integer.class);
            cache.clear();
            if (old_value == null) {
                return;
            }
            cache.put(annotation.key(), (old_value + annotation.value()));
        }
    }
}
Example 11
Project: db-util-master  File: ReflectionUtils.java View source code
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;
    }
    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);
}
Example 12
Project: fluxtream-app-master  File: NewRelicTransactionAspect.java View source code
private void logArguments(ProceedingJoinPoint pjp, String httpMethod) {
    try {
        StringBuilder sb = new StringBuilder(httpMethod).append(" ");
        final Path classPathAnnotation = pjp.getTarget().getClass().getAnnotation(Path.class);
        if (classPathAnnotation != null)
            sb.append(classPathAnnotation.value());
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        final Path methodPathAnnotation = method.getAnnotation(Path.class);
        if (methodPathAnnotation != null)
            sb.append(methodPathAnnotation.value());
        NewRelic.setTransactionName(null, sb.toString());
    } catch (Throwable t) {
        logger.warn("Could not log arguments for join point: " + pjp);
    }
}
Example 13
Project: frodo-master  File: LogObservable.java View source code
@Pointcut(METHOD)
public static boolean methodAnnotatedWithRxLogObservable(ProceedingJoinPoint joinPoint) {
    final FrodoProceedingJoinPoint frodoJoinPoint = new FrodoProceedingJoinPoint(joinPoint);
    final Annotation annotation = frodoJoinPoint.getAnnotation(RxLogObservable.class);
    return ((MethodSignature) joinPoint.getSignature()).getReturnType() == Observable.class && ((RxLogObservable) annotation).value() != RxLogObservable.Scope.NOTHING;
}
Example 14
Project: funiture-master  File: RoutingDataSourceAdvisor.java View source code
@Around("routingDataSource()")
public Object routing(ProceedingJoinPoint joinPoint) throws Exception {
    Class<?> clazz = joinPoint.getTarget().getClass();
    String className = clazz.getName();
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    String methodName = method.getName();
    Object[] arguments = joinPoint.getArgs();
    String key;
    RoutingDataSource routingDataSource = method.getAnnotation(RoutingDataSource.class);
    key = routingDataSource.value().getKey();
    log.info("Routing to datasource({}) in {}.{}, args={}", key, className, methodName, arguments);
    Object result = null;
    DataSourceKeyHolder.set(key);
    try {
        checkIfCompatible(clazz, method);
        result = joinPoint.proceed(arguments);
    } catch (Throwable e) {
        log.error("Error occurred during datasource(key=" + key + ") routing, ", e);
    } finally {
        DataSourceKeyHolder.clear();
    }
    return result;
}
Example 15
Project: HERD-master  File: NamespaceSecurityAdviceTest.java View source code
/**
     * Test case where the current user has both the namespace and the appropriate permissions.
     */
@Test
public void checkPermissionAssertNoExceptionWhenHasPermissions() throws Exception {
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] { "namespace" });
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] { "foo" });
    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser.getNamespaceAuthorizations().add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));
    try {
        namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
        fail();
    }
}
Example 16
Project: hsweb-framework-master  File: DynamicDataSourceAutoConfiguration.java View source code
private <T extends Annotation> T getAnn(ProceedingJoinPoint pjp, Class<T> annClass) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method m = signature.getMethod();
    T a = AnnotationUtils.findAnnotation(m, annClass);
    if (a != null)
        return a;
    Class<?> targetClass = pjp.getTarget().getClass();
    m = org.springframework.util.ClassUtils.getMostSpecificMethod(m, targetClass);
    a = AnnotationUtils.findAnnotation(m, annClass);
    if (a != null)
        return a;
    return AnnotationUtils.findAnnotation(pjp.getTarget().getClass(), annClass);
}
Example 17
Project: jersey-jpa-trenako-master  File: ValidatorAspect.java View source code
@Before("execution(* *(@com.github.carlomicieli.rest.Valid(*)))")
public void validate(JoinPoint jp) throws NoSuchMethodException {
    Set<ConstraintViolation<?>> violations = new HashSet<ConstraintViolation<?>>();
    Method methodSignature = ((MethodSignature) jp.getSignature()).getMethod();
    Method targetMethod = jp.getTarget().getClass().getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
    Annotation[][] annotationParameters = targetMethod.getParameterAnnotations();
    for (int i = 0; i < annotationParameters.length; i++) {
        Annotation[] annotations = annotationParameters[i];
        for (Annotation a : annotations) {
            if (a.annotationType().equals(Valid.class)) {
                Object arg = jp.getArgs()[i];
                violations.addAll(validator.validate(arg));
            }
        }
    }
    if (!violations.isEmpty()) {
        throw new ConstraintViolationException(violations);
    }
}
Example 18
Project: liferay-portal-master  File: AspectJUtil.java View source code
public static Method getMethod(MethodSignature methodSignature) throws NoSuchMethodException {
    Method method = null;
    if (ServerDetector.isWebSphere()) {
        Class<?> declaringType = methodSignature.getDeclaringType();
        String name = methodSignature.getName();
        Class<?>[] parameterTypes = methodSignature.getParameterTypes();
        method = declaringType.getMethod(name, parameterTypes);
    } else {
        method = methodSignature.getMethod();
    }
    return method;
}
Example 19
Project: methodvalidation-integration-master  File: ValidationInterceptor.java View source code
//Match any public methods in a class annotated with @AutoValidating
@Around("execution(public * *(..)) && @within(de.gmorling.methodvalidation.spring.AutoValidating)")
public Object validateMethodInvocation(ProceedingJoinPoint pjp) throws Throwable {
    Object result;
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    MethodValidator methodValidator = validator.unwrap(MethodValidator.class);
    Set<MethodConstraintViolation<Object>> parametersViolations = methodValidator.validateParameters(pjp.getTarget(), signature.getMethod(), pjp.getArgs());
    if (!parametersViolations.isEmpty()) {
        throw new MethodConstraintViolationException(parametersViolations);
    }
    //Execute the method
    result = pjp.proceed();
    Set<MethodConstraintViolation<Object>> returnValueViolations = methodValidator.validateReturnValue(pjp.getTarget(), signature.getMethod(), result);
    if (!returnValueViolations.isEmpty()) {
        throw new MethodConstraintViolationException(returnValueViolations);
    }
    return result;
}
Example 20
Project: spring-auto-master  File: DataSourceSwitchAdviceSupport.java View source code
/*
     * å??射获得标注 查找顺åº?如下
     *   1. 实现类上方法
     *   2. 实现类类型
     *   3. 接�方法上
     *   4. 接�类型
     */
private <T extends Annotation> T findAnnotation(ProceedingJoinPoint joinPoint, Class<T> annotationType) throws Throwable {
    final Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    final Class<?> implCls = joinPoint.getTarget().getClass();
    T anno;
    Method implMethod = implCls.getMethod(method.getName(), method.getParameterTypes());
    anno = implMethod.getDeclaredAnnotation(annotationType);
    if (anno != null) {
        return anno;
    }
    anno = implCls.getAnnotation(annotationType);
    if (anno != null) {
        return anno;
    }
    Class<?>[] interfaces = implCls.getInterfaces();
    for (Class<?> interfaceCls : interfaces) {
        Method ifaceMethod;
        try {
            ifaceMethod = interfaceCls.getMethod(method.getName(), method.getParameterTypes());
        } catch (NoSuchMethodException e) {
            continue;
        } catch (SecurityException e) {
            continue;
        }
        anno = ifaceMethod.getAnnotation(annotationType);
        if (anno != null) {
            return anno;
        }
        anno = interfaceCls.getAnnotation(annotationType);
        if (anno != null) {
            return anno;
        }
    }
    return null;
}
Example 21
Project: stratio-connector-commons-master  File: MethodTimer.java View source code
/**
     * Function that register metrics.
     * @param point
     * @return
     * @throws Throwable
     */
@Around("execution(* *(..)) && @annotation(TimerJ)")
public Object around(ProceedingJoinPoint point) throws Throwable {
    String methodName = MethodSignature.class.cast(point.getSignature()).getMethod().getName();
    String methodArgs = point.getArgs().toString();
    MetricRegistry metricRegistry = Metrics.getRegistry();
    Timer timer;
    String metricName = "Starting method " + methodName + "at " + System.nanoTime();
    synchronized (this) {
        if (metricRegistry.getTimers().containsKey(methodName)) {
            timer = metricRegistry.getTimers().get(metricName);
        } else {
            timer = metricRegistry.register(metricName, new Timer());
        }
    }
    Timer.Context before = timer.time();
    Object result = point.proceed();
    long timeAfter = before.stop();
    logger.debug("Method " + methodName + " with args " + methodArgs + " executed in " + timeAfter + " ns");
    return result;
}
Example 22
Project: T-MVP-master  File: MemoryCacheAspect.java View source code
//在连接点进行方法替�
@Around("methodAnnotated()")
public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    String methodName = methodSignature.getName();
    MemoryCacheManager mMemoryCacheManager = MemoryCacheManager.getInstance();
    StringBuilder keyBuilder = new StringBuilder();
    keyBuilder.append(methodName);
    for (Object obj : joinPoint.getArgs()) {
        if (obj instanceof String)
            keyBuilder.append((String) obj);
        else if (obj instanceof Class)
            keyBuilder.append(((Class) obj).getSimpleName());
    }
    String key = keyBuilder.toString();
    //key规则 : 方法å??+å?‚æ•°1+å?‚æ•°2+...
    Object result = mMemoryCacheManager.get(key);
    LogUtils.showLog("MemoryCache", "key:" + key + "--->" + (result != null ? "not null" : "null"));
    //缓存已有,直接返回
    if (result != null)
        return result;
    //执行原方法
    result = joinPoint.proceed();
    if (//列表�为空
    result instanceof List && result != null && ((List) result).size() > 0 || //字符�为空
    result instanceof String && !TextUtils.isEmpty((String) result) || //对象�为空
    result instanceof Object && result != null)
        //存入缓存
        mMemoryCacheManager.add(key, result);
    LogUtils.showLog("MemoryCache", "key:" + key + "--->" + "save");
    return result;
}
Example 23
Project: yum-repo-server-master  File: MongoTxAspect.java View source code
private MongoTx getMongoTxAnnotation(ProceedingJoinPoint pjp) {
    final Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
    final MethodSignature signature = (MethodSignature) pjp.getSignature();
    final Method mostSpecificMethod = AopUtils.getMostSpecificMethod(signature.getMethod(), targetClass);
    final MongoTx mongoTxAnnotation = mostSpecificMethod.getAnnotation(MongoTx.class);
    if (mongoTxAnnotation == null) {
        throw new IllegalStateException(String.format("cannot determine MongoTx annotation in %s with found target class %s and method %s.", pjp, targetClass, mostSpecificMethod));
    }
    return mongoTxAnnotation;
}
Example 24
Project: AndroidDevMetrics-master  File: ActivityLifecycleAnalyzer.java View source code
@Around("onCreateMethod() || onStartMethod() || onResumeMethod()")
public Object logAndExecute(ProceedingJoinPoint joinPoint) throws Throwable {
    if (!enabled)
        return joinPoint.proceed();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    String methodName = signature.getMethod().getName();
    final Object result;
    if (METHOD_ON_RESUME.equals(methodName)) {
        ActivityLifecycleMetrics.getInstance().logPreOnResume((Activity) joinPoint.getTarget());
        result = executeWithTracingIfEnabled(joinPoint, methodName);
        ActivityLifecycleMetrics.getInstance().logPostOnResume((Activity) joinPoint.getTarget());
    } else if (METHOD_ON_START.equals(methodName)) {
        ActivityLifecycleMetrics.getInstance().logPreOnStart((Activity) joinPoint.getTarget());
        result = executeWithTracingIfEnabled(joinPoint, methodName);
        ActivityLifecycleMetrics.getInstance().logPostOnStart((Activity) joinPoint.getTarget());
    } else if (METHOD_ON_CREATE.equals(methodName)) {
        ActivityLifecycleMetrics.getInstance().logPreOnCreate((Activity) joinPoint.getTarget());
        result = executeWithTracingIfEnabled(joinPoint, methodName);
        ActivityLifecycleMetrics.getInstance().logPostOnCreate((Activity) joinPoint.getTarget());
    } else {
        result = null;
    }
    return result;
}
Example 25
Project: audit4j-spring-master  File: AuditAspect.java View source code
/**
     * Audit Aspect.
     * 
     * @param jointPoint
     *            the joint point
     * @throws Throwable
     *             the throwable
     */
@Before("@within(org.audit4j.core.annotation.Audit) || @annotation(org.audit4j.core.annotation.Audit)")
public void audit(final JoinPoint jointPoint) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) jointPoint.getSignature();
    Method method = methodSignature.getMethod();
    if (method.getDeclaringClass().isInterface()) {
        try {
            method = jointPoint.getTarget().getClass().getDeclaredMethod(jointPoint.getSignature().getName(), method.getParameterTypes());
        } catch (final SecurityException exception) {
            throw new Audit4jRuntimeException("Exception occured while proceding Audit Aspect in Audit4j Spring Integration", exception);
        } catch (final NoSuchMethodException exception) {
            throw new Audit4jRuntimeException("Exception occured while proceding Audit Aspect in Audit4j Spring Integration", exception);
        }
    }
    AuditManager.getInstance().audit(jointPoint.getTarget().getClass(), method, jointPoint.getArgs());
}
Example 26
Project: AutoLoadCache-master  File: AspectjAopInterceptor.java View source code
public Object checkAndProceed(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(Cache.class)) {
        // method.getAnnotationsByType(Cache.class)[0];
        Cache cache = method.getAnnotation(Cache.class);
        return this.proceed(pjp, cache);
    }
    try {
        return pjp.proceed();
    } catch (Throwable e) {
        throw e;
    }
}
Example 27
Project: jadice-webtoolkit-master  File: BasicAspect.java View source code
/**
   * This method needs to be called to set metric name and metric description as well label
   * attribute and label value for this object. The proceeding join point is given by an around
   * ({@link org.aspectj.lang.annotation.Around @Around(..)}) advice.
   * 
   * @param joinPoint The {@link ProceedingJoinPoint} of an around advice.
   */
protected void determineMetricInformation(DataObject<?> data, ProceedingJoinPoint joinPoint, Class<? extends Annotation> clazz) {
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    Annotation annotation = method.getAnnotation(clazz);
    // Get the metric name
    try {
        Method name = annotation.getClass().getMethod("name");
        data.setMetricName((String) name.invoke(annotation));
    } catch (Exception e) {
        System.err.println(e.getLocalizedMessage());
    }
    // Get the metric description
    try {
        Method description = annotation.getClass().getMethod("description");
        data.setMetricDescription((String) description.invoke(annotation));
    } catch (Exception e) {
        System.err.println(e.getLocalizedMessage());
    }
    InstrumentedLabels ils = method.getAnnotation(InstrumentedLabels.class);
    if (null != ils) {
        for (InstrumentedLabel label : ils.value()) {
            data.getLabels().put(label.attr(), label.value());
        }
    }
    InstrumentedLabel il = method.getAnnotation(InstrumentedLabel.class);
    if (null != il) {
        data.getLabels().put(il.attr(), il.value());
    }
}
Example 28
Project: kaleido-repository-master  File: NotNullAspect.java View source code
/**
    * introspect constructor or method argument, in order to detect if parameter annotated {@link NotNull} is null or not. <br/>
    * add useful debug informations too
    * 
    * @param jp
    * @param esjp
    */
void handleArgument(final JoinPoint jp, final JoinPoint.EnclosingStaticPart esjp) {
    debugJoinPoint(LOGGER, jp);
    Annotation[][] parametersAnnotations = null;
    String[] parametersName = null;
    // 1. extract method / constructor parameter static informations
    if (jp.getSignature() instanceof ConstructorSignature) {
        parametersName = ((ConstructorSignature) jp.getSignature()).getParameterNames();
        parametersAnnotations = ((ConstructorSignature) jp.getSignature()).getConstructor().getParameterAnnotations();
    }
    if (jp.getSignature() instanceof MethodSignature) {
        parametersName = ((MethodSignature) jp.getSignature()).getParameterNames();
        parametersAnnotations = ((MethodSignature) jp.getSignature()).getMethod().getParameterAnnotations();
    }
    // 2. introspect input parameters
    if (parametersName != null && parametersAnnotations != null) {
        for (int paramCpt = 0; paramCpt < parametersName.length; paramCpt++) {
            Annotation[] parameterAnnotations = parametersAnnotations[paramCpt];
            if (parameterAnnotations != null) {
                for (Annotation parameterAnnotation : parameterAnnotations) {
                    // parameter annotated with @NotNull + null value
                    if (NotNull.class == parameterAnnotation.annotationType() && jp.getArgs()[paramCpt] == null) {
                        throw new NotNullException(jp.getStaticPart().getSignature().toString(), parametersName[paramCpt], jp.getSignature().toString(), jp.getSourceLocation().toString());
                    }
                }
            }
        }
    }
}
Example 29
Project: nextprot-api-master  File: InstrumentationAspect.java View source code
@Around("execution(* org.nextprot.api.*.controller.*.*(..))")
public Object logServiceInformaton(ProceedingJoinPoint pjp) throws Throwable {
    if (enableInstrumentation) {
        controllerRequestId.set(controllerRequestIdCounter.incrementAndGet());
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Annotation[][] annotations = methodSignature.getMethod().getParameterAnnotations();
        Object[] arguments = pjp.getArgs();
        RequestInfo request = RequestInfoFactory.createRequestInfo(methodSignature.getDeclaringType().getSimpleName() + "#" + methodSignature.getName());
        request.putAll(extractSecurityInfo());
        request.putAll(extractHttpInfo());
        clientRequestManager.startMonitoringClientRequest(request);
        StringBuilder sb = new StringBuilder();
        sb.append("type=Controller;");
        addMethodParameters(sb, methodSignature);
        addArgumentsParameters(sb, arguments, annotations);
        sb.append("controllerRequestId=");
        sb.append(controllerRequestIdCounter.get());
        sb.append(";");
        for (String key : request.keySet()) {
            sb.append(key);
            sb.append("=");
            sb.append(request.get(key));
            sb.append(";");
        }
        long start = System.currentTimeMillis();
        // Proceed to method invocation
        try {
            //LOGGER.info("aspect=before;" + sb);
            Object result = pjp.proceed();
            addTimeElapsed(sb, System.currentTimeMillis() - start);
            addResultParameters(sb, result);
            LOGGER.info("aspect=after;" + sb);
            clientRequestManager.stopMonitoringCurrentRequestInfo();
            controllerRequestId.remove();
            return result;
        } catch (Exception e) {
            addTimeElapsed(sb, System.currentTimeMillis() - start);
            addExceptionParameters(sb, e);
            LOGGER.info("aspect=after;" + sb);
            clientRequestManager.stopMonitoringCurrentRequestInfo(e);
            controllerRequestId.remove();
            throw e;
        }
    } else {
        return pjp.proceed();
    }
}
Example 30
Project: shiro-master  File: BeforeAdviceMethodInvocationAdapter.java View source code
/**
     * Factory method that creates a new {@link BeforeAdviceMethodInvocationAdapter} instance
     * using the AspectJ {@link JoinPoint} provided. If the joint point passed in is not
     * a method joint point, this method throws an {@link IllegalArgumentException}.
     *
     * @param aJoinPoint The AspectJ {@link JoinPoint} to use to adapt the advice.
     * @return The created instance.
     * @throws IllegalArgumentException If the join point passed in does not involve a method call.
     */
public static BeforeAdviceMethodInvocationAdapter createFrom(JoinPoint aJoinPoint) {
    if (aJoinPoint.getSignature() instanceof MethodSignature) {
        return new BeforeAdviceMethodInvocationAdapter(aJoinPoint.getThis(), ((MethodSignature) aJoinPoint.getSignature()).getMethod(), aJoinPoint.getArgs());
    } else if (aJoinPoint.getSignature() instanceof AdviceSignature) {
        return new BeforeAdviceMethodInvocationAdapter(aJoinPoint.getThis(), ((AdviceSignature) aJoinPoint.getSignature()).getAdvice(), aJoinPoint.getArgs());
    } else {
        throw new IllegalArgumentException("The joint point signature is invalid: expected a MethodSignature or an AdviceSignature but was " + aJoinPoint.getSignature());
    }
}
Example 31
Project: SmallMind-master  File: ORMBasedCacheAsAspect.java View source code
@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;
    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().isAssignableFrom(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().isAssignableFrom((Class<?>) ((ParameterizedType) returnType).getActualTypeArguments()[0]))) {
                throw new CacheAutomationError("Methods annotated with @CacheAs which return an Iterable type must be parameterized to <? extends Iterable<? extends %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<? extends %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));
        }
    }
}
Example 32
Project: spring-framework-issues-master  File: AuditAspect.java View source code
@Around("auditMethods()")
public Object audit(ProceedingJoinPoint jp) throws Throwable {
    Throwable exception = null;
    Object retVal = null;
    Method method = AopUtils.getMostSpecificMethod(((MethodSignature) jp.getSignature()).getMethod(), jp.getTarget().getClass());
    logger.debug("inside auditing advice for '" + method.getName() + "'");
    try {
        logger.debug("proceed with original method invocation...");
        retVal = jp.proceed();
        logger.debug("original method invocation completed for method '" + method.getName() + "'");
    } catch (Throwable e) {
        exception = e;
        logger.debug("original method invocation for '" + method.getName() + "' threw exception '" + e.getClass().getName() + "'!");
    }
    Auditable annotation = method.getAnnotation(Auditable.class);
    if (annotation != null) {
        AuditMessage audit = new AuditMessage();
        String actionCode = annotation.actionCode();
        String auditMessage = annotation.auditMessage();
        // determinePrincipal(annotation);
        Person principal = null;
        auditMessage = (exception == null ? "" : "The following exception occurred: " + exception.toString());
        audit.setId(UUID.randomUUID().toString());
        audit.setActionCode(actionCode);
        audit.setMessage(auditMessage);
        audit.setSuccessIndicator(exception == null);
        audit.setActionBy(principal);
        audit.setActionDate(new Date());
        logger.info("audit message=> " + audit);
        logger.debug("persisting audit...");
        if (auditRepository == null) {
            logger.error("<<***************BAD: audit repo is null*************>>");
        }
        auditRepository.save(audit);
        logger.debug("persistance complete!");
    }
    if (exception != null) {
        logger.debug("re-throwing '" + exception.getClass().getName() + "' exception");
        throw exception;
    }
    return retVal;
}
Example 33
Project: spring-insight-plugins-master  File: OperationFTLTest.java View source code
@SuppressWarnings("boxing")
@Test
public void testView() throws Exception {
    JoinPoint jp = mock(JoinPoint.class);
    Signature sig = mock(Signature.class);
    when(jp.getSignature()).thenReturn(sig);
    when(sig.getName()).thenReturn("GreatHeapingMethod");
    when(jp.getArgs()).thenReturn(new String[] { "one", "two" });
    JoinPoint.StaticPart staticPart = mock(JoinPoint.StaticPart.class);
    SourceLocation sl = mock(SourceLocation.class);
    when(sl.getFileName()).thenReturn("Test.java");
    when(sl.getLine()).thenReturn(100);
    when(sl.getWithinType()).thenReturn(this.getClass());
    when(staticPart.getSourceLocation()).thenReturn(sl);
    MethodSignature msig = mock(MethodSignature.class);
    when(staticPart.getSignature()).thenReturn(msig);
    when(jp.getStaticPart()).thenReturn(staticPart);
    // Db
    Operation op = MongoDbOperationCollectionAspect.aspectOf().createOperation(jp);
    op.put(OperationFields.RETURN_VALUE, "my return");
    String content = getRenderingOf(op);
    assertNotNull(content);
    // Cursor
    DBCursor cursor = mock(DBCursor.class);
    when(cursor.getKeysWanted()).thenReturn(new BasicDBObject("everybody", "loves"));
    when(cursor.getQuery()).thenReturn(new BasicDBObject("spring", "insight"));
    when(jp.getTarget()).thenReturn(cursor);
    op = MongoCursorOperationCollectionAspect.aspectOf().createOperation(jp);
    op.put(OperationFields.RETURN_VALUE, "my return");
    content = getRenderingOf(op);
    assertNotNull(content);
    // Collection
    DBCollection collection = mock(DBCollection.class);
    when(collection.getFullName()).thenReturn("this is a super cool collection");
    when(jp.getThis()).thenReturn(collection);
    op = MongoCollectionOperationCollectionAspect.aspectOf().createOperation(jp);
    op.put(OperationFields.RETURN_VALUE, "my return");
    content = getRenderingOf(op);
    assertNotNull(content);
}
Example 34
Project: tsharding-master  File: ReadWriteSplittingAdvice.java View source code
@Around("@annotation(com.mogujie.trade.db.ReadWriteSplitting)")
public Object intercept(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Signature signature = proceedingJoinPoint.getSignature();
    DataSourceType dataSourceType = null;
    if (signature instanceof MethodSignature) {
        // 若已�在事务中 则��处�
        if (RoutingDataSourceTransactionContext.getCurTransactionDataSource() != null) {
            return proceedingJoinPoint.proceed();
        }
        // 若已�设置为Master 则忽略
        if (ReadWriteSplittingContext.isMaster()) {
            return proceedingJoinPoint.proceed();
        }
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        dataSourceType = this.getDataSourceType(method);
    } else {
        // this may not happend.
        throw new ReadWriteSplittingException("ReadWriteSplitting annotation should only used on method. ");
    }
    ReadWriteSplittingContext.set(dataSourceType);
    logger.debug("{} {} using dataSourceOf {} ", proceedingJoinPoint.getTarget(), proceedingJoinPoint.getSignature(), dataSourceType);
    try {
        return proceedingJoinPoint.proceed();
    } finally {
        ReadWriteSplittingContext.clear();
        logger.debug("{} release dataSource of {}", proceedingJoinPoint.getTarget(), dataSourceType);
    }
}
Example 35
Project: Annotations-master  File: MethodLogger.java View source code
/**
     * Log methods in a class.
     *
     * <p>Try NOT to change the signature of this method, in order to keep
     * it backward compatible.
     *
     * @param point Joint point
     * @return The result of call
     * @throws Throwable If something goes wrong inside
     */
@Around(// @checkstyle StringLiteralsConcatenation (7 lines)
"execution(public * (@com.jcabi.aspects.Loggable *).*(..))" + " && !execution(String *.toString())" + " && !execution(int *.hashCode())" + " && !execution(boolean *.canEqual(Object))" + " && !execution(boolean *.equals(Object))" + " && !cflow(call(com.jcabi.aspects.aj.MethodLogger.new()))")
public Object wrapClass(final ProceedingJoinPoint point) throws Throwable {
    final Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
    Object output;
    if (method.isAnnotationPresent(Loggable.class)) {
        output = point.proceed();
    } else {
        output = this.wrap(point, method, method.getDeclaringClass().getAnnotation(Loggable.class));
    }
    return output;
}
Example 36
Project: capture-replay-framework-master  File: JsonDataMapper.java View source code
@Override
public void writeCapturedData(MethodSignature signature, Object returnValue, Object[] arguments) throws DataMappingException {
    Method method = signature.getMethod();
    String captureFileName = getCaptureFileName(method, arguments);
    try {
        File captureFile = captureFileProvider.getCaptureFile(captureFileName);
        enableTypeSupport();
        objectMapper.writeValue(captureFile, new TypeWrapper(returnValue.getClass().getCanonicalName(), returnValue));
    } catch (Exception e) {
        throw new DataMappingException(String.format("Could not write test data to file %s.", captureFileName), e);
    }
}
Example 37
Project: cerebro-master  File: LoggingAspect.java View source code
@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();
    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;
}
Example 38
Project: circuitbreaker-master  File: RateLimiterAspect.java View source code
@Around(value = "matchAnnotatedClassOrMethod(limitedService)", argNames = "proceedingJoinPoint, limitedService")
public Object rateLimiterAroundAdvice(ProceedingJoinPoint proceedingJoinPoint, RateLimiter limitedService) throws Throwable {
    RateLimiter targetService = limitedService;
    Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
    String methodName = method.getDeclaringClass().getName() + "#" + method.getName();
    if (targetService == null) {
        targetService = getRateLimiterAnnotation(proceedingJoinPoint);
    }
    String name = targetService.name();
    io.github.resilience4j.ratelimiter.RateLimiter rateLimiter = getOrCreateRateLimiter(methodName, name);
    return handleJoinPoint(proceedingJoinPoint, rateLimiter, methodName);
}
Example 39
Project: corgi-master  File: GlobalValidation.java View source code
@Around("pointCut()")
protected Object around(ProceedingJoinPoint pjp) throws Throwable {
    BindingResult result = null;
    //jsonp callback method
    String callbackFun = null;
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();
    Annotation[] annotationList = method.getAnnotations();
    Annotation[][] argAnnotations = method.getParameterAnnotations();
    String[] argNames = methodSignature.getParameterNames();
    Object[] args = pjp.getArgs();
    int length = args != null ? args.length : 0;
    if (length != 0) {
        for (int i = 1; i < length; i++) {
            Object object = args[i];
            if (null != object) {
                if (null == result && object instanceof BindingResult) {
                    result = (BindingResult) object;
                }
                if (null != argAnnotations[i] && argAnnotations[i].length > 0) {
                    //检测是�带注解
                    if (null != argAnnotations[i][0] && argAnnotations[i][0] instanceof Callback && null != object && StringUtils.isNotBlank(object.toString())) {
                        //回调函数�能为空
                        callbackFun = object.toString();
                    }
                    if (null != result && null != callbackFun) {
                        //两个都找到了,�以退出循环
                        break;
                    }
                }
            }
        }
    }
    if (writeResult(result, callbackFun)) {
        return null;
    }
    return pjp.proceed(args);
}
Example 40
Project: cyclop-master  File: AopValidator.java View source code
private void executeResponseValidation(ProceedingJoinPoint pjp, Object response) {
    MethodSignature sig = (MethodSignature) pjp.getSignature();
    Method method = sig.getMethod();
    BeanValidator validator = null;
    for (Annotation respAnnotatioin : method.getDeclaredAnnotations()) {
        if (respAnnotatioin.annotationType().isAssignableFrom(NotNull.class) || (respAnnotatioin.annotationType().isAssignableFrom(Valid.class) && response != null)) {
            if (validator == null) {
                validator = createValidator(pjp);
            }
            validator.add("METHOD_RETURN_VALUE", response);
        }
    }
    if (validator != null) {
        validator.validate();
    }
}
Example 41
Project: disconf-master  File: DisconfAspectJ.java View source code
/**
     * 获��置文件数�, �有开�disconf远程�会进行切�
     *
     * @throws Throwable
     */
@Around("anyPublicMethod() && @annotation(disconfFileItem)")
public Object decideAccess(ProceedingJoinPoint pjp, DisconfFileItem disconfFileItem) throws Throwable {
    if (DisClientConfig.getInstance().ENABLE_DISCONF) {
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        //
        // 文件å??
        //
        Class<?> cls = method.getDeclaringClass();
        DisconfFile disconfFile = cls.getAnnotation(DisconfFile.class);
        //
        // Fieldå??
        //
        Field field = MethodUtils.getFieldFromMethod(method, cls.getDeclaredFields(), DisConfigTypeEnum.FILE);
        if (field != null) {
            //
            // 请求仓库�置数�
            //
            DisconfStoreProcessor disconfStoreProcessor = DisconfStoreProcessorFactory.getDisconfStoreFileProcessor();
            Object ret = disconfStoreProcessor.getConfig(disconfFile.filename(), disconfFileItem.name());
            if (ret != null) {
                LOGGER.debug("using disconf store value: " + disconfFile.filename() + " (" + disconfFileItem.name() + " , " + ret + ")");
                return ret;
            }
        }
    }
    Object rtnOb;
    try {
        // 返回原值
        rtnOb = pjp.proceed();
    } catch (Throwable t) {
        LOGGER.info(t.getMessage());
        throw t;
    }
    return rtnOb;
}
Example 42
Project: hugo-master  File: Hugo.java View source code
private static void exitMethod(JoinPoint joinPoint, Object result, long lengthMillis) {
    if (!enabled)
        return;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        Trace.endSection();
    }
    Signature signature = joinPoint.getSignature();
    Class<?> cls = signature.getDeclaringType();
    String methodName = signature.getName();
    boolean hasReturnType = signature instanceof MethodSignature && ((MethodSignature) signature).getReturnType() != void.class;
    StringBuilder builder = new StringBuilder("⇠ ").append(methodName).append(" [").append(lengthMillis).append("ms]");
    if (hasReturnType) {
        builder.append(" = ");
        builder.append(Strings.toString(result));
    }
    Log.v(asTag(cls), builder.toString());
}
Example 43
Project: instrumentation-master  File: MethodTimer.java View source code
private PrometheusTimeMethod getAnnotation(ProceedingJoinPoint pjp) throws NoSuchMethodException {
    assert (pjp.getSignature() instanceof MethodSignature);
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    PrometheusTimeMethod annot = AnnotationUtils.findAnnotation(pjp.getTarget().getClass(), PrometheusTimeMethod.class);
    if (annot != null) {
        return annot;
    }
    // When target is an AOP interface proxy but annotation is on class method (rather than Interface method).
    final String name = signature.getName();
    final Class[] parameterTypes = signature.getParameterTypes();
    return AnnotationUtils.findAnnotation(pjp.getTarget().getClass().getDeclaredMethod(name, parameterTypes), PrometheusTimeMethod.class);
}
Example 44
Project: joinery-master  File: Metrics.java View source code
private static Annotation getAnnotation(final Signature signature, final Class<? extends Annotation> annotationClass) {
    if (signature instanceof ConstructorSignature) {
        final Constructor<?> ctor = ConstructorSignature.class.cast(signature).getConstructor();
        return ctor.getAnnotation(annotationClass);
    } else if (signature instanceof MethodSignature) {
        return MethodSignature.class.cast(signature).getMethod().getAnnotation(annotationClass);
    } else if (signature instanceof FieldSignature) {
        return FieldSignature.class.cast(signature).getField().getAnnotation(annotationClass);
    }
    throw new RuntimeException("Unsupported signature type " + signature.getClass().getName());
}
Example 45
Project: koala-master  File: DataSourceAspect.java View source code
//添加synchronized关键字,��在�一个group下的数��轮训��匀
@Before(value = "all()")
public synchronized void classBefore(JoinPoint jp) {
    MethodSignature sig = (MethodSignature) jp.getSignature();
    Method method = sig.getMethod();
    String name = method.getName();
    Annotation annotation = method.getAnnotation(ChangeTo.class);
    if (annotation != null) {
        return;
    }
    Object obj = jp.getTarget();
    DataSourceDistribute dataSourceDistribute = obj.getClass().getAnnotation(DataSourceDistribute.class);
    DataSourceGroup dataSourceGroup = obj.getClass().getAnnotation(DataSourceGroup.class);
    if (dataSourceDistribute != null) {
        if (dealDataSourceDistribute(dataSourceDistribute, name)) {
            return;
        }
    }
    if (dataSourceGroup != null) {
        dealDataSourceGroup(dataSourceGroup, name);
    }
}
Example 46
Project: let-master  File: RuntimePermissionRequest.java View source code
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 {
            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);
        }
    }
}
Example 47
Project: quadriga-master  File: PublicAccessAspect.java View source code
@Around("within(edu.asu.spring.quadriga.web..*) && @annotation(check)")
public Object checkAccess(ProceedingJoinPoint joinPoint, CheckPublicAccess check) throws Throwable {
    // Get the Method signature and the arguments passed to the method.
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = methodSignature.getMethod();
    Parameter[] paras = method.getParameters();
    Object[] args = joinPoint.getArgs();
    int projectIdx = -1;
    Object projectObj = null;
    // with annotations CheckAccess.
    if (paras != null) {
        for (int i = 0; i < paras.length; i++) {
            Parameter p = paras[i];
            if (p.getAnnotation(CheckAccess.class) != null) {
                projectIdx = i;
            }
        }
        if (projectIdx == -1) {
            throw new AnnotationMisconfigurationException("There is no parameter with a CheckAccess annotation.");
        }
        projectObj = args[projectIdx];
    }
    if (!(IProject.class.isAssignableFrom(projectObj.getClass()))) {
        throw new AnnotationMisconfigurationException("The parameter you are accessing is not a project.");
    }
    IProject project = (IProject) projectObj;
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    String userName = auth.getName().toLowerCase();
    // show forbidden page.
    if (project.getProjectAccess() == EProjectAccessibility.PUBLIC || (userName != null && projectManager.canAccessProjectWebsite(project.getUnixName(), userName))) {
        return joinPoint.proceed();
    } else {
        logger.debug("Access denied to: " + userName);
        return "public/forbidden";
    }
}
Example 48
Project: serengeti-ws-master  File: DefaultPreStartServicesAdvice.java View source code
@Around("@annotation(com.vmware.bdd.software.mgmt.plugin.aop.PreConfiguration)")
public Object preClusterConfiguration(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    PreConfiguration beforeConfig = AnnotationUtils.findAnnotation(method, PreConfiguration.class);
    String nameParam = beforeConfig.clusterNameParam();
    String[] paramNames = signature.getParameterNames();
    Object[] args = pjp.getArgs();
    String clusterName = null;
    for (int i = 0; i < paramNames.length; i++) {
        if (paramNames[i].equals(nameParam)) {
            clusterName = (String) args[i];
        }
    }
    if (clusterName == null) {
        logger.error("Cluster name is not specified in method");
        throw BddException.INTERNAL(null, "Wrong annotation usage. Cluster name must be specified in method.");
    }
    ClusterEntity cluster = clusterEntityMgr.findByName(clusterName);
    if (cluster == null) {
        throw BddException.NOT_FOUND("Cluster", clusterName);
    }
    preStartServices(clusterName);
    return pjp.proceed();
}
Example 49
Project: spring-framework-2.5.x-master  File: MethodInvocationProceedingJoinPointTests.java View source code
public void before(Method method, Object[] args, Object target) throws Throwable {
    JoinPoint jp = AbstractAspectJAdvice.currentJoinPoint();
    assertTrue("Method named in toString", jp.toString().indexOf(method.getName()) != -1);
    // Ensure that these don't cause problems
    jp.toShortString();
    jp.toLongString();
    assertSame(target, AbstractAspectJAdvice.currentJoinPoint().getTarget());
    assertFalse(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getTarget()));
    ITestBean thisProxy = (ITestBean) AbstractAspectJAdvice.currentJoinPoint().getThis();
    assertTrue(AopUtils.isAopProxy(AbstractAspectJAdvice.currentJoinPoint().getThis()));
    assertNotSame(target, thisProxy);
    // Check getting again doesn't cause a problem
    assertSame(thisProxy, AbstractAspectJAdvice.currentJoinPoint().getThis());
    // Be sure to increment depth to avoid infinite recursion
    if (depth++ == 0) {
        // Check that toString doesn't cause a problem
        thisProxy.toString();
        // Change age, so this will be returned by invocation
        thisProxy.setAge(newAge);
        assertEquals(newAge, thisProxy.getAge());
    }
    assertSame(AopContext.currentProxy(), thisProxy);
    assertSame(target, raw);
    assertSame(method.getName(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getName());
    assertEquals(method.getModifiers(), AbstractAspectJAdvice.currentJoinPoint().getSignature().getModifiers());
    MethodSignature msig = (MethodSignature) AbstractAspectJAdvice.currentJoinPoint().getSignature();
    assertSame("Return same MethodSignature repeatedly", msig, AbstractAspectJAdvice.currentJoinPoint().getSignature());
    assertSame("Return same JoinPoint repeatedly", AbstractAspectJAdvice.currentJoinPoint(), AbstractAspectJAdvice.currentJoinPoint());
    assertEquals(method.getDeclaringClass(), msig.getDeclaringType());
    assertTrue(Arrays.equals(method.getParameterTypes(), msig.getParameterTypes()));
    assertEquals(method.getReturnType(), msig.getReturnType());
    assertTrue(Arrays.equals(method.getExceptionTypes(), msig.getExceptionTypes()));
    try {
        msig.getParameterNames();
        fail("Can't determine parameter names");
    } catch (UnsupportedOperationException ex) {
    }
    msig.toLongString();
    msig.toShortString();
}
Example 50
Project: spring-metrics-master  File: MetricsSchedulingAspect.java View source code
@Around("execution (@org.springframework.scheduling.annotation.Scheduled  * *.*(..))")
public Object timeScheduledOperation(ProceedingJoinPoint pjp) throws Throwable {
    Method method = ((MethodSignature) pjp.getSignature()).getMethod();
    String signature = pjp.getSignature().toShortString();
    if (method.getDeclaringClass().isInterface()) {
        try {
            method = pjp.getTarget().getClass().getDeclaredMethod(pjp.getSignature().getName(), method.getParameterTypes());
        } catch (final SecurityExceptionNoSuchMethodException |  e) {
            logger.warn("Unable to perform metrics timing on " + signature, e);
            return pjp.proceed();
        }
    }
    Map<Boolean, Timed> timedAnnots = TimedUtils.findTimed(method).filter( t -> !t.value().isEmpty()).collect(Collectors.toMap(Timed::longTask, Functions.identity()));
    Timed shortTaskTimerAnnot = timedAnnots.get(false);
    Timer shortTaskTimer = null;
    if (shortTaskTimerAnnot != null)
        shortTaskTimer = registry.timer(shortTaskTimerAnnot.value(), Tags.tagList(shortTaskTimerAnnot.extraTags()));
    Timed longTaskTimerAnnot = timedAnnots.get(true);
    LongTaskTimer longTaskTimer = null;
    if (longTaskTimerAnnot != null)
        longTaskTimer = registry.longTaskTimer(longTaskTimerAnnot.value(), Tags.tagList(longTaskTimerAnnot.extraTags()));
    if (shortTaskTimer != null && longTaskTimer != null) {
        final Timer finalTimer = shortTaskTimer;
        return longTaskTimer.recordThrowable(() -> finalTimer.recordThrowable(pjp::proceed));
    } else if (shortTaskTimer != null) {
        return shortTaskTimer.recordThrowable(pjp::proceed);
    } else if (longTaskTimer != null) {
        return longTaskTimer.recordThrowable(pjp::proceed);
    }
    return pjp.proceed();
}
Example 51
Project: syncope-master  File: LogicInvocationHandler.java View source code
@Around("execution(* org.apache.syncope.core.logic.AbstractLogic+.*(..))")
public Object around(final ProceedingJoinPoint joinPoint) throws Throwable {
    Class<?> clazz = joinPoint.getTarget().getClass();
    Object[] input = joinPoint.getArgs();
    String category = clazz.getSimpleName();
    MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    Method method = ms.getMethod();
    String event = joinPoint.getSignature().getName();
    AuditElements.Result result = null;
    Object output = null;
    Object before = null;
    try {
        LOG.debug("Before {}.{}({})", clazz.getSimpleName(), event, input == null || input.length == 0 ? "" : Arrays.asList(input));
        try {
            before = ((AbstractLogic) joinPoint.getTarget()).resolveBeanReference(method, input);
        } catch (UnresolvedReferenceException ignore) {
            LOG.debug("Unresolved bean reference ...");
        }
        output = joinPoint.proceed();
        result = AuditElements.Result.SUCCESS;
        LOG.debug("After returning {}.{}: {}", clazz.getSimpleName(), event, output);
        return output;
    } catch (Throwable t) {
        output = t;
        result = AuditElements.Result.FAILURE;
        LOG.debug("After throwing {}.{}", clazz.getSimpleName(), event);
        throw t;
    } finally {
        notificationManager.createTasks(AuditElements.EventCategoryType.LOGIC, category, null, event, result, before, output, input);
        auditManager.audit(AuditElements.EventCategoryType.LOGIC, category, null, event, result, before, output, input);
    }
}
Example 52
Project: talkback-master  File: TraceAspect.java View source code
private void log(ProceedingJoinPoint joinPoint, long elapsedMillis) {
    if (elapsedMillis >= LATENCY_THRESHOLD_MS) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String className = methodSignature.getMethod().getDeclaringClass().getCanonicalName();
        String methodName = methodSignature.getName();
        LogUtils.log(className, Log.DEBUG, "%s %s.%s -->%dms", Strings.repeat("  ", callLevel > 0 ? callLevel : 0), className, methodName, elapsedMillis);
    }
}
Example 53
Project: XWorld-master  File: XSpringAop.java View source code
public Object transcation(ProceedingJoinPoint joinpoint) throws Throwable {
    Object object = null;
    boolean isTranscation = true;
    Class tagetClass = joinpoint.getTarget().getClass();
    MethodSignature signature = (MethodSignature) joinpoint.getSignature();
    Method method = signature.getMethod();
    Annotation[] annotations = method.getAnnotations();
    if (annotations != null) {
        for (Annotation annotation : annotations) {
            if (annotation instanceof XNTranscation) {
                isTranscation = false;
                break;
            }
        }
    }
    if (isTranscation) {
        if (tagetClass.getAnnotation(XNTranscation.class) != null) {
            isTranscation = false;
        }
    }
    if (isTranscation) {
        try {
            // 是�是第一个方法,第一个方法�能得到事务
            if (isFirstMethod()) {
                setFirstMethod(method);
                getTranscation();
            }
            object = joinpoint.proceed();
            // 当执行到最å?Žä¸€ä¸ªæ–¹æ³•æ—¶,æ??交
            if (getFirstMethod() == method) {
                commit();
            }
        } catch (Throwable e) {
            rollback();
            throw e;
        } finally {
            // 当执行到最�一个方法时,close
            if (getFirstMethod() == method) {
                this.setFirstMethod(null);
                close();
            }
        }
    } else {
        object = joinpoint.proceed();
    }
    return object;
}
Example 54
Project: zheng-master  File: LogAspect.java View source code
@Around("execution(* *..controller..*.*(..))")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    // 获�request
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
    HttpServletRequest request = servletRequestAttributes.getRequest();
    UpmsLog upmsLog = new UpmsLog();
    // 从注解中获å?–æ“?作å??称ã€?获å?–å“?应结果
    Object result = pjp.proceed();
    Signature signature = pjp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(ApiOperation.class)) {
        ApiOperation log = method.getAnnotation(ApiOperation.class);
        upmsLog.setDescription(log.value());
    }
    if (method.isAnnotationPresent(RequiresPermissions.class)) {
        RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
        String[] permissions = requiresPermissions.value();
        if (permissions.length > 0) {
            upmsLog.setPermissions(permissions[0]);
        }
    }
    endTime = System.currentTimeMillis();
    _log.debug("doAround>>>result={},耗时:{}", result, endTime - startTime);
    upmsLog.setBasePath(RequestUtil.getBasePath(request));
    upmsLog.setIp(RequestUtil.getIpAddr(request));
    upmsLog.setMethod(request.getMethod());
    if (request.getMethod().equalsIgnoreCase("GET")) {
        upmsLog.setParameter(request.getQueryString());
    } else {
        upmsLog.setParameter(ObjectUtils.toString(request.getParameterMap()));
    }
    upmsLog.setResult(ObjectUtils.toString(result));
    upmsLog.setSpendTime((int) (endTime - startTime));
    upmsLog.setStartTime(startTime);
    upmsLog.setUri(request.getRequestURI());
    upmsLog.setUrl(ObjectUtils.toString(request.getRequestURL()));
    upmsLog.setUserAgent(request.getHeader("User-Agent"));
    upmsLog.setUsername(ObjectUtils.toString(request.getUserPrincipal()));
    upmsApiService.insertUpmsLogSelective(upmsLog);
    return result;
}
Example 55
Project: aop-logging-master  File: AOPLogger.java View source code
private Method extractMethod(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    // signature.getMethod() points to method declared in interface. it is not suit to discover arg names and arg annotations
    // see AopProxyUtils: org.springframework.cache.interceptor.CacheAspectSupport#execute(CacheAspectSupport.Invoker, Object, Method, Object[])
    Class<?> targetClass = joinPoint.getTarget().getClass();
    if (Modifier.isPublic(signature.getMethod().getModifiers())) {
        return targetClass.getMethod(signature.getName(), signature.getParameterTypes());
    } else {
        return ReflectionUtils.findMethod(targetClass, signature.getName(), signature.getParameterTypes());
    }
}
Example 56
Project: APP-dashboard-master  File: ControllerInputValidatorAspect.java View source code
/**
     * Around for pointcut defined by controllerMethodInvocation
     * @param joinPoint
     * @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);
}
Example 57
Project: Consent2Share-master  File: AspectUtilsTest.java View source code
private JoinPoint setJointPoint() throws NoSuchMethodException, SecurityException {
    JoinPoint jpMock = mock(JoinPoint.class);
    MethodSignature ms = mock(MethodSignature.class);
    Method method = this.getClass().getMethod("testBeforeMethod_nullpname");
    when(ms.getMethod()).thenReturn(method);
    when(jpMock.getSignature()).thenReturn(ms);
    when(ms.getName()).thenReturn("fakeName");
    when(ms.getReturnType()).thenReturn(String.class);
    when(jpMock.getTarget()).thenReturn(new LoggingAspect());
    return jpMock;
}
Example 58
Project: easyooo-framework-master  File: CacheAspectExecutor.java View source code
public <T> Object selectByGroupKey(ProceedingJoinPoint pjp, Object bean) throws Throwable {
    if (!checkHasCache(bean)) {
        return pjp.proceed();
    }
    MethodSignature method = (MethodSignature) pjp.getSignature();
    GroupStrategy group = method.getMethod().getAnnotation(GroupStrategy.class);
    if (group == null) {
        return pjp.proceed();
    }
    return dataProxy.selectByGroupKey(bean, group.value(), new DefaultDelegater<List<T>>(pjp));
}
Example 59
Project: easyrec-code-master  File: IOLogAspectAdvice.java View source code
/**
     * Logs a method call and prints the arguments and the return value to the log level given in the
     * iol parameter.
     *
     * @param pjp the JoinPoint containing information about the intercepted method call
     * @param iol annotation for the IOLog aspect; contains info about the log level
     * @return the result of the method call
     * @throws Throwable
     */
public Object logIO(ProceedingJoinPoint pjp, IOLog iol) throws Throwable {
    StringBuilder sb = new StringBuilder();
    String methodName = pjp.getSignature().getName();
    // parameter names only work with when compiled with AspectJ compiler
    //String[] params = ((MethodSignature)pjp.getSignature()).getParameterNames();
    Class<?>[] paramTypes = ((MethodSignature) pjp.getSignature()).getParameterTypes();
    Class<?> returnType = ((MethodSignature) pjp.getSignature()).getReturnType();
    Object[] args = pjp.getArgs();
    Log logger = LogFactory.getLog(pjp.getTarget().getClass());
    Object o = pjp.proceed();
    if (!LoggerUtils.isLogLevelEnabled(logger, iol.value()))
        return o;
    sb.append(methodName).append(argsToString(paramTypes, args)).append(':').append(returnType.getName()).append('=').append(o);
    LoggerUtils.log(logger, iol.value(), sb.toString());
    return o;
}
Example 60
Project: exist-master  File: PermissionRequiredAspect.java View source code
@Before("methodParameterWithPermissionRequired(permission, o)")
public void enforcePermissionsOnParameter(JoinPoint joinPoint, Permission permission, Object o) throws PermissionDeniedException {
    //the next two lines can be replaced when this aspectj bug is closed - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259416
    final MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    final PermissionRequired parameterPermissionRequired = (PermissionRequired) ms.getMethod().getParameterAnnotations()[0][0];
    //1) check if we should allow DBA access
    if (((parameterPermissionRequired.user() & IS_DBA) == IS_DBA) && permission.isCurrentSubjectDBA()) {
        return;
    }
    //2) check if the user is in the target group
    if ((parameterPermissionRequired.user() & IS_MEMBER) == IS_MEMBER) {
        final Integer groupId = (Integer) o;
        if (permission.isCurrentSubjectInGroup(groupId)) {
            return;
        }
    }
    //3) check if we are looking for setGID
    if ((parameterPermissionRequired.mode() & IS_SET_GID) == IS_SET_GID) {
        final Permission other = (Permission) o;
        if (other.isSetGid()) {
            return;
        }
    }
    throw new PermissionDeniedException("You must be a member of the group you are changing the item to");
}
Example 61
Project: head-master  File: AspectJRESTApprovalInterceptor.java View source code
@Around("restMethods() && requestMapping() && excludeAPI() && exludeRestfulServices()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getStaticPart().getSignature();
    LOG.debug(this.getClass().getSimpleName() + " staring");
    // FIXME : somehow autowiring is not working
    if (approvalService == null) {
        approvalService = ApplicationContextProvider.getBean(ApprovalService.class);
    }
    if (configurationServiceFacade == null) {
        configurationServiceFacade = ApplicationContextProvider.getBean(ConfigurationServiceFacade.class);
    }
    if (parameterNameDiscoverer == null) {
        parameterNameDiscoverer = ApplicationContextProvider.getBean(ParameterNameDiscoverer.class);
    }
    if (!RESTConfigKey.isApprovalRequired(configurationServiceFacade)) {
        LOG.debug(pjp.getSignature() + " skip approval");
        return pjp.proceed();
    }
    if (signature instanceof MethodSignature) {
        MethodSignature ms = (MethodSignature) signature;
        Method m = ms.getMethod();
        RequestMapping mapping = m.getAnnotation(RequestMapping.class);
        if (isReadOnly(mapping)) {
            LOG.debug(m.getName() + " is read only, hence returning control");
            return pjp.proceed();
        }
        Class<?> methodClassType = m.getDeclaringClass();
        if (!methodClassType.getSimpleName().endsWith("RESTController")) {
            LOG.debug(m.getName() + " is not from REST controller, hence returning control");
            return pjp.proceed();
        }
        Object[] argValues = pjp.getArgs();
        Class<?>[] argTypes = m.getParameterTypes();
        String methodName = m.getName();
        String[] names = parameterNameDiscoverer.getParameterNames(m);
        MethodArgHolder args = new MethodArgHolder(argTypes, argValues, names);
        ApprovalMethod method = new ApprovalMethod(methodName, methodClassType, args);
        approvalService.create(method);
    }
    return pjp.proceed();
}
Example 62
Project: ignite-master  File: GridifySetToValueAspectJAspect.java View source code
/**
     * Aspect implementation which executes grid-enabled methods on remote
     * nodes.
     *
     * @param joinPnt Join point provided by AspectJ AOP.
     * @return Method execution result.
     * @throws Throwable If execution failed.
     */
@SuppressWarnings({ "ProhibitedExceptionDeclared", "ProhibitedExceptionThrown", "CatchGenericClass" })
@Around("execution(@org.apache.ignite.compute.gridify.GridifySetToValue * *(..)) && !cflow(call(* org.apache.ignite.compute.ComputeJob.*(..)))")
public Object gridify(ProceedingJoinPoint joinPnt) throws Throwable {
    Method mtd = ((MethodSignature) joinPnt.getSignature()).getMethod();
    GridifySetToValue ann = mtd.getAnnotation(GridifySetToValue.class);
    assert ann != null : "Intercepted method does not have gridify annotation.";
    // Since annotations in Java don't allow 'null' as default value
    // we have accept an empty string and convert it here.
    // NOTE: there's unintended behavior when user specifies an empty
    // string as intended Igninte instance name.
    // NOTE: the 'ann.igniteInstanceName() == null' check is added to mitigate
    // annotation bugs in some scripting languages (e.g. Groovy).
    String igniteInstanceName = F.isEmpty(ann.igniteInstanceName()) ? ann.gridName() : ann.igniteInstanceName();
    if (F.isEmpty(igniteInstanceName))
        igniteInstanceName = null;
    if (G.state(igniteInstanceName) != STARTED)
        throw new IgniteCheckedException("Grid is not locally started: " + igniteInstanceName);
    GridifyNodeFilter nodeFilter = null;
    if (!ann.nodeFilter().equals(GridifyNodeFilter.class))
        nodeFilter = ann.nodeFilter().newInstance();
    // Check is method allowed for gridify.
    checkMethodSignature(mtd);
    GridifyArgumentBuilder argBuilder = new GridifyArgumentBuilder();
    // Creates task argument.
    GridifyRangeArgument arg = argBuilder.createTaskArgument(mtd.getDeclaringClass(), mtd.getName(), mtd.getReturnType(), mtd.getParameterTypes(), mtd.getParameterAnnotations(), joinPnt.getArgs(), joinPnt.getTarget());
    if (!ann.interceptor().equals(GridifyInterceptor.class)) {
        // Check interceptor first.
        if (!ann.interceptor().newInstance().isGridify(ann, arg))
            return joinPnt.proceed();
    }
    // Proceed locally for negative threshold parameter.
    if (ann.threshold() < 0)
        return joinPnt.proceed();
    // Analyse where to execute method (remotely or locally).
    if (arg.getInputSize() != UNKNOWN_SIZE && arg.getInputSize() <= ann.threshold())
        return joinPnt.proceed();
    // Check is split to jobs allowed for input method argument with declared splitSize.
    checkIsSplitToJobsAllowed(arg, ann);
    try {
        Ignite ignite = G.ignite(igniteInstanceName);
        return execute(mtd, ignite.compute(), joinPnt.getSignature().getDeclaringType(), arg, nodeFilter, ann.threshold(), ann.splitSize(), ann.timeout());
    } catch (Exception e) {
        for (Class<?> ex : ((MethodSignature) joinPnt.getSignature()).getMethod().getExceptionTypes()) {
            Throwable cause = e.getCause();
            while (cause != null) {
                if (ex.isAssignableFrom(cause.getClass()))
                    throw cause;
                cause = cause.getCause();
            }
            if (ex.isAssignableFrom(e.getClass()))
                throw e;
        }
        throw new GridifyRuntimeException("Undeclared exception thrown: " + e.getMessage(), e);
    }
}
Example 63
Project: java-lib-master  File: RmLogMethod.java View source code
void doLog(JoinPoint jp, Object r) {
    long now = System.currentTimeMillis();
    long executeTime = now - methodHolder.get().longValue();
    StringBuilder sb = new StringBuilder();
    //时间戳
    sb.append(now);
    sb.append("|");
    //执行时间
    sb.append(executeTime);
    sb.append("|");
    //返回结果监控
    int rSize = -1;
    if (r != null) {
        if (r instanceof Collection) {
            rSize = ((Collection) r).size();
        } else if (r instanceof Map && !"org.quickbundle.project.common.vo.RmCommonVo".equals(r.getClass().getName())) {
            rSize = ((Map) r).size();
        } else if (r instanceof Object[]) {
            rSize = ((Object[]) r).length;
        }
    }
    if (rSize > -1) {
        sb.append(rSize);
    }
    sb.append("|");
    //线程信�
    sb.append(RmGlobalMonitor.getShortUniqueUUID());
    sb.append(".");
    sb.append(Thread.currentThread().getId());
    sb.append("|");
    sb.append(jp.getTarget().getClass().getName());
    sb.append("|");
    sb.append(jp.getSignature().getName());
    sb.append("(");
    Signature sig = jp.getSignature();
    if (sig instanceof MethodSignature) {
        Class[] aClass = ((MethodSignature) sig).getParameterTypes();
        for (int i = 0; i < aClass.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(aClass[i].getName());
        }
    }
    sb.append(")");
    logMethod.debug(sb.toString().replaceAll("[\\r\\n]+", " "));
}
Example 64
Project: javasec-master  File: RmLogMethod.java View source code
void doLog(JoinPoint jp, Object r) {
    long now = System.currentTimeMillis();
    long executeTime = now - methodHolder.get().longValue();
    StringBuilder sb = new StringBuilder();
    //时间戳
    sb.append(now);
    sb.append("|");
    //执行时间
    sb.append(executeTime);
    sb.append("|");
    //返回结果监控
    int rSize = -1;
    if (r != null) {
        if (r instanceof Collection) {
            rSize = ((Collection) r).size();
        } else if (r instanceof Map && !"org.quickbundle.project.common.vo.RmCommonVo".equals(r.getClass().getName())) {
            rSize = ((Map) r).size();
        } else if (r instanceof Object[]) {
            rSize = ((Object[]) r).length;
        }
    }
    if (rSize > -1) {
        sb.append(rSize);
    }
    sb.append("|");
    //线程信�
    sb.append(RmGlobalMonitor.getShortUniqueUUID());
    sb.append(".");
    sb.append(Thread.currentThread().getId());
    sb.append("|");
    sb.append(jp.getTarget().getClass().getName());
    sb.append("|");
    sb.append(jp.getSignature().getName());
    sb.append("(");
    Signature sig = jp.getSignature();
    if (sig instanceof MethodSignature) {
        Class[] aClass = ((MethodSignature) sig).getParameterTypes();
        for (int i = 0; i < aClass.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(aClass[i].getName());
        }
    }
    sb.append(")");
    logMethod.debug(sb.toString().replaceAll("[\\r\\n]+", " "));
}
Example 65
Project: mifos-head-master  File: AspectJRESTApprovalInterceptor.java View source code
@Around("restMethods() && requestMapping() && excludeAPI() && exludeRestfulServices()")
public Object profile(ProceedingJoinPoint pjp) throws Throwable {
    Signature signature = pjp.getStaticPart().getSignature();
    LOG.debug(this.getClass().getSimpleName() + " staring");
    // FIXME : somehow autowiring is not working
    if (approvalService == null) {
        approvalService = ApplicationContextProvider.getBean(ApprovalService.class);
    }
    if (configurationServiceFacade == null) {
        configurationServiceFacade = ApplicationContextProvider.getBean(ConfigurationServiceFacade.class);
    }
    if (parameterNameDiscoverer == null) {
        parameterNameDiscoverer = ApplicationContextProvider.getBean(ParameterNameDiscoverer.class);
    }
    if (!RESTConfigKey.isApprovalRequired(configurationServiceFacade)) {
        LOG.debug(pjp.getSignature() + " skip approval");
        return pjp.proceed();
    }
    if (signature instanceof MethodSignature) {
        MethodSignature ms = (MethodSignature) signature;
        Method m = ms.getMethod();
        RequestMapping mapping = m.getAnnotation(RequestMapping.class);
        if (isReadOnly(mapping)) {
            LOG.debug(m.getName() + " is read only, hence returning control");
            return pjp.proceed();
        }
        Class<?> methodClassType = m.getDeclaringClass();
        if (!methodClassType.getSimpleName().endsWith("RESTController")) {
            LOG.debug(m.getName() + " is not from REST controller, hence returning control");
            return pjp.proceed();
        }
        Object[] argValues = pjp.getArgs();
        Class<?>[] argTypes = m.getParameterTypes();
        String methodName = m.getName();
        String[] names = parameterNameDiscoverer.getParameterNames(m);
        MethodArgHolder args = new MethodArgHolder(argTypes, argValues, names);
        ApprovalMethod method = new ApprovalMethod(methodName, methodClassType, args);
        approvalService.create(method);
    }
    return pjp.proceed();
}
Example 66
Project: qb-core-master  File: RmLogMethod.java View source code
void doLog(JoinPoint jp, Object r) {
    long now = System.currentTimeMillis();
    long executeTime = now - methodHolder.get().longValue();
    StringBuilder sb = new StringBuilder();
    //时间戳
    sb.append(now);
    sb.append("|");
    //执行时间
    sb.append(executeTime);
    sb.append("|");
    //返回结果监控
    int rSize = -1;
    if (r != null) {
        if (r instanceof Collection) {
            rSize = ((Collection) r).size();
        } else if (r instanceof Map && !"org.quickbundle.project.common.vo.RmCommonVo".equals(r.getClass().getName())) {
            rSize = ((Map) r).size();
        } else if (r instanceof Object[]) {
            rSize = ((Object[]) r).length;
        }
    }
    if (rSize > -1) {
        sb.append(rSize);
    }
    sb.append("|");
    //线程信�
    sb.append(RmGlobalMonitor.getShortUniqueUUID());
    sb.append(".");
    sb.append(Thread.currentThread().getId());
    sb.append("|");
    sb.append(jp.getTarget().getClass().getName());
    sb.append("|");
    sb.append(jp.getSignature().getName());
    sb.append("(");
    Signature sig = jp.getSignature();
    if (sig instanceof MethodSignature) {
        Class[] aClass = ((MethodSignature) sig).getParameterTypes();
        for (int i = 0; i < aClass.length; i++) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(aClass[i].getName());
        }
    }
    sb.append(")");
    logMethod.debug(sb.toString().replaceAll("[\\r\\n]+", " "));
}
Example 67
Project: security-stateless-samples-master  File: OpLogAspect.java View source code
// ~ Methods ==================================================
/**
	 * [Main] {@link Around}
	 * @param pjp {@link ProceedingJoinPoint}
	 * @return Object
	 * @throws Throwable
	 */
public Object around(ProceedingJoinPoint pjp) throws Throwable {
    Object obj = null;
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    int result = 1;
    String message = "";
    String action = getPlogValue(method);
    Date startAt = new Date();
    try {
        // call target object method
        obj = pjp.proceed();
    } catch (Exception e) {
        result = 0;
        message = e.getMessage();
        throw e;
    } finally {
        register(action, startAt, result, message);
    }
    return obj;
}
Example 68
Project: thysdrus-master  File: CircuitBreakerAspect.java View source code
@Around("execution(@net.greencoding.thysdrus.circuitbreaker.annotation.MonitoredByCircuitBreaker * * (..))")
public Object breakCircuit(final ProceedingJoinPoint pjp) throws Throwable {
    Object returnObject = null;
    final String method = pjp.getSignature().toLongString();
    CircuitBreakerStatus status = null;
    try {
        final MethodSignature sig = (MethodSignature) pjp.getStaticPart().getSignature();
        final MonitoredByCircuitBreaker cbAnnotation = sig.getMethod().getAnnotation(MonitoredByCircuitBreaker.class);
        registry.registerMehtodIfnecessary(method, cbAnnotation);
        status = registry.getStatusWithHalfOpenExclusiveLockTry(method);
        if (status.equals(CircuitBreakerStatus.OPEN)) {
            logger.info("CIRCUIT STATUS: OPEN. Method {} can not be executed. try later!", method);
            if (cbAnnotation.isSilientMode()) {
                return null;
            } else {
                throw new OpenCircuitException();
            }
        } else if (status.equals(CircuitBreakerStatus.HALF_OPEN)) {
            logger.info("CIRCUIT STATUS: HALF_OPEN. Another thread has the exclusive lock for half open. Method {} can not be executed.", method);
            if (cbAnnotation.isSilientMode()) {
                return null;
            } else {
                throw new OpenCircuitException();
            }
        } else if (status.equals(CircuitBreakerStatus.CLOSED)) {
            logger.info("CIRCUIT STATUS: CLOSED. execute method {}", method);
            returnObject = proceed(pjp);
        } else if (status.equals(CircuitBreakerStatus.HALF_OPEN_EXCLUSIVE)) {
            logger.info("CIRCUIT STATUS: HALF_OPEN_EXCLUSIVE. This thread win the exclusive lock for the half open call. execute method: {}", method);
            returnObject = proceed(pjp);
            logger.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())) {
                logger.info("dectected failure. failure indication: {} \nException:", clazz.getCanonicalName(), throwable);
                if (status.equals(CircuitBreakerStatus.CLOSED) && registry.sameClosedCycleInLocalAndGlobaleContext(method)) {
                    logger.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;
            }
        }
        if (status.equals(CircuitBreakerStatus.HALF_OPEN_EXCLUSIVE)) {
            logger.info("CIRCUIT STATUS: HALF_OPEN_EXCLUSIVE. method execution was successfull. now close circuit for method {}", method);
            registry.closeAndUnlock(method);
        }
        throw throwable;
    } finally {
        registry.cleanUp(method);
    }
    return returnObject;
}
Example 69
Project: XSLT-master  File: PermissionRequiredAspect.java View source code
@Before("methodParameterWithPermissionRequired(permission, o)")
public void enforcePermissionsOnParameter(JoinPoint joinPoint, Permission permission, Object o) throws PermissionDeniedException {
    //the next two lines can be replaced when this aspectj bug is closed - https://bugs.eclipse.org/bugs/show_bug.cgi?id=259416
    final MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    final PermissionRequired parameterPermissionRequired = (PermissionRequired) ms.getMethod().getParameterAnnotations()[0][0];
    //1) check if we should allow DBA access
    if (((parameterPermissionRequired.user() & IS_DBA) == IS_DBA) && permission.isCurrentSubjectDBA()) {
        return;
    }
    //2) check if the user is in the target group
    if ((parameterPermissionRequired.user() & IS_MEMBER) == IS_MEMBER) {
        final Integer groupId = (Integer) o;
        if (permission.isCurrentSubjectInGroup(groupId)) {
            return;
        }
    }
    //3) check if we are looking for setGID
    if ((parameterPermissionRequired.mode() & IS_SET_GID) == IS_SET_GID) {
        final Permission other = (Permission) o;
        if (other.isSetGid()) {
            return;
        }
    }
    throw new PermissionDeniedException("You must be a member of the group you are changing the item to");
}
Example 70
Project: Hystrix-master  File: AopUtils.java View source code
/**
     * Gets a {@link Method} object from target object (not proxy class).
     *
     * @param joinPoint the {@link JoinPoint}
     * @return a {@link Method} object or null if method doesn't exist or if the signature at a join point
     *         isn't sub-type of {@link MethodSignature}
     */
public static Method getMethodFromTarget(JoinPoint joinPoint) {
    Method method = null;
    if (joinPoint.getSignature() instanceof MethodSignature) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        method = getDeclaredMethod(joinPoint.getTarget().getClass(), signature.getName(), getParameterTypes(joinPoint));
    }
    return method;
}
Example 71
Project: inspectIT-master  File: MethodLogInterceptor.java View source code
/**
	 * Advice around the method that are annotated with {@link MethodLog} that processes wanted
	 * logging if needed.
	 *
	 * @param joinPoint
	 *            {@link ProceedingJoinPoint}.
	 * @param methodLog
	 *            {@link MethodLog} on the method.
	 * @return Returns result of method invocation.
	 * @throws Throwable
	 *             If {@link Throwable} is result of method invocation.
	 */
@Around("@annotation(rocks.inspectit.server.spring.aop.MethodLog) && @annotation(methodLog)")
public Object doMethodLog(ProceedingJoinPoint joinPoint, MethodLog methodLog) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Logger logger = (Logger) LoggerFactory.getLogger(joinPoint.getTarget().getClass());
    Level timeLogLevel = LEVELS.get(methodLog.timeLogLevel());
    Level traceLogLevel = LEVELS.get(methodLog.traceLogLevel());
    if (logger.isEnabledFor(traceLogLevel)) {
        logger.log(null, signature.getDeclaringType().getName(), LocationAwareLogger.TRACE_INT, TRACE_ENTER_FORMAT, new Object[] { signature.getDeclaringType().getName(), signature.getName() }, null);
    }
    long startTime = System.nanoTime();
    Object object = joinPoint.proceed();
    long endTime = System.nanoTime();
    double duration = Converter.nanoToMilliseconds(endTime - startTime);
    String methodName = null;
    if (logger.isEnabledFor(timeLogLevel)) {
        methodName = convertMethodName(signature.getName());
        String formatString;
        if (logger.isEnabledFor(traceLogLevel)) {
            formatString = TIME_LOG_FORMAT_W_TRACE;
        } else {
            formatString = TIME_LOG_FORMAT;
        }
        logger.log(null, signature.getDeclaringType().getName(), LocationAwareLogger.WARN_INT, formatString, new Object[] { methodName, duration }, null);
    }
    if ((-1 != methodLog.durationLimit()) && (duration > methodLog.durationLimit())) {
        if (null == methodName) {
            methodName = convertMethodName(signature.getName());
        }
        String formatString;
        if (logger.isEnabledFor(traceLogLevel)) {
            formatString = DURATION_THRESHOLD_MSG_W_TRACE;
        } else {
            formatString = DURATION_THRESHOLD_MSG;
        }
        logger.log(null, signature.getDeclaringType().getName(), LocationAwareLogger.WARN_INT, formatString, new Object[] { methodLog.durationLimit(), methodName, duration }, null);
    }
    if (logger.isEnabledFor(traceLogLevel)) {
        logger.log(null, signature.getDeclaringType().getName(), LocationAwareLogger.TRACE_INT, TRACE_EXIT_FORMAT, new Object[] { signature.getDeclaringType().getName(), signature.getName() }, null);
    }
    return object;
}
Example 72
Project: lilith-master  File: TracingAspect.java View source code
public Object trace(ProceedingJoinPoint call) throws Throwable {
    if (logger == null) {
        setLoggerName(null);
    // this initializes the logger
    }
    Signature signature = call.getSignature();
    Class<?> clazz = signature.getDeclaringType();
    Object theTarget = call.getTarget();
    if (theTarget != null) {
        clazz = theTarget.getClass();
    }
    String fullClassName = clazz.getName();
    String methodName = signature.getName();
    StringBuilder msg = new StringBuilder();
    if (showingModifiers) {
        msg.append(Modifier.toString(signature.getModifiers())).append(" ");
    }
    if (usingShortClassName) {
        msg.append(clazz.getSimpleName());
    } else {
        msg.append(fullClassName);
    }
    msg.append(".").append(methodName);
    String methodBaseName = msg.toString();
    if (signature instanceof MethodSignature) {
        MethodSignature methodSignature = (MethodSignature) signature;
        msg.append("(");
        if (showingParameterValues) {
            Object[] args = call.getArgs();
            boolean first = true;
            for (Object arg : args) {
                if (first) {
                    first = false;
                } else {
                    msg.append(", ");
                }
                msg.append(SafeString.toString(arg, SafeString.StringWrapping.ALL, SafeString.StringStyle.GROOVY, SafeString.MapStyle.GROOVY));
            }
        } else {
            Method method = methodSignature.getMethod();
            Class<?>[] parameterTypes = method.getParameterTypes();
            boolean first = true;
            for (Class<?> param : parameterTypes) {
                if (first) {
                    first = false;
                } else {
                    msg.append(", ");
                }
                msg.append(param.getSimpleName());
            }
            if (method.isVarArgs()) {
                int length = msg.length();
                // cut of existing []
                msg.delete(length - 2, length);
                msg.append("...");
            }
        }
        msg.append(")");
    }
    String methodSignatureString = msg.toString();
    String previousClass = MDC.get(TRACED_CLASS_MDC_KEY);
    String previousMethod = MDC.get(TRACED_METHOD_MDC_KEY);
    long nanoSeconds = 0;
    try {
        MDC.put(TRACED_CLASS_MDC_KEY, fullClassName);
        MDC.put(TRACED_METHOD_MDC_KEY, methodName);
        if (logger.isInfoEnabled(ENTERING_MARKER))
            logger.info(ENTERING_MARKER, "{} entered.", methodSignatureString);
        Object result;
        nanoSeconds = System.nanoTime();
        result = call.proceed();
        nanoSeconds = System.nanoTime() - nanoSeconds;
        profile(methodBaseName, methodSignatureString, nanoSeconds);
        if (result == null || !showingParameterValues) {
            if (logger.isInfoEnabled(EXITING_MARKER))
                logger.info(EXITING_MARKER, "{} returned.", methodSignatureString);
        } else {
            if (logger.isInfoEnabled(EXITING_MARKER))
                logger.info(EXITING_MARKER, "{} returned {}.", methodSignatureString, result);
        }
        return result;
    } catch (Throwable t) {
        nanoSeconds = System.nanoTime() - nanoSeconds;
        profile(methodBaseName, methodSignatureString, nanoSeconds);
        if (logger.isInfoEnabled(THROWING_MARKER))
            logger.info(THROWING_MARKER, "{} failed.", methodSignatureString, t);
        throw t;
    } finally {
        if (previousClass == null) {
            MDC.remove(TRACED_CLASS_MDC_KEY);
        } else {
            MDC.put(TRACED_CLASS_MDC_KEY, previousClass);
        }
        if (previousMethod == null) {
            MDC.remove(TRACED_METHOD_MDC_KEY);
        } else {
            MDC.put(TRACED_METHOD_MDC_KEY, previousMethod);
        }
    }
}
Example 73
Project: PerformanceHat-master  File: ProcedureCallJoinPoint.java View source code
/**
   * Helper that returns all {@link java.lang.annotation.Annotation}s of the given call joint point needed for the
   * CostHat UseCase
   * 
   * @return list of all {@link java.lang.annotation.Annotation}
   */
private List<java.lang.annotation.Annotation> getAnnotations() {
    Signature signature = getSignature();
    if (signature instanceof MethodSignature) {
        return Arrays.asList(((MethodSignature) getSignature()).getMethod().getAnnotations());
    } else if (signature instanceof ConstructorSignature) {
        return Arrays.asList(((ConstructorSignature) getSignature()).getConstructor().getAnnotations());
    }
    return Lists.newArrayList();
}
Example 74
Project: qalingo-engine-master  File: CacheManagementAspect.java View source code
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Object returnObject = null;
    try {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Class classReturnType = signature.getReturnType();
        Object[] args = joinPoint.getArgs();
        String cacheType = null;
        String cacheName = null;
        Cache cache = null;
        String key = null;
        logger.debug("Start Cache AOP. Call from : '" + joinPoint.getSignature().toShortString() + "'");
        // DEFINE THE CACHE TYPE
        try {
            CacheMethodInformation cacheMethodInformation = signature.getMethod().getAnnotation(CacheMethodInformation.class);
            cacheType = cacheMethodInformation.cacheType();
            logger.debug("CacheMethodInformation from annotation : cacheType= '" + cacheType + "'");
            cacheName = cacheMethodInformation.cacheName();
            logger.debug("CacheEntityInformation from annotation : cacheName= '" + cacheName + "'");
        } catch (Exception e) {
        }
        if (DomainEntity.class.isAssignableFrom(classReturnType)) {
            cacheType = CacheType.CACHE_ENTITY;
            if (joinPoint.getSignature().toShortString().contains("ByCode")) {
                // FIRST ARG IS A STRING FOR THE GET METHOD : SO THIS A GET BY CODE
                cacheType = CacheType.CACHE_LINK_CODE_ID;
            }
        } else if (AbstractPojo.class.isAssignableFrom(classReturnType)) {
            cacheType = CacheType.CACHE_POJO;
        }
        logger.debug("Cache Type : '" + cacheType + "'");
        // TARGETED FETCH PLAN
        FetchPlan askedFetchPlan = null;
        FetchPlan loadedFetchPlan = null;
        for (Object arg : args) {
            if (arg instanceof Object[]) {
                Object[] objects = (Object[]) arg;
                for (Object object : objects) {
                    if (object instanceof FetchPlan) {
                        FetchPlan fetchPlan = (FetchPlan) object;
                        if (fetchPlan != null && !fetchPlan.getFetchModes().isEmpty()) {
                            askedFetchPlan = fetchPlan;
                            break;
                        }
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(cacheType)) {
            try {
                CacheEntityInformation cacheEntityInformation = (CacheEntityInformation) classReturnType.getAnnotation(CacheEntityInformation.class);
                cacheName = cacheEntityInformation.cacheName();
                // CHECK THE NAME OF THE CACHE
                if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    cacheName += "_link_code_id";
                }
                logger.debug("CacheEntityInformation from annotation : cacheName= '" + cacheName + "'");
            } catch (Exception e) {
            }
            if (StringUtils.isNotEmpty(cacheName)) {
                // LOAD THE CACHE
                if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                    String id = null;
                    if (args != null && args.length > 0) {
                        if (args[0] instanceof Long) {
                            id = ((Long) args[0]).toString();
                        }
                    }
                    key = cacheService.buildEntityKey(signature.getReturnType(), id);
                    if (id == null) {
                        // OVERRIDE THE KEY BY THE METHOD
                        key = signature.toShortString();
                    }
                    cache = cacheService.getCache(cacheName, String.class, AbstractEntity.class);
                } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    String code = null;
                    if (args != null && args.length > 0) {
                        if (args[0] instanceof String) {
                            code = ((String) args[0]).toString();
                        }
                    }
                    key = cacheService.buildCodeIdKey(signature, code);
                    if (code == null) {
                        // OVERRIDE THE KEY BY THE METHOD
                        key = signature.toShortString();
                    }
                    cache = cacheService.getCache(cacheName, String.class, Long.class);
                } else if (cacheType.equals(CacheType.CACHE_POJO)) {
                    key = cacheService.buildCommonKey(signature, args);
                    cache = cacheService.getCache(cacheName, String.class, AbstractPojo.class);
                } else if (cacheType.equals(CacheType.CACHE_STRING)) {
                    key = cacheService.buildCommonKey(signature, args);
                    cache = cacheService.getCache(cacheName, String.class, String.class);
                }
                // TEST IF THE VALUE IS IN CACHE
                if (cache != null) {
                    logger.debug("Searching object in cache with : key= '" + key + "'");
                    if (cache.containsKey(key)) {
                        logger.debug("Object exist in cache with : key= '" + key + "'");
                        Object element = cache.get(key);
                        if (element != null) {
                            // WE TEST IF THE FETCH PLAN ARE EQUALS
                            returnObject = element;
                            if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                                returnObject = checkFetchPlan(returnObject, askedFetchPlan, loadedFetchPlan);
                            } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                                String cacheNameEntity = cacheName.replace("_link_code_id", "");
                                Long id = (Long) returnObject;
                                returnObject = null;
                                Cache cacheEntity = cacheService.getCache(cacheNameEntity, String.class, AbstractEntity.class);
                                String keyEntity = cacheService.buildEntityKey(signature.getReturnType(), id.toString());
                                if (cacheEntity.containsKey(keyEntity)) {
                                    Object entity = cacheEntity.get(keyEntity);
                                    returnObject = entity;
                                    returnObject = checkFetchPlan(returnObject, askedFetchPlan, loadedFetchPlan);
                                }
                            }
                        }
                    } else {
                        logger.debug("Object doesn't exist in cache with : key= '" + key + "'");
                    }
                }
            }
        }
        // NOTHING IN CACHE - CALL THE TARGET METHOD
        if (returnObject == null) {
            if (loadedFetchPlan != null) {
                args = ArrayUtils.add(args, loadedFetchPlan);
                returnObject = joinPoint.proceed(args);
            } else {
                returnObject = joinPoint.proceed();
            }
            if (returnObject != null && cache != null) {
                // PUT IN CACHE
                if (cacheType.equals(CacheType.CACHE_ENTITY)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '" + returnObject + "'");
                    cache.put(key, returnObject);
                    // PUT THE CODE/ID
                    String cacheNameCodeId = cacheName + "_link_code_id";
                    Cache cacheCodeId = cacheService.getCache(cacheNameCodeId, String.class, Long.class);
                    Long id = (Long) handleClassMethodGetValue(joinPoint, returnObject, classReturnType, "getId");
                    String code = (String) handleClassMethodGetValue(joinPoint, returnObject, classReturnType, "getCode");
                    String newKey = key = cacheService.buildCodeIdKey(signature, code);
                    logger.debug("Put in cache '" + cacheNameCodeId + "'. key : '" + newKey + "'. value: '" + id + "'");
                    cacheCodeId.put(newKey, id);
                } else if (cacheType.equals(CacheType.CACHE_LINK_CODE_ID)) {
                    Long id = (Long) handleClassMethodGetValue(joinPoint, returnObject, classReturnType, "getId");
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '" + id + "'");
                    cache.put(key, id);
                    // PUT THE ENTITY
                    String cacheNameEntity = cacheName.replace("_link_code_id", "");
                    Cache cacheEntity = cacheService.getCache(cacheNameEntity, String.class, AbstractEntity.class);
                    String newKey = cacheService.buildEntityKey(signature.getReturnType(), id.toString());
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + newKey + "'. value: '" + returnObject + "'");
                    cacheEntity.put(newKey, returnObject);
                } else if (cacheType.equals(CacheType.CACHE_POJO)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '" + returnObject + "'");
                    cache.put(key, returnObject);
                } else if (cacheType.equals(CacheType.CACHE_STRING)) {
                    logger.debug("Put in cache '" + cacheName + "'. key : '" + key + "'. value: '" + returnObject + "'");
                    cache.put(key, returnObject);
                }
            }
        }
    } catch (Exception e) {
        logger.error("Failed to load datas with Cache AOP! Call from : '" + joinPoint.getSignature().toShortString() + "'", e);
    }
    logger.debug("End Cache AOP. Call from : '" + joinPoint.getSignature().toShortString() + "'");
    logger.debug("---------------------------------------------------------------------------------");
    return returnObject;
}
Example 75
Project: simple-spring-memcached-master  File: CacheBase.java View source code
public Method getMethodToCache(final JoinPoint jp) throws NoSuchMethodException {
    final Signature sig = jp.getSignature();
    if (!(sig instanceof MethodSignature)) {
        throw new InvalidAnnotationException("This annotation is only valid on a method.");
    }
    final MethodSignature msig = (MethodSignature) sig;
    final Object target = jp.getTarget();
    // cannot use msig.getMethod() because it can return the method where annotation was declared i.e. method in
    // interface
    String name = msig.getName();
    Class<?>[] parameters = msig.getParameterTypes();
    Method method = findMethodFromTargetGivenNameAndParams(target, name, parameters);
    if (method.isBridge()) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Method is bridge. Name {}, params: {}", name, parameters);
        }
        parameters = bridgeMethodMappingStore.getTargetParamsTypes(target.getClass(), name, parameters);
        method = findMethodFromTargetGivenNameAndParams(target, name, parameters);
    }
    return method;
}
Example 76
Project: spring-framework-master  File: AbstractAspectJAdvisorFactoryTests.java View source code
@Before(value = "execution(void set*(*)) && this(modifiable) && args(newValue)", argNames = "modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(JoinPoint jp, MutableModifable mixin, Object newValue) {
    if (mixin.isModified()) {
        //System.out.println("changed");
        return;
    }
    // Find the current raw value, by invoking the corresponding setter
    Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod());
    boolean modified = true;
    if (correspondingGetter != null) {
        try {
            Object oldValue = correspondingGetter.invoke(jp.getTarget());
            //System.out.println("Old value=" + oldValue + "; new=" + newValue);
            modified = !ObjectUtils.nullSafeEquals(oldValue, newValue);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else {
    //System.out.println("cannot get getter for " + jp);
    }
    if (modified) {
        mixin.markDirty();
    }
}
Example 77
Project: xebia-management-extras-master  File: ProfileAspect.java View source code
@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 {
            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);
        }
    }
}
Example 78
Project: cache2-master  File: Cache2Intercepter.java View source code
/**
	 * Handles the {@link CacheStrategy#GET} strategy by intercepting a method
	 * call with a cache lookup and caching it if it was not found.
	 * 
	 * @param pjp
	 * @return cached value or retVal
	 * @throws Throwable
	 */
@SuppressWarnings("unchecked")
protected Object get(ProceedingJoinPoint pjp, CachedMethod annotation) throws Throwable {
    Object retVal = null;
    // the declaring class
    final Class<?> declaringClass = pjp.getTarget().getClass();
    final Method method = AopUtils.getMostSpecificMethod(((MethodSignature) pjp.getSignature()).getMethod(), declaringClass);
    // cache 1 key
    final Cache1Key cache1Key = CacheUtil.createCache1Key(declaringClass, method.getName(), method.getParameterTypes(), pjp.getArgs());
    // return type of method
    final Class<?> returnType = method.getReturnType();
    // if the return type is a list
    if (List.class.isAssignableFrom(returnType) && annotation.clazz().isAnnotationPresent(Cache2Element.class)) {
        CachedValue<List<Identifiable>> cachedValue = (CachedValue<List<Identifiable>>) cache1Helper.get(cache1Key);
        if (cachedValue != null) {
            retVal = cachedValue.getValue();
        } else {
            // proceed
            retVal = pjp.proceed();
            // create new cached value
            cachedValue = new CachedValue<List<Identifiable>>((List<Identifiable>) retVal);
            // cache the value
            cache1Helper.put(cache1Key, cachedValue);
            // create links in cache2
            this.handleFields(cachedValue.getValue(), cache1Key, this.putCommand);
        }
    } else // annotated
    if (returnType.isAnnotationPresent(Cache2Element.class) || method.isAnnotationPresent(Cache2Element.class)) {
        // check the cache
        CachedValue<Identifiable> cachedValue = (CachedValue<Identifiable>) cache1Helper.get(cache1Key);
        if (cachedValue != null) {
            retVal = cachedValue.getValue();
        } else {
            // proceed
            retVal = pjp.proceed();
            // create new cached value
            cachedValue = new CachedValue<Identifiable>((Identifiable) retVal);
            // cache the value
            cache1Helper.put(cache1Key, cachedValue);
            // create links in cache2
            this.handleFields(cachedValue.getValue(), cache1Key, this.putCommand);
        }
    } else // if the return type is not an entity
    {
        retVal = pjp.proceed();
    }
    return retVal;
}
Example 79
Project: entando-core-master  File: CacheInfoManager.java View source code
@Around("@annotation(cacheableInfo)")
public Object aroundCacheableMethod(ProceedingJoinPoint pjp, CacheableInfo cacheableInfo) throws Throwable {
    Object result = pjp.proceed();
    if (cacheableInfo.expiresInMinute() < 0 && (cacheableInfo.groups() == null || cacheableInfo.groups().trim().length() == 0)) {
        return result;
    }
    try {
        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        Method targetMethod = methodSignature.getMethod();
        Class targetClass = pjp.getTarget().getClass();
        Method effectiveTargetMethod = targetClass.getMethod(targetMethod.getName(), targetMethod.getParameterTypes());
        Cacheable cacheable = effectiveTargetMethod.getAnnotation(Cacheable.class);
        if (null == cacheable) {
            return result;
        }
        String[] cacheNames = cacheable.value();
        Object key = this.evaluateExpression(cacheable.key().toString(), targetMethod, pjp.getArgs(), effectiveTargetMethod, targetClass);
        for (int j = 0; j < cacheNames.length; j++) {
            String cacheName = cacheNames[j];
            if (cacheableInfo.groups() != null && cacheableInfo.groups().trim().length() > 0) {
                Object groupsCsv = this.evaluateExpression(cacheableInfo.groups().toString(), targetMethod, pjp.getArgs(), effectiveTargetMethod, targetClass);
                if (null != groupsCsv && groupsCsv.toString().trim().length() > 0) {
                    String[] groups = groupsCsv.toString().split(",");
                    this.putInGroup(cacheName, key.toString(), groups);
                }
            }
            if (cacheableInfo.expiresInMinute() > 0) {
                this.setExpirationTime(cacheName, key.toString(), cacheableInfo.expiresInMinute());
            }
        }
    } catch (Throwable t) {
        _logger.error("Error while evaluating cacheableInfo annotation", t);
        throw new ApsSystemException("Error while evaluating cacheableInfo annotation", t);
    }
    return result;
}
Example 80
Project: spring-mvc-exts-master  File: HandlerMethodExposingAspect.java View source code
@Before("handlerMethod()")
public void interceptHandlerMethod(JoinPoint jp) {
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    MethodSignature methodSignature = (MethodSignature) jp.getSignature();
    requestAttributes.setAttribute(Controllers.HANDLER_METHOD_KEY, methodSignature.getMethod(), RequestAttributes.SCOPE_REQUEST);
}
Example 81
Project: incogito-master  File: TimingAspect.java View source code
public void afterReturning(JoinPoint joinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    String method = signature.toShortString();
    long start = state.get();
    recorder.addOkMeasurement(method, System.currentTimeMillis() - start);
}
Example 82
Project: kalipo-master  File: RateLimitAspect.java View source code
@Before("throttledMethod()")
public void enter(JoinPoint joinPoint) throws KalipoException {
    final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    rateLimitService.enter(signature.toLongString());
}
Example 83
Project: reactive-audit-master  File: WithLatencyAudit.java View source code
@Before("execution(@com.octo.reactive.audit.lib.WithLatency * *(..) )")
public void with(JoinPoint thisJoinPoint) throws ReactiveAuditException {
    WithLatency withLatency = ((MethodSignature) thisJoinPoint.getSignature()).getMethod().getAnnotation(WithLatency.class);
    latency(withLatency.value(), thisJoinPoint);
}
Example 84
Project: mycar-master  File: AspectUtils.java View source code
// methods
// -------------------------------------------------------------------------------
public static Method getMethod(JoinPoint joinPoint) {
    if (joinPoint == null)
        return null;
    MethodSignature ms = (MethodSignature) joinPoint.getSignature();
    return ms.getMethod();
}
Example 85
Project: osiris-master  File: MethodInvocationValidationAspect.java View source code
/**
	 * Method that retrieve the calling method.
	 * @param joinPoint the joint point.
	 * @return the method called method.
	 */
private Method retreiveCallMethod(ProceedingJoinPoint joinPoint) {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    return signature.getMethod();
}
Example 86
Project: cloudbreak-master  File: ConcurrentMethodExecutionAspect.java View source code
private <T extends Annotation> T getAnnotation(Class<T> clazz, JoinPoint joinPoint) throws NoSuchMethodException {
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = joinPoint.getTarget().getClass().getDeclaredMethod(joinPoint.getSignature().getName(), methodSignature.getMethod().getParameterTypes());
    return method.getAnnotation(clazz);
}
Example 87
Project: spring_mem_plugin-master  File: GetCacheAop.java View source code
/**
	 * 得到�行时方法对象
	 * 
	 * @param pjp
	 * @return
	 */
private Method getMethod(ProceedingJoinPoint pjp) {
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method method = methodSignature.getMethod();
    return method;
}
Example 88
Project: TNTConcept-master  File: ChangesHistoryAspect.java View source code
/**
	 * Returns the intercepted method
	 * @param call
	 * @return
	 */
private Method getCallMethod(JoinPoint call) {
    Method metodo = null;
    MethodSignature sig = (MethodSignature) call.getSignature();
    metodo = sig.getMethod();
    return metodo;
}