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

The following examples show how to use org.aspectj.lang.reflect.MethodSignature. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: supplierShop   Source File: DataSourceAspect.java    License: MIT License 6 votes vote down vote up
/**
 * 获取需要切换的数据源
 */
public DataSource getDataSource(ProceedingJoinPoint point)
{
    MethodSignature signature = (MethodSignature) point.getSignature();
    Class<? extends Object> targetClass = point.getTarget().getClass();
    DataSource targetDataSource = targetClass.getAnnotation(DataSource.class);
    if (StringUtils.isNotNull(targetDataSource))
    {
        return targetDataSource;
    }
    else
    {
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        return dataSource;
    }
}
 
Example 2
Source Project: semagrow   Source File: MethodLogger.java    License: Apache License 2.0 6 votes vote down vote up
@Around("execution(* *(..)) && @annotation(Loggable)")
public Object around(ProceedingJoinPoint point) {


    Object result = null;
    try {
        Method method = MethodSignature.class.cast(point.getSignature()).getMethod();
        Logger logger = LoggerFactory.getLogger(method.getDeclaringClass());
        LogExprProcessing event = new LogExprProcessing();
        logger.info( "Enter {}", method.getName());
        result = point.proceed();
        logger.info( "Exit  {}", method.getName());
        event.finalize();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }

    /*
            MethodSignature.class.cast(point.getSignature()).getMethod().getName(),
            point.getArgs(),
            result,

            );
    */
    return result;
}
 
Example 3
Source Project: hyena   Source File: IdempotentAround.java    License: Apache License 2.0 6 votes vote down vote up
@Around("@annotation(Idempotent)")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Method method = ((MethodSignature) point.getSignature()).getMethod();

    Idempotent shelter = method.getAnnotation(Idempotent.class);
    String name = shelter.name();
    Object[] args = point.getArgs();
    HttpServletRequest request = (HttpServletRequest) args[0];
    PointOpParam param = (PointOpParam) args[1];
    BaseResponse res;

    // String seq = request.getParameter(HyenaConstants.REQ_IDEMPOTENT_SEQ_KEY);
    String seq = param.getSeq();
    request.setAttribute(HyenaConstants.REQ_IDEMPOTENT_SEQ_KEY, seq);

    res = this.preProceed(name, param, method);

    if (res != null) {
        return res;
    }

    res = (BaseResponse) point.proceed(point.getArgs());

    this.postProceed(name, param, res);
    return res;
}
 
Example 4
Source Project: mall   Source File: RedisCacheAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Around("cacheAspect()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    Object result = null;
    try {
        result = joinPoint.proceed();
    } catch (Throwable throwable) {
        //有CacheException注解的方法需要抛出异常
        if (method.isAnnotationPresent(CacheException.class)) {
            throw throwable;
        } else {
            LOGGER.error(throwable.getMessage());
        }
    }
    return result;
}
 
Example 5
Source Project: Cheddar   Source File: LoggingAspect.java    License: Apache License 2.0 6 votes vote down vote up
private Object proceedAndLog(final ProceedingJoinPoint point) throws Throwable {
    final String methodCallDetail = methodCallDetail(point);
    final String securityContextDetail = securityContextDetail();
    final long startTime = System.currentTimeMillis();
    try {
        logger.debug("Enter;[{}] {}", methodCallDetail, securityContextDetail);
        final Object result = point.proceed();
        logger.debug("Exit; [{}] returned [{}] ms:[{}]",
                ((MethodSignature) (point.getSignature())).getMethod().getName(), result,
                System.currentTimeMillis() - startTime);
        return result;
    } catch (final Throwable e) {
        logger.debug("Exception;[{}] ms:[{}]", e, System.currentTimeMillis() - startTime);
        throw e;
    }
}
 
Example 6
Source Project: data-prep   Source File: AnnotationUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns the id of the parameter annotated with <code>annotationClass</code> in all the <code>pjp</code>
 * arguments. If multiple parameters hold the annotation, returns the index of the <b>last</b> parameter.
 *
 * @param pjp The {@link ProceedingJoinPoint} to check for annotation in parameters.
 * @param annotationClass The annotation to look for.
 * @return The index of the annotated parameter or -1 if not found.
 */
