org.aspectj.lang.reflect.MethodSignature Java Examples

The following examples show how to use org.aspectj.lang.reflect.MethodSignature. 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 File: AnnotationUtils.java    From data-prep with 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 #2
Source File: NamespaceSecurityAdviceTest.java    From herd with 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 #3
Source File: LogAspect.java    From mall with 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 #4
Source File: LoggingAspect.java    From Cheddar with 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 #5
Source File: RedisCacheAspect.java    From mall with 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 #6
Source File: HttpAspect.java    From yue-library with 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 #7
Source File: UeLogAspect.java    From ueboot with 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 #8
Source File: CachingAnnotationsAspect.java    From jim-framework with 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 #9
Source File: IdempotentAround.java    From hyena with 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 #10
Source File: SimplePerformanceMonitor.java    From spring-cloud-study with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: MethodLogger.java    From semagrow with 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 #12
Source File: DataSourceAspect.java    From supplierShop with 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 #13
Source File: ResourceCoordinatorInterceptor.java    From tcc-transaction with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: DatasourceSelectorAspect.java    From spring-boot-demo with 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 #15
Source File: DataSourceAspect.java    From SuperBoot with 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
Source File: MethodTimeLogger.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * If the pointcuts results true, this method is invoked every time a method satisfies the
 * criteria given in the pointcut.
 *
 * @param point The JoinPoint before method execution
 * @return result of method execution
 * @throws Throwable
 */
@Around("isConfigEnabled() && (pointCut() || pointCutAll())")
public Object log(ProceedingJoinPoint point) throws Throwable {
    long start = System.currentTimeMillis();
    MethodSignature signature = (MethodSignature) point.getSignature();
    Object result = point.proceed();
    String[] args = signature.getParameterNames();

    String argString;
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append("[");
    if (args != null && args.length != 0) {
        String delimiter = "";
        for (String arg : args) {
            stringBuilder.append(delimiter);
            delimiter = ", ";
            stringBuilder.append(arg);
        }
    }
    stringBuilder.append("]");
    argString = stringBuilder.toString();
    MessageContext messageContext = MessageContext.getCurrentMessageContext();
    if (messageContext != null) {
        Map headers = (Map) messageContext.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
        if (headers != null) {
            String correlationId = (String) headers.get(APIConstants.AM_ACTIVITY_ID);
            if (correlationId != null) {
                MDC.put(APIConstants.CORRELATION_ID, correlationId);
            }
        }
    }
    log.info((System.currentTimeMillis() - start) + "|METHOD|" +
            MethodSignature.class.cast(point.getSignature()).getDeclaringTypeName() + "|" +
            MethodSignature.class.cast(point.getSignature()).getMethod().getName()+ "|" + argString);
    return result;
}
 
Example #17
Source File: ChangeSchemeStatusAspect.java    From agile-service-old with Apache License 2.0 5 votes vote down vote up
@Around("updateStatusPointcut()")
public Object interceptor(ProceedingJoinPoint pjp) {
    // 下面两个数组中,参数值和参数名的个数和位置是一一对应的。
    Object[] args = pjp.getArgs();
    String[] argNames = ((MethodSignature) pjp.getSignature()).getParameterNames();
    Long schemeId = null;
    for (int i = 0; i < argNames.length; i++) {
        if (argNames[i].equals("schemeId")) {
            schemeId = Long.valueOf(args[i] + "");
        }
    }
    logger.info("schemeId:{}", schemeId);
    StateMachineSchemeDTO scheme = schemeMapper.selectByPrimaryKey(schemeId);
    if (scheme == null) {
        throw new CommonException("error.scheme.notFound");
    }
    if (scheme.getStatus().equals(StateMachineSchemeStatus.ACTIVE)) {
        scheme.setStatus(StateMachineSchemeStatus.DRAFT);
        Criteria criteria = new Criteria();
        criteria.update("status");
        schemeMapper.updateByPrimaryKeyOptions(scheme, criteria);
    }

    try {
        return pjp.proceed();
    } catch (Throwable e) {
        throw new CommonException("error.changeSchemeStatusAspect.proceed", e);
    }
}
 
