org.aspectj.lang.annotation.AfterReturning Java Examples

The following examples show how to use org.aspectj.lang.annotation.AfterReturning. 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: WebAopLog.java    From Jpom with MIT License 6 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) {
    if (aopLogInterface != null) {
        aopLogInterface.afterReturning(ret);
    }
    try {
        if (ret == null) {
            return;
        }
        // 处理完请求,返回内容
        Boolean isLog = IS_LOG.get();
        if (isLog != null && !isLog) {
            return;
        }
        DefaultSystemLog.getLog().info(" :" + ret.toString());
    } finally {
        IS_LOG.remove();
    }
}
 
Example #2
Source File: BindingResultAop.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
/**
 * Do after.
 *
 * @param joinPoint the join point
 */
@AfterReturning(pointcut = "validateAnnotation()")
public void doAfter(final JoinPoint joinPoint) {
	String methodName = joinPoint.getSignature().getName();
	Object target = joinPoint.getTarget();
	//得到拦截的方法
	Method method = getMethodByClassAndName(target.getClass(), methodName);
	Object[] objects = joinPoint.getArgs();
	//方法的参数
	assert method != null;
	ValidateAnnotation annotation = (ValidateAnnotation) getAnnotationByMethod(method, ValidateAnnotation.class);
	if (annotation != null) {
		BindingResult bindingResult = null;
		for (Object arg : objects) {
			if (arg instanceof BindingResult) {
				bindingResult = (BindingResult) arg;
			}
		}
		if (bindingResult != null && bindingResult.hasErrors()) {
			String errorInfo = bindingResult.getFieldError().getDefaultMessage();
			throw new IllegalArgumentException(errorInfo);
		}
	}
}
 
Example #3
Source File: WebLogAspect.java    From dk-foundation with GNU Lesser General Public License v2.1 6 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
    if (logger.isInfoEnabled()) {
        logger.debug("systemMode:"+systemMode);
        if ("prod".equals(systemMode.trim().toLowerCase()) && ret instanceof String) {
            String resp = ret.toString();
            try {
                int bodyindex =resp.indexOf("\"body\":");
                if(bodyindex>0) {
                    int errorindex =resp.indexOf(",\"errorMessage\"");
                    resp = resp.substring(0, bodyindex)+"..."+(errorindex>0?resp.substring(errorindex):"");
                }
                logger.info("RESPONSE : " + resp);
            } catch (Exception e) {
                logger.info("RESPONSE : " + ret);
            }
        } else {
            logger.info("RESPONSE : " + ret);
        }
    }
}
 
Example #4
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 #5
Source File: WebLogAcpect.java    From charging_pile_cloud with MIT License 6 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(JoinPoint joinPoint, Object ret) throws Throwable {
    Signature signature = joinPoint.getSignature();
    MethodSignature methodSignature = (MethodSignature) signature;
    Method method = methodSignature.getMethod();
    LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class);
    String time = (System.currentTimeMillis() - startTime.get()) + "ms";
    if (method.isAnnotationPresent(LogMenthodName.class)) {
        String token = request.getHeader(AuthSign.token);
        Long id = AuthSign.getUserId(token);
        if (id != 0) {
            logAdminAgent.setReturnParam(Arrays.asList(ret).toString());
            logAdminAgent.setTime(time);
            logAdminAgent.setOperatorId(id);
            logAdminAgent.setOperatorPlatform(LogAdminAgentAppEnum.ANDROID_SYS.getSystem());
            logAdminAgent.setLoginFacility(HttpRequestUtil.getSystemDevice(request));
            logAdminAgentService.save(logAdminAgent);
        }
    }
    // 处理完请求,返回内容
    logger.info("返回内容: " + Arrays.asList(ret));
    logger.info("耗时 : " + time);
    startTime.remove();

}
 
Example #6
Source File: AbstractAspectJAdvisorFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Find and return the first AspectJ annotation on the given method
 * (there <i>should</i> only be one anyway...)
 */
@SuppressWarnings("unchecked")
protected static AspectJAnnotation<?> findAspectJAnnotationOnMethod(Method method) {
	Class<?>[] classesToLookFor = new Class<?>[] {
			Before.class, Around.class, After.class, AfterReturning.class, AfterThrowing.class, Pointcut.class};
	for (Class<?> c : classesToLookFor) {
		AspectJAnnotation<?> foundAnnotation = findAnnotation(method, (Class<Annotation>) c);
		if (foundAnnotation != null) {
			return foundAnnotation;
		}
	}
	return null;
}
 