public static int getAnnotatedParameterIndex(ProceedingJoinPoint pjp, Class<? extends Annotation> annotationClass) {
    MethodSignature ms = (MethodSignature) pjp.getSignature();
    Method m = ms.getMethod();

    Annotation[][] pa = m.getParameterAnnotations();
    int idParameterIndex = -1;
    int i = 0;
    for (Annotation[] annotations : pa) {
        for (Annotation annotation : annotations) {
            if (annotation.annotationType().equals(annotationClass)) {
                idParameterIndex = i;
            }
        }
        i++;
    }
    return idParameterIndex;
}
 
Example 7
Source Project: spring-boot-demo   Source File: DatasourceSelectorAspect.java    License: MIT License 6 votes vote down vote up
/**
 * 前置操作,拦截具体请求,获取header里的数据源id,设置线程变量里,用于后续切换数据源
 */
@Before("datasourcePointcut()")
public void doBefore(JoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    // 排除不可切换数据源的方法
    DefaultDatasource annotation = method.getAnnotation(DefaultDatasource.class);
    if (null != annotation) {
        DatasourceConfigContextHolder.setDefaultDatasource();
    } else {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String configIdInHeader = request.getHeader("Datasource-Config-Id");
        if (StringUtils.hasText(configIdInHeader)) {
            long configId = Long.parseLong(configIdInHeader);
            DatasourceConfigContextHolder.setCurrentDatasourceConfig(configId);
        } else {
            DatasourceConfigContextHolder.setDefaultDatasource();
        }
    }
}
 
Example 8
@Around("logTime()")
public Object timeAround(ProceedingJoinPoint joinPoint) {
    // 定义返回对象、得到方法需要的参数
    Object obj = null;
    Object[] args = joinPoint.getArgs();
    long startTime = System.currentTimeMillis();

    try {
        obj = joinPoint.proceed(args);
    } catch (Throwable e) {
        e.printStackTrace();
        log.error("统计某方法执行耗时环绕通知出错", e);
    }

    // 获取执行的方法名
    long endTime = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    String methodName = signature.getDeclaringTypeName() + "." + signature.getName();

    // 打印耗时的信息
    log.info(String.format("「%s」执行时间为:%d ms",methodName, endTime - startTime));
    return obj;
}
 
Example 9
Source Project: yue-library   Source File: HttpAspect.java    License: Apache License 2.0 6 votes vote down vote up
@Before("pointcut()")
public void doVerifyBefore(JoinPoint joinPoint) {
	// 1. 登录校验
	MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
	String uri = request.getRequestURI();
       Long user_id = null;
	if (!uri.startsWith("/open") && !uri.equals("/")) {
		user_id = user.getUserId();
	}
	
	// 2. 开发环境-打印日志
	String ip = request.getRemoteHost();
       log.info("ip={}", ip);
	log.info("uri={}", uri);
	log.info("user_id={}", user_id);
	log.info("method={}", request.getMethod());
	log.info("class_method={}", methodSignature.getDeclaringTypeName() + "." + methodSignature.getName() + "()");
}
 
Example 10
Source Project: mall   Source File: LogAspect.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 方法执行前切入
 */
@Before("pointCut()")
public void printLog(JoinPoint joinPoint) {


    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    Method method = signature.getMethod();

    Log syslog = method.getAnnotation(Log.class);

    //请求的方法名
    String className = joinPoint.getTarget().getClass().getName();
    String methodName = signature.getName();
    //请求的参数
    Object[] args = joinPoint.getArgs();

    log.debug("begin to execute className:{} \r\n methodName:{} \r\n logDesc:{} \r\n params:{}", className, methodName, syslog.value(), args);
}
 
