Java Code Examples for org.aspectj.lang.annotation.AfterReturning

The following examples show how to use org.aspectj.lang.annotation.AfterReturning. 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: Jpom   Source File: WebAopLog.java    License: 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 Project: charging_pile_cloud   Source File: WebLogAcpect.java    License: 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 3
@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 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 5
Source Project: paascloud-master   Source File: BindingResultAop.java    License: 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 6
Source Project: Qualitis   Source File: DaoAspect.java    License: 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 7
Source Project: Qualitis   Source File: DaoAspect.java    License: 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 8
Source Project: Qualitis   Source File: DaoAspect.java    License: Apache License 2.0 5 votes vote down vote up
@AfterReturning(pointcut = "templateOutputMetaAspect()", returning = "object")
public void templateOutputMetaAspectAfter(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 9
Source Project: Qualitis   Source File: DaoAspect.java    License: 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 10
/**
 * 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 11
Source Project: mail-micro-service   Source File: MailSendLogAspect.java    License: 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 12
Source Project: ZTuoExchange_framework   Source File: AntiAttackAspect.java    License: 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 13
Source Project: scaffold-cloud   Source File: SysOperateLogAop.java    License: 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 14
Source Project: sophia_scaffolding   Source File: ApiLogAspect.java    License: 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 15
Source Project: sophia_scaffolding   Source File: ApiLogAspect.java    License: 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 16
Source Project: mall   Source File: WebLogAspect.java    License: 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 17
Source Project: Spring   Source File: ControllerLoggingAspect.java    License: 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 18
Source Project: Spring   Source File: ControllerLoggingAspect.java    License: 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 19
Source Project: Spring   Source File: ControllerLoggingAspect.java    License: 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 20
@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 21
Source Project: hdw-dubbo   Source File: SysLogAspect.java    License: 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 22
Source Project: my-site   Source File: WebLogAspect.java    License: 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 Project: Mykit   Source File: SystemLogAspect.java    License: 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 24
Source Project: Mykit   Source File: Interceptor.java    License: 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 25
Source Project: spring-cloud-gray   Source File: ResultfulOpRecordAspect.java    License: 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 26
Source Project: oauth2-server   Source File: WebRequestLogAspect.java    License: 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 27
/**
 * 使用@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 28
@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 29
Source Project: bird-java   Source File: OperateLogAspect.java    License: 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 30
Source Project: Spring-5.0-Cookbook   Source File: DetectNullsAspect.java    License: 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);
	 }
}