Example #7
Source File: WebRequestLogAspect.java    From oauth2-server with MIT License 5 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "wsLog()")
public void doAfterReturning(Object ret) throws Throwable {
    // 处理完请求,返回内容
    if (log.isInfoEnabled()) {
        try {
            log.info("Response from server : \n" + JsonUtil.objectToJsonString(ret));
        } catch (Exception e) {
            log.info("log http response Exception:\n ", e);
        }
    }
}
 
Example #8
Source File: UserInfoProcessor.java    From Pixiv-Illustration-Collection-Backend with Apache License 2.0 5 votes vote down vote up
@AfterReturning(value = "pointCut()", returning = "result")
public void withUserInfo(Object result) {
    Map<String, Object> context = AppContext.get();
    if (context != null && context.get(AuthConstant.USER_ID) != null) {
        int userId = (int) context.get(AuthConstant.USER_ID);
        if (result instanceof ResponseEntity) {
            deal(result, userId);
        } else if (result instanceof CompletableFuture) {
            ((CompletableFuture) result).thenAccept(e -> {
                deal(e, userId);
            });
        }
    }
}
 
Example #9
Source File: AntiAttackAspect.java    From ZTuoExchange_framework with MIT License 5 votes vote down vote up
@AfterReturning(pointcut = "antiAttack()")
public void doAfterReturning() throws Throwable {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String key = SysConstant.ANTI_ATTACK_ + request.getSession().getId();
    ValueOperations valueOperations = redisTemplate.opsForValue();
    valueOperations.set(key, "send sms all too often", 1, TimeUnit.MINUTES);
    log.info("处理耗时:" + (System.currentTimeMillis() - startTime.get()) + "ms");
    log.info("↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑");
    startTime.remove();
}
 
Example #10
Source File: OperateLogAspect.java    From bird-java with MIT License 5 votes vote down vote up
@AfterReturning("logPointCut()")
public void log(JoinPoint joinPoint) {
    try {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();
        OperateLogInfo logInfo = new OperateLogInfo(method,args);
        logBuffer.enqueue(logInfo);
    } catch (Exception ex) {
        log.error("操作日志记录失败:" + ex.getMessage());
    }
}
 
Example #11
Source File: Interceptor.java    From Mykit with Apache License 2.0 5 votes vote down vote up
@AfterReturning("aspect()")
public void afterReturn(JoinPoint joinPoint){
    System.out.println("===========执行后置返回通知==============");
    if(log.isInfoEnabled()){
        log.info("afterReturn " + joinPoint);
    }
}
 
Example #12
Source File: DaoAspect.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "templateMidTableInputMetaAspect()", returning = "object")
public void templateMidTableInputMetaAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String localeStr = request.getHeader("Content-Language");
    if (object != null) {
        replaceMessage(object, localeStr);
    }
}
 
Example #13
Source File: DaoAspect.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "ruleAspect()", returning = "object")
public void ruleAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String localeStr = request.getHeader("Content-Language");
    if (object != null) {
        replaceMessage(object, localeStr);
    }
}
 
Example #14
Source File: DetectNullsAspect.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@AfterReturning(pointcut="execution(* org.packt.aop.transaction.service.impl.EmployeeServiceImpl.readEmployees(..))", returning="emps")
public void detectNullEmps(JoinPoint joinPoint, List emps) {
   	  logger.info("DetectNullsAspect.detectNullEmps() detected : " + joinPoint.getSignature().getName());
   
	 if(emps == null){
		 logger.info("DetectNullsAspect.safeReadEmps() passes : empty " + emps);
	 }else{
		 logger.info("DetectNullsAspect.safeReadEmps() passes : " + emps);
	 }
}
 
Example #15
Source File: WebLogAspect.java    From SpringBoot-Base-System with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 使用@AfterReturning在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
 * 
 * @author 梦境迷离
 * @time 下午4:37:25.
 */
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
	// 处理完请求,返回内容
	log.info("RESPONSE : " + ret);
	log.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
}
 
Example #16
Source File: DaoAspect.java    From Qualitis with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "ruleTemplateAspect()", returning = "object")
public void ruleTemplateAspectAfter(JoinPoint joinPoint, Object object) throws InvocationTargetException, IllegalAccessException {
    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = attributes.getRequest();
    String localeStr = request.getHeader("Content-Language");
    if (object != null) {
        replaceMessage(object, localeStr);
    }
}
 