Example 11
Source Project: herd   Source File: NamespaceSecurityAdviceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() 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"});

    SecurityContextHolder.getContext().setAuthentication(new TestingAuthenticationToken(null, null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals("Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage());
    }
}
 
Example 12
Source Project: ueboot   Source File: UeLogAspect.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 切面 配置通知
 *
 * @param joinPoint 连接点
 */
@AfterReturning("logPointCut()")
public void saveSysLog(JoinPoint joinPoint) {
    //从切面织入点处通过反射机制获取织入点处的方法
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    //获取切入点所在的方法
    Method method = signature.getMethod();
    //获取请求的类名
    String methodInfo = joinPoint.getTarget().getClass().getName()+"#" + method.getName();
    //请求的参数
    Object[] args = joinPoint.getArgs();
    //将参数所在的数组转换成json
    String params = JSON.toJSONString(args);
    //TODO 根据需求进行日志处理 可调用service保存SysLog实体类到数据库
    log.info("....logPointCut....{}", methodInfo);
}
 
Example 13
Source Project: jim-framework   Source File: CachingAnnotationsAspect.java    License: Apache License 2.0 6 votes vote down vote up
private Method getSpecificmethod(ProceedingJoinPoint pjp) {
	MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
	Method method = methodSignature.getMethod();
	// The method may be on an interface, but we need attributes from the
	// target class. If the target class is null, the method will be
	// unchanged.
	Class<?> targetClass = AopProxyUtils.ultimateTargetClass(pjp.getTarget());
	if (targetClass == null && pjp.getTarget() != null) {
		targetClass = pjp.getTarget().getClass();
	}
	Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
	// If we are dealing with method with generic parameters, find the
	// original method.
	specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
	return specificMethod;
}
 
Example 14
private Compensable getCompensable(ProceedingJoinPoint pjp) {
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();

    Compensable compensable = method.getAnnotation(Compensable.class);

    if (compensable == null) {
        Method targetMethod = null;
        try {
            targetMethod = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
            if (targetMethod != null) {
                compensable = targetMethod.getAnnotation(Compensable.class);
            }
        } catch (NoSuchMethodException e) {
            compensable = null;
        }
    }

    return compensable;
}
 
Example 15
Source Project: SuperBoot   Source File: DataSourceAspect.java    License: MIT License 5 votes vote down vote up
@Around("execution(public * org.superboot.dao.jpa..*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
    Method targetMethod = methodSignature.getMethod();

    //根据注解判断数据源
    if (targetMethod.isAnnotationPresent(TargetDataSource.class)) {
        String targetDataSource = targetMethod.getAnnotation(TargetDataSource.class).dataSource();
        DynamicDataSourceHolder.setDataSource(targetDataSource);
    } else {
        //保存使用写数据源
        if (pjp.getSignature().getName().startsWith("save")) {
            DynamicDataSourceHolder.setDataSource(DataSourceConfig.WRITE_DATASOURCE_KEY);
        }
        //删除使用写数据源
        else if (pjp.getSignature().getName().startsWith("delete")) {
            DynamicDataSourceHolder.setDataSource(DataSourceConfig.WRITE_DATASOURCE_KEY);
        }

        //查询使用读数据源
        else if (pjp.getSignature().getName().startsWith("find")) {
            DynamicDataSourceHolder.setDataSource(DataSourceConfig.READ_DATASOURCE_KEY);
        }

        //保存使用写数据源
        else if (pjp.getSignature().getName().startsWith("get")) {
            DynamicDataSourceHolder.setDataSource(DataSourceConfig.READ_DATASOURCE_KEY);
        } else {
            //默认使用写数据源
            DynamicDataSourceHolder.setDataSource(DataSourceConfig.WRITE_DATASOURCE_KEY);
        }
    }
    logger.info("操作使用数据源:" + DynamicDataSourceHolder.getDataSource());
    //执行方法
    Object result = pjp.proceed();
    DynamicDataSourceHolder.clearDataSource();

    return result;

}
 
Example 16
/**
 * 计算参数表达式
 *
 * @param point      ProceedingJoinPoint
 * @param limitParam limitParam
 * @return 结果
 */
private String evalLimitParam(ProceedingJoinPoint point, String limitParam) {
	MethodSignature ms = (MethodSignature) point.getSignature();
	Method method = ms.getMethod();
	Object[] args = point.getArgs();
	Object target = point.getTarget();
	Class<?> targetClass = target.getClass();
	EvaluationContext context = evaluator.createContext(method, args, target, targetClass, applicationContext);
	AnnotatedElementKey elementKey = new AnnotatedElementKey(method, targetClass);
	return evaluator.evalAsText(limitParam, elementKey, context);
}
 
Example 17
Source Project: herd   Source File: CheckAllowedMethodAdvice.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether the requested operation is permitted.
 *
 * @param pjp the join point.
 *
 * @return the return value of the method at the join point.
 * @throws Throwable if any errors were encountered.
 */
@SuppressWarnings("rawtypes")
public Object checkNotAllowedMethods(ProceedingJoinPoint pjp) throws Throwable
{
    // Get the method name being invoked.
    Class targetClass = pjp.getTarget().getClass();
    MethodSignature targetMethodSignature = (MethodSignature) pjp.getSignature();
    String methodName = targetClass.getName() + "." + targetMethodSignature.getName();

    configurationDaoHelper.checkNotAllowedMethod(methodName);
    return pjp.proceed();
}
 
Example 18
Source Project: Spring-Boot-Book   Source File: TestAnnotationAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Before("myAnnotationPointCut()")
public void before(JoinPoint joinPoint) throws Throwable {
    MethodSignature sign = (MethodSignature) joinPoint.getSignature();
    Method method = sign.getMethod();
    MyTestAnnotation annotation = method.getAnnotation(MyTestAnnotation.class);
    //获取注解参数
    System.out.print("打印TestAnnotation 参数:" + annotation.value());

}
 
Example 19
Source Project: new-bull   Source File: DbLogAspect.java    License: MIT License 5 votes vote down vote up
@Around("@annotation(DbLog)")
public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    DbLog annotation = signature.getMethod().getAnnotation(DbLog.class);

    dbLogStorage
            .create(annotation.resource(), annotation.action(), signature.getMethod().getDeclaringClass().getName(),
                    signature.getMethod().getName());

    return joinPoint.proceed();
}
 