Example #18
Source File: AllureAspectJ.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@Before("anyAssert()")
public void stepStart(final JoinPoint joinPoint) {
    final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();

    final String uuid = UUID.randomUUID().toString();
    final String name = joinPoint.getArgs().length > 0
            ? String.format("%s \'%s\'", methodSignature.getName(), arrayToString(joinPoint.getArgs()))
            : methodSignature.getName();

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

    getLifecycle().startStep(uuid, result);
}
 
Example #19
Source File: BulkheadAspect.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Around(value = "matchAnnotatedClassOrMethod(bulkheadAnnotation)", argNames = "proceedingJoinPoint, bulkheadAnnotation")
public Object bulkheadAroundAdvice(ProceedingJoinPoint proceedingJoinPoint,
    @Nullable Bulkhead bulkheadAnnotation) throws Throwable {
    Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
    String methodName = method.getDeclaringClass().getName() + "#" + method.getName();
    if (bulkheadAnnotation == null) {
        bulkheadAnnotation = getBulkheadAnnotation(proceedingJoinPoint);
    }
    if (bulkheadAnnotation == null) { //because annotations wasn't found
        return proceedingJoinPoint.proceed();
    }
    Class<?> returnType = method.getReturnType();
    String backend = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), bulkheadAnnotation.name());
    String fallbackMethodValue = spelResolver.resolve(method, proceedingJoinPoint.getArgs(), bulkheadAnnotation.fallbackMethod());
    if (bulkheadAnnotation.type() == Bulkhead.Type.THREADPOOL) {
        if (StringUtils.isEmpty(fallbackMethodValue)) {
            return proceedInThreadPoolBulkhead(proceedingJoinPoint, methodName, returnType,
                backend);
        }
        return executeFallBack(proceedingJoinPoint, fallbackMethodValue, method,
            () -> proceedInThreadPoolBulkhead(proceedingJoinPoint, methodName, returnType,
                backend));
    } else {
        io.github.resilience4j.bulkhead.Bulkhead bulkhead = getOrCreateBulkhead(methodName,
            backend);
        if (StringUtils.isEmpty(fallbackMethodValue)) {
            return proceed(proceedingJoinPoint, methodName, bulkhead, returnType);
        }
        return executeFallBack(proceedingJoinPoint, fallbackMethodValue, method,
            () -> proceed(proceedingJoinPoint, methodName, bulkhead, returnType));
    }

}
 
Example #20
Source File: AbstractRequestLockInterceptor.java    From jim-framework with Apache License 2.0 5 votes vote down vote up
@Around("pointcut()")
public Object doAround(ProceedingJoinPoint point) throws Throwable{
    Signature signature = point.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    String targetName = point.getTarget().getClass().getName();
    String methodName = point.getSignature().getName();
    Object[] arguments = point.getArgs();

    if (method != null && method.isAnnotationPresent(RequestLockable.class)) {
        logger.info("RequestLockable doAround start");
        RequestLockable requestLockable = method.getAnnotation(RequestLockable.class);

        String requestLockKey = getLockKey(method,targetName, methodName, requestLockable.key(), arguments);
        Lock lock=this.getLock(requestLockKey);
        boolean isLock = this.tryLock(requestLockable.maximumWaiteTime(),requestLockable.expirationTime(), requestLockable.timeUnit(),lock);
        if(isLock) {
            try {
                logger.info("RequestLockable point.proceed start");
                return point.proceed();
            } finally {
                try {
                    lock.unlock();
                }
                catch (IllegalMonitorStateException e){
                    logger.info("not locked by current thread",e);
                }
            }
        } else {
            logger.error("get lock error,key:{}",requestLockKey);
            //多线程场景下主线程捕获异常需要注意,不同的调用方式可能会影响异常的抛出
            throw new RuntimeException("get lock error");
        }
    }
    return point.proceed();
}
 