Example #17
Source File: MailSendLogAspect.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
@AfterReturning(returning="result", pointcut="log()")
public void doAfterReturning(JoinPoint joinPoint, R result) {
    ServletRequestAttributes sra =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpServletRequest request = sra.getRequest();
    // 下面两个数组中,参数值和参数名的个数和位置是一一对应的。
    // 参数值
    Object[] args = joinPoint.getArgs();
    // 参数名
    String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
    // 异步存储日志
    CompletableFuture.runAsync(new SaveLogThread(sendLogService, args, argNames,
            ThreadLocalUtils.get(Constants.CURRENT_MAIL_FROM), request.getRemoteHost(),
            result.getCode(), result.getMessage()), SAVE_LOG_EXECUTOR_SERVICE);
    log.debug("方法返回值:" + result);
}
 
Example #18
Source File: ResultfulOpRecordAspect.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@AfterReturning(value = "pointcut()", returning = "result")
    public void doAfter(JoinPoint joinPoint, Object result) {

        RequestMapping requestMapping = getRequestMapping(joinPoint);
        if (!isSholdRecord(requestMapping)) {
            return;
        }


        OperateRecord operateRecord = new OperateRecord();
        operateRecord.setOperateTime(new Date());
        Signature signature = joinPoint.getSignature();
        operateRecord.setHandler(signature.getDeclaringType().getSimpleName() + "#" + signature.getName());
        operateRecord.setOperator(userModule.getCurrentUserId());

        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//        if (requestAttributes != null) {
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
//            if (request != null) {
        operateRecord.setUri(request.getRequestURI());
        operateRecord.setHttpMethod(request.getMethod());
        operateRecord.setIp(WebUtils.getIpAddr(request));
        operateRecord.setQueryString(request.getQueryString());
//            }
//        }
        try {
            String HeadlerArgs = desensitizationArgs(request, joinPoint.getArgs());
            operateRecord.setHeadlerArgs(objectMapper.writeValueAsString(HeadlerArgs));
        } catch (Exception e) {
            log.warn(e.getMessage(), e);
        }
        if (result instanceof ApiRes) {
            ApiRes apiRes = (ApiRes) result;
            operateRecord.setApiResCode(apiRes.getCode());
            if (StringUtils.equals(apiRes.getCode(), ApiRes.CODE_SUCCESS)) {
                operateRecord.setOperateState(OperateRecord.OPERATE_STATE_SCUUESSED);
            }
        }
        operateAuditModule.recordOperate(operateRecord);
    }
 
Example #19
Source File: DetectNullsAspect.java    From Spring-5.0-Cookbook with MIT License 5 votes vote down vote up
@AfterReturning(pointcut="execution(* org.packt.aop.transaction.service.impl.EmployeeServiceImpl.readEmployee(..))", returning="emp")
public void detectNullOneEmp(JoinPoint joinPoint, Employee emp) {
	logger.info("DetectNullsAspect.detectNullOneEmp() detected : " + joinPoint.getSignature().getName());
	 if(emp == null){
		 logger.info("DetectNullsAspect.safeReadEmps() passes : empty " + emp);
	 }else{
		 logger.info("DetectNullsAspect.safeReadEmps() passes : " + emp);
	 }
	
}
 
Example #20
Source File: SysOperateLogAop.java    From scaffold-cloud with MIT License 5 votes vote down vote up
/**
 * 在结束之后插入后台操作记录
 */
@AfterReturning(pointcut = "pointCut()", returning = "retValue")
public void insertSysOperateLog(JoinPoint joinPoint, Object retValue) {
    if (retValue instanceof String || retValue instanceof ModelAndView) {
        return;
    }
    String methodName = joinPoint.getSignature().getName().toLowerCase();
    boolean match = Arrays.stream(LOG_METHOD_NAMES).anyMatch(methodName::contains);
    if (match) {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        taskExecutor.execute(()->{
            HttpServletRequest request = requestAttributes.getRequest();
            String uri = request.getRequestURI();
            String classType = joinPoint.getTarget().getClass().getName();
            String param = null;
            Map<String, String[]> parameterMap = request.getParameterMap();
            if(parameterMap != null && parameterMap.size()>0 ){
                param = JSON.toJSONString(parameterMap);
            }
            String returnParam = null;
            if(retValue!=null){
                returnParam = JSON.toJSONString(retValue);
            }
            SysOperateLogModel operateLog = new SysOperateLogModel();
            operateLog.setClassName(classType);
            operateLog.setRequestUrl(uri);
            operateLog.setRequestParam(param);
            operateLog.setResponseParam(returnParam);
            operateLog.setRequestMethod(methodName);
            operateLog.setOperateId(UserUtil.getOperatorId());
            operateLog.setOperateName(UserUtil.getOperatorFromSession().getUserName());
            SysOperateLogMqModel model = new SysOperateLogMqModel(operateLog);
            log.info("准备发送MQ消息,tag:{}", model.getTag());
            RocketMqSendUtil.sendMq(Collections.singletonList(model));
        });

    }
}
 