Example 20
Source Project: AspectJDemo   Source File: TraceAspect.java    License: Apache License 2.0 5 votes vote down vote up
/**
     *  截获原方法,并替换
     * @param joinPoint
     * @return
     * @throws Throwable
     */
  @Around("methodAnnotated()")
  public Object weaveJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable {

    if (currentObject == null){
        currentObject = joinPoint.getTarget();
    }
      //初始化计时器
    final StopWatch stopWatch = new StopWatch();
      //开始监听
      stopWatch.start();
      //调用原方法的执行。
    Object result = joinPoint.proceed();
      //监听结束
    stopWatch.stop();
      //获取方法信息对象
      MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
      String className;
      //获取当前对象,通过反射获取类别详细信息
      className = joinPoint.getThis().getClass().getName();

      String methodName = methodSignature.getName();
      String msg =  buildLogMessage(methodName, stopWatch.getTotalTime(1));
    if (currentObject != null && currentObject.equals(joinPoint.getTarget())){
        DebugLog.log(new MethodMsg(className,msg,stopWatch.getTotalTime(1)));
    }else if(currentObject != null && !currentObject.equals(joinPoint.getTarget())){
        DebugLog.log(new MethodMsg(className, msg,stopWatch.getTotalTime(1)));
        Log.e(className,msg);
        currentObject = joinPoint.getTarget();
//        DebugLog.outPut(new Path());    //日志存储
//        DebugLog.ReadIn(new Path());    //日志读取
    }
    return result;
  }
 
