org.aspectj.lang.annotation.Around Java Examples

The following examples show how to use org.aspectj.lang.annotation.Around. 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: OperateLogAspect.java    From magic-starter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Around("@annotation(operateLog)")
public Object around(ProceedingJoinPoint point, OperateLog operateLog) throws Throwable {
	// 获取类名
	String className = point.getTarget().getClass().getName();
	// 获取方法
	String methodName = point.getSignature().getName();
	// 开始时间
	long beginTime = System.currentTimeMillis();
	// 执行方法
	Object result = point.proceed();
	// 执行时长(毫秒)
	long time = System.currentTimeMillis() - beginTime;
	// 日志描述
	String description = operateLog.value();
	// 异步记录日志
	LogEventPublisher.publishOperateLogEvent(methodName, className, description, time);
	return result;
}
 
Example #2
Source File: OauthAuthorizeAspect.java    From microservices-platform with Apache License 2.0 6 votes vote down vote up
@Around("execution(* org.springframework.security.oauth2.provider.endpoint.AuthorizationEndpoint.authorize(..))")
public Object doAroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    Map<String, String> parameters = (Map<String, String>) args[1];
    Principal principal = (Principal) args[3];
    if (principal instanceof TenantUsernamePasswordAuthenticationToken) {
        TenantUsernamePasswordAuthenticationToken tenantToken = (TenantUsernamePasswordAuthenticationToken)principal;
        String clientId = tenantToken.getClientId();
        String requestClientId = parameters.get(OAuth2Utils.CLIENT_ID);
        //判断是否不同租户单点登录
        if (!requestClientId.equals(clientId)) {
            try {
                TenantContextHolder.setTenant(requestClientId);
                //重新查询对应该租户的角色等信息
                LoginAppUser user = userService.findByUsername(tenantToken.getName());
                tenantToken = new TenantUsernamePasswordAuthenticationToken(user, tenantToken.getCredentials(), user.getAuthorities(), requestClientId);
                args[3] = tenantToken;
            } finally {
                TenantContextHolder.clear();
            }
        }
    }
    return joinPoint.proceed(args);
}
 
Example #3
Source File: LoggingAspect.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice.
 * @return result.
 * @throws Throwable throws {@link IllegalArgumentException}.
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #4
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 #5
Source File: LogAspect.java    From java-master with Apache License 2.0 6 votes vote down vote up
@Around("logPointCut()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    long nowMillis = System.currentTimeMillis();
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = requestAttributes.getRequest();
    Object[] parameters = joinPoint.getArgs();
    String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    Object resObject;
    try {
        resObject = joinPoint.proceed(parameters);
    } catch (Exception e) {
        logger.error("aspect error req ip:{}|class_method:{}|args:{}", getIpAddr(request), classMethod, Arrays.toString(parameters));
        throw e;
    }
    logger.info("aspect req ip:{}|class_method:{}|args:{},response:{},cost time:{}ms", getIpAddr(request), classMethod,
            Arrays.toString(parameters), resObject, System.currentTimeMillis() - nowMillis);
    return resObject;
}
 
Example #6
Source File: TryAgainAspect.java    From admin-plus with Apache License 2.0 6 votes vote down vote up
@Around("retryOnOptFailure()")
	@Transactional(rollbackFor = Exception.class)
	public Object doConcurrentOperation(ProceedingJoinPoint pjp) throws Throwable {
		int numAttempts = 0;
		do {
			numAttempts++;
			try {
				//再次执行业务代码
				return pjp.proceed();
			} catch (TryAgainException ex) {
				if (numAttempts > maxRetries) {
					//log failure information, and throw exception
//					如果大于 默认的重试机制 次数,我们这回就真正的抛出去了
					throw new ApiException(ApiResultEnum.ERROR);
				}else{
					//如果 没达到最大的重试次数,将再次执行
					System.out.println("=====正在重试====="+numAttempts+"次");
				}
			}
		} while (numAttempts <= this.maxRetries);

		return null;
	}
 