Example #21
Source File: SystemLogAspect.java    From Mykit with Apache License 2.0 5 votes vote down vote up
@AfterReturning("controllerAspect()")
public void afterReturn(JoinPoint joinPoint){
    System.out.println("=====执行controller后置返回通知=====");  
        if(logger.isInfoEnabled()){
            logger.info("afterReturn " + joinPoint);
        }
}
 
Example #22
Source File: WebLogAspect.java    From my-site with Apache License 2.0 5 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
    // 处理完请求,返回内容
    LOGGER.info("RESPONSE : " + ret);
    LOGGER.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    startTime.remove();//用完之后记得清除,不然可能导致内存泄露;
}
 
Example #23
Source File: ApiLogAspect.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 返回通知
 *
 * @param ret
 * @throws Throwable
 */
@AfterReturning(returning = "ret", pointcut = "log()")
public void doAfterReturning(Object ret) {
    //得到当前线程的log对象
    ApiLogger apiLogger = logThreadLocal.get();
    // 发布事件
    publisher.publishEvent(new SysLogEvent(apiLogger));
    //移除当前log实体
    logThreadLocal.remove();
}
 
Example #24
Source File: ApiLogAspect.java    From sophia_scaffolding with Apache License 2.0 5 votes vote down vote up
/**
 * 返回通知
 *
 * @param ret
 * @throws Throwable
 */
@AfterReturning(returning = "ret", pointcut = "log()")
public void doAfterReturning(Object ret) {
    //得到当前线程的log对象
    ApiLogger apiLogger = logThreadLocal.get();
    // 发布事件
    publisher.publishEvent(new SysLogEvent(apiLogger));
    //移除当前log实体
    logThreadLocal.remove();
}
 
Example #25
Source File: SysLogAspect.java    From hdw-dubbo with Apache License 2.0 5 votes vote down vote up
@AfterReturning(returning = "object", pointcut = "logPointCut()")
public void doAfterReturning(Object object) {
    if (object != null) {
        logger.info("response={}", JacksonUtil.toJson(object));
    } else {
        logger.info("response=");
    }

}
 
Example #26
Source File: TransferServiceAspect.java    From Hands-On-High-Performance-with-Spring-5 with MIT License 5 votes vote down vote up
@AfterReturning(pointcut = "transfer() and args(source, dest, amount)", returning = "isTransferSucessful")
public void afterTransferReturns(JoinPoint joinPoint, Account source, Account dest, Double amount,
		boolean isTransferSucessful) {
	if (isTransferSucessful) {
		LOGGER.info("Amount transferred successfully ");
		// find remaining balance of source account
	}
}
 
Example #27
Source File: WebLogAspect.java    From mall with Apache License 2.0 5 votes vote down vote up
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfterReturning(Object ret) throws Throwable {
    // 处理完请求,返回内容
    LOGGER.info("RESPONSE : " + ret);
    LOGGER.info("SPEND TIME : " + (System.currentTimeMillis() - startTime.get()));
    LOGGER.info("***************End API Request***************");
}
 
Example #28
Source File: ControllerLoggingAspect.java    From Spring with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
	log.info("Exiting Method: " + joinPoint.getSignature().getName());
	if (log.isDebugEnabled()) {
		try {
			log.debug("Response: " + mapper.writeValueAsString(result));
		}
		catch (JsonProcessingException e) {
			log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
			log.warn(e.getMessage(), e);
		}
	}
}
 
Example #29
Source File: ControllerLoggingAspect.java    From Spring with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
	log.info("Exiting Method: " + joinPoint.getSignature().getName());
	if (log.isDebugEnabled()) {
		try {
			log.debug("Response: " + mapper.writeValueAsString(result));
		}
		catch (JsonProcessingException e) {
			log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
			log.warn(e.getMessage(), e);
		}
	}
}
 
Example #30
Source File: ControllerLoggingAspect.java    From Spring with Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "restEndPoints()", returning = "result")
public void logAfterReturn(JoinPoint joinPoint, Object result) {
	log.info("Exiting Method: " + joinPoint.getSignature().getName());
	if (log.isDebugEnabled()) {
		try {
			log.debug("Response: " + mapper.writeValueAsString(result));
		}
		catch (JsonProcessingException e) {
			log.warn("An error occurred while attempting to write value as JSON: " + result.toString());
			log.warn(e.getMessage(), e);
		}
	}
}