Example 21
Source Project: allure-java   Source File: StepsAspects.java    License: Apache License 2.0 5 votes vote down vote up
@Before("anyMethod() && withStepAnnotation()")
public void stepStart(final JoinPoint joinPoint) {
    final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    final Step step = methodSignature.getMethod().getAnnotation(Step.class);

    final String uuid = UUID.randomUUID().toString();
    final String name = getName(step.value(), joinPoint);
    final List<Parameter> parameters = getParameters(methodSignature, joinPoint.getArgs());

    final StepResult result = new StepResult()
            .setName(name)
            .setParameters(parameters);

    getLifecycle().startStep(uuid, result);
}
 
Example 22
Source Project: servicecomb-pack   Source File: ForwardRecovery.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object applyTo(ProceedingJoinPoint joinPoint, Compensable compensable, CompensableInterceptor interceptor,
    OmegaContext context, String parentTxId, int forwardRetries) throws Throwable {
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  int remains = forwardRetries;
  try {
    while (true) {
      try {
        return super.applyTo(joinPoint, compensable, interceptor, context, parentTxId, remains);
      } catch (Throwable throwable) {
        if (throwable instanceof InvalidTransactionException) {
          throw throwable;
        }

        remains--;
        if (remains == 0) {
          LOG.error(
              "Forward Retried sub tx failed maximum times, global tx id: {}, local tx id: {}, method: {}, retried times: {}",
              context.globalTxId(), context.localTxId(), method.toString(), forwardRetries);
          throw throwable;
        }

        LOG.warn("Forward Retrying sub tx failed, global tx id: {}, local tx id: {}, method: {}, remains: {}",
            context.globalTxId(), context.localTxId(), method.toString(), remains);
        Thread.sleep(compensable.retryDelayInMilliseconds());
      }
    }
  } catch (InterruptedException e) {
    String errorMessage = "Failed to handle tx because it is interrupted, global tx id: " + context.globalTxId()
        + ", local tx id: " + context.localTxId() + ", method: " + method.toString();
    LOG.error(errorMessage);
    interceptor.onError(parentTxId, compensationMethodSignature(joinPoint, compensable, method), e);
    throw new OmegaException(errorMessage);
  }
}
 
Example 23
Source Project: DimpleBlog   Source File: VisitLogAspect.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取PageId
 *
 * @param joinPoint 切入点
 * @return PageId
 */
private Long getPageId(VLog vLog, JoinPoint joinPoint) throws NoSuchMethodException {
    String pageIdStr = vLog.pageId();
    if (StringUtils.isEmpty(pageIdStr)) {
        return null;
    }
    //get target method
    MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
    Method method = joinPoint.getTarget().getClass().getMethod(methodSignature.getMethod().getName(), methodSignature.getMethod().getParameterTypes());
    //express SpEL
    ExpressionParser expressionParser = new SpelExpressionParser();
    LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    String[] params = localVariableTableParameterNameDiscoverer.getParameterNames(method);

    Object[] args = joinPoint.getArgs();
    EvaluationContext context = new StandardEvaluationContext();
    for (int i = 0; i < params.length; i++) {
        context.setVariable(params[i], args[i]);
    }

    Expression expression = expressionParser.parseExpression(pageIdStr);
    Object value = expression.getValue(context);

    if (value == null) {
        return null;
    }
    try {
        return (Long) value;
    } catch (Exception e) {
        log.error("get pageId error for parameters {}", value);
        return null;
    }
}
 
Example 24
Source Project: sisyphus   Source File: RetryAop.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取当前方法信息
 *
 * @param point 切点
 * @return 方法
 */
private Method getCurrentMethod(ProceedingJoinPoint point) {
    try {
        Signature sig = point.getSignature();
        MethodSignature msig = (MethodSignature) sig;
        Object target = point.getTarget();
        return target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
    } catch (NoSuchMethodException e) {
        throw new RetryException(e);
    }
}
 
Example 25
@Around("execution (@io.micrometer.core.annotation.Timed * *.*(..))")
public Object timedMethod(ProceedingJoinPoint joinPoint) throws Throwable {

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

  String className = methodSignature.getDeclaringType().getSimpleName();
  String methodName = methodSignature.getName();
  String metricName = String.format("%s.%s", className, methodName);

  Timer.Sample timer = Timer.start(registry);

  //@formatter:off
  return Try.of(joinPoint::proceed)
            .map(value ->
                Match(value).of(
                    Case($(instanceOf(Mono.class)),
                        m -> m.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(instanceOf(Flux.class)),
                        f -> f.doOnTerminate(() -> stopTimer(className, methodName, metricName, timer))),

                    Case($(), res -> {
                      stopTimer(className, methodName, metricName, timer);
                      return res;
                    })
                ))
            .get();
  //@formatter:on
}
 