Example #7
Source File: DataSourceAspect.java    From supplierShop with MIT License 6 votes vote down vote up
@Around("dsPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable
{
    DataSource dataSource = getDataSource(point);

    if (StringUtils.isNotNull(dataSource))
    {
        DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
    }

    try
    {
        return point.proceed();
    }
    finally
    {
        // 销毁数据源 在执行方法之后
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}
 
Example #8
Source File: BindingResultAspect.java    From HIS with Apache License 2.0 6 votes vote down vote up
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    for (Object arg : args) {
        if (arg instanceof BindingResult) {
            BindingResult result = (BindingResult) arg;
            if (result.hasErrors()) {
                FieldError fieldError = result.getFieldError();
                if(fieldError!=null){
                    return CommonResult.validateFailed(fieldError.getDefaultMessage());
                }else{
                    return CommonResult.validateFailed();
                }
            }
        }
    }
    return joinPoint.proceed();
}
 
Example #9
Source File: BindingResultAspect.java    From mall-swarm with Apache License 2.0 6 votes vote down vote up
@Around("BindingResult()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
    Object[] args = joinPoint.getArgs();
    for (Object arg : args) {
        if (arg instanceof BindingResult) {
            BindingResult result = (BindingResult) arg;
            if (result.hasErrors()) {
                FieldError fieldError = result.getFieldError();
                if(fieldError!=null){
                    return CommonResult.validateFailed(fieldError.getDefaultMessage());
                }else{
                    return CommonResult.validateFailed();
                }
            }
        }
    }
    return joinPoint.proceed();
}
 
Example #10
Source File: RetryAop.java    From sisyphus with Apache License 2.0 6 votes vote down vote up
/**
 * 执行核心方法
 * 1. 判断是否拥有 {@link RetryAble} 标识的注解。
 * 2. 没有则正常执行。
 * @param point 切点
 * @return 结果
 * @throws Throwable 异常信息
 */
@Around("myPointcut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    final Method method = getCurrentMethod(point);
    final RetryMethodHandler retryMethodHandler = InstanceFactory.getInstance()
            .singleton(RetryMethodHandler.class);

    //1. 判断注解信息
    Optional<RetryAbleBean> retryAbleAnnotationOpt = retryMethodHandler.retryAbleAnnotation(method);
    if(!retryAbleAnnotationOpt.isPresent()) {
        return point.proceed();
    }

    //2. 重试执行
    final Callable callable = buildCallable(point);
    final RetryAbleBean retryAbleBean = retryAbleAnnotationOpt.get();
    return retryMethodHandler.retryCall(retryAbleBean, callable);
}
 
Example #11
Source File: OptimisticLockAspect.java    From youran with Apache License 2.0 6 votes vote down vote up
@Around("servicePointcut()")
public Object doServiceAround(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
    Signature signature = thisJoinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    final Method targetMethod = methodSignature.getMethod();
    OptimisticLock optimisticLock = targetMethod.getAnnotation(OptimisticLock.class);
    if (optimisticLock == null) {
        throw new RuntimeException("乐观锁aop异常");
    }

    Class<? extends Exception>[] catchTypes = optimisticLock.catchType();
    if (catchTypes == null || catchTypes.length == 0) {
        throw new RuntimeException("乐观锁aop异常");
    }
    int retry = optimisticLock.retry();
    Object object = tryServiceProceed(thisJoinPoint, catchTypes, retry);
    return object;
}
 
Example #12
Source File: LogRecordAspect.java    From teaching with Apache License 2.0 6 votes vote down vote up
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();

    String url = request.getRequestURL().toString();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = pjp.proceed();

    logger.info("请求结束,controller的返回值是 " + result);
    return result;
}
 
Example #13
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 #14
Source File: LoggingAspect.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #15
Source File: LogRecordAspect.java    From jeecg-boot-with-activiti with MIT License 6 votes vote down vote up
@Around("excudeService()")
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
    RequestAttributes ra = RequestContextHolder.getRequestAttributes();
    ServletRequestAttributes sra = (ServletRequestAttributes) ra;
    HttpServletRequest request = sra.getRequest();

    String url = request.getRequestURL().toString();
    String method = request.getMethod();
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    logger.info("请求开始, 各个参数, url: {}, method: {}, uri: {}, params: {}", url, method, uri, queryString);

    // result的值就是被拦截方法的返回值
    Object result = pjp.proceed();

    logger.info("请求结束,controller的返回值是 " + result);
    return result;
}
 
Example #16
Source File: RetryAspect.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
@Around("RetryPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
    Method method = ((MethodSignature) point.getSignature()).getMethod();
    Retry retry = method.getAnnotation(Retry.class);
    for (int i = 0; i < retry.times(); i++) {
        try {
            if (i != 0) {
                log.info("The {} times to retry {}", i + 1, method.getName());
            }
            return point.proceed();
        } catch (IOException e) {
            log.error("IOException: {}", e.getMessage());
            Thread.sleep(retry.interval() * 1000);
        }
    }
    throw new IOException();
}
 