Example #21
Source File: AspectjAopInterceptor.java    From AutoLoadCache with Apache License 2.0 5 votes vote down vote up
public void checkAndDeleteCache(JoinPoint jp, Object retVal) throws Throwable {
    Signature signature = jp.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    if (method.isAnnotationPresent(CacheDelete.class)) {
        CacheDelete cacheDelete = method.getAnnotation(CacheDelete.class);
        this.deleteCache(jp, cacheDelete, retVal);
    }
}
 
Example #22
Source File: DistributedLockAspect.java    From spring-boot-cookbook with Apache License 2.0 5 votes vote down vote up
@Around("distributedLockPointCut()")
public Object process(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = signature.getMethod();
    DistributedLock annotation = method.getAnnotation(DistributedLock.class);
    if (annotation == null) {
        Class<?> classTarget = proceedingJoinPoint.getTarget().getClass();
        Class<?>[] parameterTypes = ((MethodSignature) proceedingJoinPoint.getSignature()).getParameterTypes();
        Method objMethod = classTarget.getMethod(signature.getName(), parameterTypes);
        annotation = objMethod.getAnnotation(DistributedLock.class);
    }
    String lockKey = keyGenerator.getLockKey(proceedingJoinPoint, annotation);
    if (StringUtils.isBlank(lockKey)) {
        log.warn("lockKey is blank");
        throw new DistributedLockException("lock key must not be blank");
    }
    Boolean success = getLock(annotation, lockKey);
    if (success) {
        try {
            return proceedingJoinPoint.proceed();
        } finally {
            stringRedisTemplate.delete(lockKey);
            log.debug("release lock . key->{}", lockKey);
        }
    }
    //能走到这的,肯定是没有获取到锁,原因有两个,超过了等待时间还没有获取到
    throw new DistributedLockException("fail to ge lock");
}
 
Example #23
Source File: AbstractOperationExecutionWithParameterAspect.java    From TeaStore with Apache License 2.0 5 votes vote down vote up
private void logWithParameter(final ProceedingJoinPoint thisJoinPoint, String signature,
    String sessionId, long traceId, long tin, long tout, String hostname, int eoi, int ess,
    Object retval) {
  /** extension over the original routine. */
  final String[] names = ((MethodSignature) thisJoinPoint.getSignature()).getParameterNames();

  final Object[] arguments = thisJoinPoint.getArgs();
  final String[] values = new String[arguments.length];

  int i = 0;
  for (final Object argument : arguments) {
    values[i] = parseObjectToString(argument);
    if (argument instanceof java.util.Collection && !names[i].endsWith(".size()")) {
      names[i] = names[i] + ".size()";
    }
    i++;
  }
  // get return type
  Class<?> returnClass = ((MethodSignature) thisJoinPoint.getSignature()).getReturnType();
  final String returnType;
  final String returnValue;
  if (returnClass.equals(Void.TYPE)) {
    // return type is void
    returnType = "void";
    returnValue = "";
  } else {
    // we have a return type
    returnType = returnClass.getName();
    returnValue = parseObjectToString(retval);
  }

  CTRLINST.newMonitoringRecord(new OperationExecutionWithParametersRecord(signature, sessionId,
      traceId, tin, tout, hostname, eoi, ess, names, values, returnType, returnValue));

}
 
Example #24
Source File: NamespaceSecurityAdviceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
@Test
public void checkPermissionAssertAccessDeniedWhenCurrentUserHasNoAnyRequiredPermissions() 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("mockMethodMultiplePermissions", 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.WRITE_DESCRIPTIVE_CONTENT)));
    SecurityContextHolder.getContext().setAuthentication(
        new TestingAuthenticationToken(new SecurityUserWrapper(userId, "", false, false, false, false, Arrays.asList(), applicationUser), null));

    try
    {
        namespaceSecurityAdvice.checkPermission(joinPoint);
        fail();
    }
    catch (Exception e)
    {
        assertEquals(AccessDeniedException.class, e.getClass());
        assertEquals(String.format("User \"%s\" does not have \"[READ OR WRITE]\" permission(s) to the namespace \"foo\"", userId), e.getMessage());
    }
}
 