Example 26
@Override
public <T extends Annotation> void checkPermissions(T rawMethodAnnotation, String userCrn, ProceedingJoinPoint proceedingJoinPoint,
        MethodSignature methodSignature, long startTime) {
    CheckPermissionByResourceNameList methodAnnotation = (CheckPermissionByResourceNameList) rawMethodAnnotation;
    AuthorizationResourceAction action = methodAnnotation.action();
    Collection<String> resourceNames = commonPermissionCheckingUtils
            .getParameter(proceedingJoinPoint, methodSignature, ResourceNameList.class, Collection.class);
    List<String> resourceCrnList = commonPermissionCheckingUtils.getResourceBasedCrnProvider(action)
            .getResourceCrnListByResourceNameList(getNotNullResourceNames(resourceNames));
    commonPermissionCheckingUtils.checkPermissionForUserOnResources(action, userCrn, resourceCrnList);
}
 
Example 27
@BeforeClass
public static void beforeClass() {
    cut = new ReadThroughSingleCacheAdvice();
    cut.setCacheBase(new CacheBase());

    pjp = createMock(ProceedingJoinPoint.class);
    cache = createMock(Cache.class);
    sig = createMock(MethodSignature.class);
}
 
Example 28
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)",
		argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(JoinPoint jp,
	MutableModifable mixin, Object newValue) {

	/*
	 * We use the mixin to check and, if necessary, change,
	 * modification status. We need the JoinPoint to get the
	 * setter method. We use newValue for comparison.
	 * We try to invoke the getter if possible.
	 */

	if (mixin.isModified()) {
		// Already changed, don't need to change again
		//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();
			// Don't sweat on exceptions; assume value was modified
		}
	}
	else {
		//System.out.println("cannot get getter for " + jp);
	}
	if (modified) {
		mixin.markDirty();
	}
}
 
Example 29
Source Project: ace-cache   Source File: CacheAspect.java    License: Apache License 2.0 5 votes vote down vote up
@Around("aspect()&&@annotation(anno)")
public Object interceptor(ProceedingJoinPoint invocation, Cache anno)
        throws Throwable {
    MethodSignature signature = (MethodSignature) invocation.getSignature();
    Method method = signature.getMethod();
    Object result = null;
    Class<?>[] parameterTypes = method.getParameterTypes();
    Object[] arguments = invocation.getArgs();
    String key = "";
    String value = "";
    try {
        key = getKey(anno, parameterTypes, arguments);
        value = cacheAPI.get(key);
        Type returnType = method.getGenericReturnType();
        result = getResult(anno, result, value, returnType);
    } catch (Exception e) {
        log.error("获取缓存失败:" + key, e);
    } finally {
        if (result == null) {
            result = invocation.proceed();
            if (StringUtils.isNotBlank(key)) {
                cacheAPI.set(key, result, anno.expire());
            }
        }
    }
    return result;
}
 
Example 30
Source Project: fluent-validator   Source File: MockInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Around("execution(* com.baidu.unbiz.fluentvalidator.service.impl.CarServiceImpl.*(..))")
public Object validate4AjaxQuery(ProceedingJoinPoint pjp) throws Throwable {
    MethodInvocationProceedingJoinPoint methodJoinPoint = (MethodInvocationProceedingJoinPoint) pjp;
    MethodSignature methodSignature = (MethodSignature) methodJoinPoint.getSignature();
    System.out.println("here we enter aspectJ interceptor");
    Object[] args = pjp.getArgs();
    System.out.println(Arrays.asList(args));
    System.out.println(methodSignature);

    return pjp.proceed();
}