Example #17
Source File: SyncDatabaseExt.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Around("syncSaveEsData()")  
   public Object syncSaveEsData(ProceedingJoinPoint pjp) throws Throwable{  
   	Object[] args  = pjp.getArgs() ;
   	if(args.length == 1){
   		Object data = args[0] ;
   		if(data!=null){
    		if(data instanceof UKeFuList){
    			/**只有一个地方用到,从DB同步数据到ES**/
    		}else if(data instanceof List){
    			List<Object> dataList = (List<Object>)data ;
    			for(Object dbData : dataList){
    				UKTools.multiupdate(new MultiUpdateEvent<Object>(dbData , dbDataRes, UKDataContext.MultiUpdateType.SAVE.toString()));
    			}
    		}else{
    			UKTools.multiupdate(new MultiUpdateEvent<Object>(data, dbDataRes, UKDataContext.MultiUpdateType.SAVE.toString()));
    		}
   		}
   	}
       return pjp.proceed();  
   }
 
Example #18
Source File: LoggingAspect.java    From flair-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #19
Source File: LoggingAspect.java    From flair-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("loggingPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
                joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #20
Source File: LoggingAspect.java    From java-microservices-examples with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice.
 * @return result.
 * @throws Throwable throws {@link IllegalArgumentException}.
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #21
Source File: TransactionAspect.java    From txle with Apache License 2.0 6 votes vote down vote up
@Around("execution(@org.apache.servicecomb.saga.omega.transaction.annotations.Compensable * *(..)) && @annotation(compensable)")
Object advise(ProceedingJoinPoint joinPoint, Compensable compensable) throws Throwable {
  Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
  String localTxId = context.localTxId();
  context.newLocalTxId();
  LOG.debug("Updated context {} for compensable method {} ", context, method.toString());

  int retries = compensable.retries();
  RecoveryPolicy recoveryPolicy = RecoveryPolicyFactory.getRecoveryPolicy(retries);
  try {
    return recoveryPolicy.apply(joinPoint, compensable, interceptor, context, localTxId, retries);
  } catch (Exception e) {
    throw e;
  } finally {
    context.setLocalTxId(localTxId);
    LOG.debug("Restored context back to {}", context);
  }
}
 
Example #22
Source File: OperLogAspect.java    From joyqueue with Apache License 2.0 6 votes vote down vote up
@Around("@annotation(com.jd.laf.web.vertx.annotation.Path)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
    Object result = joinPoint.proceed();
    if (result instanceof Response) {
        Response response = (Response) result;
        Class<?> clazz = joinPoint.getSignature().getDeclaringType();
        if (response.getCode() == 200 && !exceptCommandClasses.contains(clazz)) {
            MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
            Path path = methodSignature.getMethod().getAnnotation(Path.class);
            int operType = -1;
            if (StringUtils.containsIgnoreCase(path.value(), "add")) {
                operType = OperLog.OperType.ADD.value();
            } else if (StringUtils.containsIgnoreCase(path.value(), "delete")) {
                operType = OperLog.OperType.DELETE.value();
            } else if (StringUtils.containsIgnoreCase(path.value(), "update")) {
                operType = OperLog.OperType.UPDATE.value();
            }
            if (operType >= 1 && operType <= 3) {
                addOperLog(clazz.getSimpleName(), path.value(), joinPoint.getArgs(), operType);
            }
        }
    }
    return result;
}
 
Example #23
Source File: LoggingAspect.java    From cubeai with Apache License 2.0 6 votes vote down vote up
/**
 * Advice that logs when a method is entered and exited.
 *
 * @param joinPoint join point for advice
 * @return result
 * @throws Throwable throws IllegalArgumentException
 */
@Around("applicationPackagePointcut() && springBeanPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug("Enter: {}.{}() with argument[s] = {}", joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
    }
    try {
        Object result = joinPoint.proceed();
        if (log.isDebugEnabled()) {
            log.debug("Exit: {}.{}() with result = {}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName(), result);
        }
        return result;
    } catch (IllegalArgumentException e) {
        log.error("Illegal argument: {} in {}.{}()", Arrays.toString(joinPoint.getArgs()),
            joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());

        throw e;
    }
}
 
Example #24
Source File: PerformanceAop.java    From android-performance with MIT License 5 votes vote down vote up
@Around("execution(* android.app.Activity.setContentView(..))")
public void getSetContentViewTime(ProceedingJoinPoint joinPoint) {
    Signature signature = joinPoint.getSignature();
    String name = signature.toShortString();
    long time = System.currentTimeMillis();
    try {
        joinPoint.proceed();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    LogUtils.i(name + " cost " + (System.currentTimeMillis() - time));
}
 
Example #25
Source File: ProjectTreeAspect.java    From ProjectTree with Apache License 2.0 5 votes vote down vote up
@Around("pointcut()")
public Object around(ProceedingJoinPoint pjp){
    int identify = new Random().nextInt();
    AroundMethod.playBeforeMethod(pjp,identify);
    Object obj = null;
    try {
        obj = pjp.proceed();
    } catch (Throwable throwable) {
        throwable.printStackTrace();
    }
    AroundMethod.playAfterMethod(pjp,identify,obj);
    return obj;
}
 
Example #26
Source File: AspectJTest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Around("test()")
public Object aroundTest(ProceedingJoinPoint joinPoint) {
	System.out.println("around Before");
	Object o = null;
	try {
		// 调用切面的方法
		o = joinPoint.proceed();
	} catch (Throwable e) {
		e.printStackTrace();
	}
	System.out.println("around After");
	return o;
}
 
Example #27
Source File: ActionAspect.java    From kvf-admin with MIT License 5 votes vote down vote up
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
	long beginTime = System.currentTimeMillis();
	//执行方法
	Object result = point.proceed();
	//执行时长(毫秒)
	long time = System.currentTimeMillis() - beginTime;

	//保存日志
	saveActionLog(point, time, true);

	return result;
}
 
Example #28
Source File: ComputerOrMobileAdapterAspect.java    From springBoot with MIT License 5 votes vote down vote up
/**
 * 环绕通知
 */
@Around(value = "pointcut()")
public Object around(ProceedingJoinPoint pjp) {
    //request对象
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();

    try {
        //获取返回值
        Object o = pjp.proceed();

        //拦截返回值为ModelAndView即可
        if("org.springframework.web.servlet.ModelAndView".equals(o.getClass().getName())){
             /*
            PC端ua:windows nt、macintosh
            移动端ua:iphone、ipod、android
         */
            String adapter;
            String ua = request.getHeader("user-agent").toLowerCase();
            if (ua.contains("iphone") || ua.contains("ipod") || ua.contains("android")) {
                adapter = "mobile";
            } else {
                adapter = "computer";
            }
            log.info("PC端、手机端页面适配器:" + adapter);

            //强势修改
            ModelAndView modelAndView = (ModelAndView) o;
            String viewName = modelAndView.getViewName();
            modelAndView.setViewName(adapter + "/" + viewName);
            o = modelAndView;
        }

        return o;
    } catch (Throwable throwable) {
        //返回统一错误页面
        log.error(throwable.getMessage());
        return new ModelAndView("common/error/500");
    }
}
 
Example #29
Source File: AutoLogAspect.java    From teaching with Apache License 2.0 5 votes vote down vote up
@Around("logPointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
	long beginTime = System.currentTimeMillis();
	//执行方法
	Object result = point.proceed();
	//执行时长(毫秒)
	long time = System.currentTimeMillis() - beginTime;

	//保存日志
	saveSysLog(point, time);

	return result;
}
 
Example #30
Source File: SecurityAspect.java    From mcspring-boot with MIT License 5 votes vote down vote up
@Order(0)
@Around("within(@(@dev.alangomes.springspigot.security.Authorize *) *) " +
        "|| execution(@(@dev.alangomes.springspigot.security.Authorize *) * *(..)) " +
        "|| @within(dev.alangomes.springspigot.security.Authorize)" +
        "|| execution(@dev.alangomes.springspigot.security.Authorize * *(..))")
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
    val sender = context.getSender();
    if (sender == null) {
        throw new PlayerNotFoundException();
    }
    val method = ((MethodSignature) joinPoint.getSignature()).getMethod();
    val senderContext = new StandardEvaluationContext(sender);
    val parameters = method.getParameters();
    IntStream.range(0, parameters.length)
            .forEach(i -> senderContext.setVariable(parameters[i].getName(), joinPoint.getArgs()[i]));
    senderContext.setVariable("session", sessionService.current());
    senderContext.setVariable("guard", guardService);

    AopAnnotationUtils.getAppliableAnnotations(method, Authorize.class).forEach(authorize -> {
        val expressionSource = authorize.value();
        val expression = expressionCache.computeIfAbsent(expressionSource, parser::parseExpression);
        senderContext.setVariable("params", authorize.params());
        if (!toBoolean(expression.getValue(senderContext, Boolean.class))) {
            val message = StringUtils.trimToNull(ChatColor.translateAlternateColorCodes('&', authorize.message()));
            throw new PermissionDeniedException(expressionSource, message);
        }
    });
    return joinPoint.proceed();
}