Example #25
Source File: DataScopeAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private DataScope getAnnotationLog(JoinPoint joinPoint)
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(DataScope.class);
    }
    return null;
}
 
Example #26
Source File: DataSourceAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 获取需要切换的数据源
 */
public DataSource getDataSource(ProceedingJoinPoint point)
{
    MethodSignature signature = (MethodSignature) point.getSignature();
    DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
    if (Objects.nonNull(dataSource))
    {
        return dataSource;
    }

    return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
}
 
Example #27
Source File: LogAspect.java    From RuoYi-Vue with MIT License 5 votes vote down vote up
/**
 * 是否存在注解,如果存在就获取
 */
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception
{
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();

    if (method != null)
    {
        return method.getAnnotation(Log.class);
    }
    return null;
}
 
Example #28
Source File: DTXInfo.java    From tx-lcn with Apache License 2.0 5 votes vote down vote up
public static DTXInfo getFromCache(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    String signature = proceedingJoinPoint.getSignature().toString();
    String unitId = Transactions.unitId(signature);
    DTXInfo dtxInfo = dtxInfoCache.get(unitId);
    if (Objects.isNull(dtxInfo)) {
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        Class<?> targetClass = proceedingJoinPoint.getTarget().getClass();
        Method thisMethod = targetClass.getMethod(method.getName(), method.getParameterTypes());
        dtxInfo = new DTXInfo(thisMethod, proceedingJoinPoint.getArgs(), targetClass);
        dtxInfoCache.put(unitId, dtxInfo);
    }
    dtxInfo.reanalyseMethodArgs(proceedingJoinPoint.getArgs());
    return dtxInfo;
}
 
Example #29
Source File: ShardingTransactionJDBCAspect.java    From opensharding-spi-impl with Apache License 2.0 5 votes vote down vote up
private ShardingTransactionType getAnnotation(final JoinPoint joinPoint) {
    Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    ShardingTransactionType result = method.getAnnotation(ShardingTransactionType.class);
    if (null == result) {
        result = method.getDeclaringClass().getAnnotation(ShardingTransactionType.class);
    }
    return result;
}
 
Example #30
Source File: ResourceCoordinatorInterceptor.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
/**
 * 生成和登记根参与者.
 * @param pjp
 * @return
 */
private Participant generateAndEnlistRootParticipant(ProceedingJoinPoint pjp) {
	LOG.debug("==>generateAndEnlistRootParticipant(ProceedingJoinPoint pjp)");
    MethodSignature signature = (MethodSignature) pjp.getSignature();
    Method method = signature.getMethod();
    Compensable compensable = getCompensable(pjp);
    String confirmMethodName = compensable.confirmMethod(); // 确认方法
    String cancelMethodName = compensable.cancelMethod(); // 取消方法

    Transaction transaction = transactionConfigurator.getTransactionManager().getCurrentTransaction(); // 获取当前事务

    TransactionXid xid = new TransactionXid(transaction.getXid().getGlobalTransactionId()); // 获取事务Xid
    LOG.debug("==>TransactionXid:" + TransactionXid.byteArrayToUUID(xid.getGlobalTransactionId()).toString()
    		+ "|" + TransactionXid.byteArrayToUUID(xid.getBranchQualifier()).toString());

    Class targetClass = ReflectionUtils.getDeclaringType(pjp.getTarget().getClass(), method.getName(), method.getParameterTypes());

    // 构建确认方法的提交上下文
    InvocationContext confirmInvocation = new InvocationContext(targetClass,
            confirmMethodName,
            method.getParameterTypes(), pjp.getArgs());
    
    // 构建取消方法的提交上下文
    InvocationContext cancelInvocation = new InvocationContext(targetClass,
            cancelMethodName,
            method.getParameterTypes(), pjp.getArgs());

    // 构建参与者对像
    Participant participant =
            new Participant(
                    xid,
                    new Terminator(confirmInvocation, cancelInvocation));

    transaction.enlistParticipant(participant); // 加入参与者

    TransactionRepository transactionRepository = transactionConfigurator.getTransactionRepository();
    transactionRepository.update(transaction); // 更新事务

    return participant;
}