Java Code Examples for org.aspectj.lang.JoinPoint#getArgs()
The following examples show how to use
org.aspectj.lang.JoinPoint#getArgs() .
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: LogUtil.java From pre with GNU General Public License v3.0 | 6 votes |
/*** * 获取操作信息 * @param point * @return */ public static String getControllerMethodDescription(JoinPoint point) throws Exception { // 获取连接点目标类名 String targetName = point.getTarget().getClass().getName(); // 获取连接点签名的方法名 String methodName = point.getSignature().getName(); //获取连接点参数 Object[] args = point.getArgs(); //根据连接点类的名字获取指定类 Class targetClass = Class.forName(targetName); //获取类里面的方法 Method[] methods = targetClass.getMethods(); String description = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == args.length) { description = method.getAnnotation(SysOperaLog.class).descrption(); break; } } } return description; }
Example 2
Source File: SpelParser.java From dynamic-data-source-demo with Apache License 2.0 | 5 votes |
public static String parse(String expression, JoinPoint point) { String[] params = ((MethodSignature) point.getSignature()).getParameterNames(); Object[] args = point.getArgs(); Map<String, Object> map = new HashMap<>(args.length); for (int i = 0; i < params.length; i++) { map.put(params[i], args[i]); } return parse(expression, String.class, map); }
Example 3
Source File: LoggingHandler.java From sakai with Educational Community License v2.0 | 5 votes |
@Before("repository() && allMethod()") public void logBefore(JoinPoint joinPoint) { log.debug("Entering in Method : " + joinPoint.getSignature().getName() + " at " + System.currentTimeMillis()); Object[] args = joinPoint.getArgs(); for (int argIndex = 0; argIndex < args.length; argIndex++) { log.debug(" " + argIndex + " = " + args[argIndex]); } }
Example 4
Source File: CommandExecutionInterceptor.java From eventapis with Apache License 2.0 | 5 votes |
private CommandRecord recordCommand(JoinPoint jp, CommandHandler commandHandler, Command command) throws ConcurrentEventException, EventStoreException { EventRepository eventRepository; CommandDto commandDto = null; CommandRecord commandRecord = new CommandRecord(); commandRecord.setEventName(commandHandler.getClass().getSimpleName()); for (int i = 0; i < jp.getArgs().length; i++) { Object arg = jp.getArgs()[i]; commandRecord.getParameters().put(i, arg); } // for (Object arg : jp.getArgs()) { // if (arg instanceof CommandDto) // commandDto = (CommandDto) arg; // } // if (commandDto == null) { // log.warn("Command" + jp.getTarget().getClass().getSimpleName() + " does not have CommandDto"); // return null; // } try { Field declaredField = commandHandler.getClass().getDeclaredField(command.eventRepository()); if (!declaredField.isAccessible()) declaredField.setAccessible(true); eventRepository = (EventRepository) declaredField.get(commandHandler); } catch (IllegalAccessException | NoSuchFieldException e) { log.error("Error while accessing EventRecorder(" + command.eventRepository() + ") of Command:" + commandHandler.getClass().getSimpleName() + " message: " + e.getMessage(), e); return null; } if (eventRepository != null) { eventRepository.getEventRecorder().recordEntityEvent(commandRecord, System.currentTimeMillis(), Optional.empty(), entityEvent -> new DefaultConcurrencyResolver()); } else log.error("Error while accessing EventRecorder(" + command.eventRepository() + " is null ) of Command:" + commandHandler.getClass().getSimpleName()); return commandRecord; }
Example 5
Source File: ServiceMonitor.java From springboot-seed with MIT License | 5 votes |
/** * Monitor whether exception is thrown in service layer. If exception * has been thrown, in order to detecting it conveniently, log the * situation where it happened. Then create a server internal error * exception and throw it out. */ @AfterThrowing(pointcut = "com.wind.monitor.ServiceMonitor.serviceLayer()", throwing = "e") public void monitorException(JoinPoint joinPoint, Throwable e) { // Log the situation where exception happened Object[] args = joinPoint.getArgs(); Signature signature = joinPoint.getSignature(); log.error("[" + signature.toShortString() + "]" + Arrays.toString(args) + "[" + e.toString() + "]"); // Throw a new server internal error exception throw new ServerInternalErrorException(e.getMessage(), e); }
Example 6
Source File: ControllerLogContextAspects.java From cloudbreak with Apache License 2.0 | 5 votes |
@Before("com.sequenceiq.cloudbreak.logger.ControllerLogContextAspects.interceptControllerMethodCalls()") public void buildLogContextForControllerCalls(JoinPoint joinPoint) { try { Object[] args = joinPoint.getArgs(); CodeSignature sig = (CodeSignature) joinPoint.getSignature(); String[] paramNames = sig.getParameterNames(); logContextService.buildMDCParams(joinPoint.getTarget(), paramNames, args); MDCBuilder.addRequestId(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString())); LOGGER.debug("A controller method has been intercepted: {} with params {}, {}, MDC logger context is built.", joinPoint.toShortString(), sig.getParameterNames(), AnonymizerUtil.anonymize(Arrays.toString(args))); } catch (Exception any) { LOGGER.warn("MDCContext build failed: ", any); } }
Example 7
Source File: DataScopeAspect.java From ruoyiplus with MIT License | 5 votes |
/** * 数据范围过滤 * @param joinPoint 切点 * @param user 用户 * @param alias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String alias) { StringBuilder sqlString = new StringBuilder(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", alias, role.getRoleId())); } } if (StringUtils.isNotBlank(sqlString.toString())) { BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0]; baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); } }
Example 8
Source File: ParamAspect.java From springBoot-study with Apache License 2.0 | 5 votes |
@Before("execution(public * com.pancm.web.*.*(..))") public void deBefore(JoinPoint joinPoint) throws Throwable { Object[] params= joinPoint.getArgs(); for (int i = 0; i < params.length; i++) { // ValidateHelper.asertPass(params[i]); } }
Example 9
Source File: ReqNoDrcAspect.java From springboot-cloud with MIT License | 5 votes |
public static BaseRequest getBaseRequest(JoinPoint joinPoint) throws Exception { BaseRequest returnRequest = null; Object[] arguments = joinPoint.getArgs(); if(arguments != null && arguments.length > 0){ returnRequest = (BaseRequest) arguments[0]; } return returnRequest; }
Example 10
Source File: LoginLogAspect.java From Shiro-Action with MIT License | 5 votes |
@After("loginLogPointCut()") public void recordLoginLog(JoinPoint joinPoint) { // 获取登陆参数 Object[] args = joinPoint.getArgs(); User user = (User) args[0]; Subject subject = SecurityUtils.getSubject(); String ip = IPUtils.getIpAddr(); loginLogService.addLog(user.getUsername(), subject.isAuthenticated(), ip); }
Example 11
Source File: LogContextAspects.java From cloudbreak with Apache License 2.0 | 5 votes |
@Before("com.sequenceiq.cloudbreak.cloud.logger.LogContextAspects.interceptCloudPlatformEventHandlersAcceptMethod()") public void buildLogContextForCloudPlatformEventHandler(JoinPoint joinPoint) { Event<CloudPlatformRequest<?>> event = (Event<CloudPlatformRequest<?>>) joinPoint.getArgs()[0]; CloudPlatformRequest<?> cloudPlatformRequest = event.getData(); CloudContext cloudContext = cloudPlatformRequest.getCloudContext(); buildMdcContext(cloudContext, event); LOGGER.debug("A CloudPlatformEventHandler's 'accept' method has been intercepted: {}, MDC logger context is built.", joinPoint.toShortString()); }
Example 12
Source File: ControllerLogContextAspects.java From cloudbreak with Apache License 2.0 | 5 votes |
@Before("com.sequenceiq.datalake.logger.ControllerLogContextAspects.interceptControllerMethodCalls()") public void buildLogContextForControllerCalls(JoinPoint joinPoint) { try { Object[] args = joinPoint.getArgs(); CodeSignature sig = (CodeSignature) joinPoint.getSignature(); String[] paramNames = sig.getParameterNames(); logContextService.buildMDCParams(joinPoint.getTarget(), paramNames, args); MDCBuilder.addRequestId(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString())); LOGGER.debug("A controller method has been intercepted: {} with params {}, {}, MDC logger context is built.", joinPoint.toShortString(), sig.getParameterNames(), AnonymizerUtil.anonymize(Arrays.toString(args))); } catch (Exception any) { LOGGER.warn("MDCContext build failed: ", any); } }
Example 13
Source File: ProceedTests.java From java-technology-stack with MIT License | 5 votes |
public void captureStringArgument(JoinPoint tjp, String arg) { if (!tjp.getArgs()[0].equals(arg)) { throw new IllegalStateException( "argument is '" + arg + "', " + "but args array has '" + tjp.getArgs()[0] + "'" ); } this.lastBeforeStringValue = arg; }
Example 14
Source File: SysLogAspect.java From pre with GNU General Public License v3.0 | 5 votes |
/*** * 拦截控制层的操作日志 * @param joinPoint * @return * @throws Throwable */ @Before(value = "sysLogAspect()") public void recordLog(JoinPoint joinPoint) throws Throwable { SysLog sysLog = new SysLog(); //将当前实体保存到threadLocal sysLogThreadLocal.set(sysLog); // 开始时间 long beginTime = Instant.now().toEpochMilli(); HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest(); PreSecurityUser securityUser = SecurityUtil.getUser(); sysLog.setUserName(securityUser.getUsername()); sysLog.setActionUrl(URLUtil.getPath(request.getRequestURI())); sysLog.setStartTime(LocalDateTime.now()); String ip = ServletUtil.getClientIP(request); sysLog.setIp(ip); sysLog.setLocation(IPUtil.getCityInfo(ip)); sysLog.setRequestMethod(request.getMethod()); String uaStr = request.getHeader("user-agent"); sysLog.setBrowser(UserAgentUtil.parse(uaStr).getBrowser().toString()); sysLog.setOs(UserAgentUtil.parse(uaStr).getOs().toString()); //访问目标方法的参数 可动态改变参数值 Object[] args = joinPoint.getArgs(); //获取执行的方法名 sysLog.setActionMethod(joinPoint.getSignature().getName()); // 类名 sysLog.setClassPath(joinPoint.getTarget().getClass().getName()); sysLog.setActionMethod(joinPoint.getSignature().getName()); sysLog.setFinishTime(LocalDateTime.now()); // 参数 sysLog.setParams(Arrays.toString(args)); sysLog.setDescription(LogUtil.getControllerMethodDescription(joinPoint)); long endTime = Instant.now().toEpochMilli(); sysLog.setConsumingTime(endTime - beginTime); }
Example 15
Source File: DataScopeAspect.java From supplierShop with MIT License | 4 votes |
/** * 数据范围过滤 * * @param joinPoint 切点 * @param user 用户 * @param alias 别名 */ public static void dataScopeFilter(JoinPoint joinPoint, SysUser user, String deptAlias, String userAlias) { StringBuilder sqlString = new StringBuilder(); for (SysRole role : user.getRoles()) { String dataScope = role.getDataScope(); if (DATA_SCOPE_ALL.equals(dataScope)) { sqlString = new StringBuilder(); break; } else if (DATA_SCOPE_CUSTOM.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias, role.getRoleId())); } else if (DATA_SCOPE_DEPT.equals(dataScope)) { sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId())); } else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope)) { sqlString.append(StringUtils.format( " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )", deptAlias, user.getDeptId(), user.getDeptId())); } else if (DATA_SCOPE_SELF.equals(dataScope)) { if (StringUtils.isNotBlank(userAlias)) { sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserId())); } else { // 数据权限为仅本人且没有userAlias别名不查询任何数据 sqlString.append(" OR 1=0 "); } } } if (StringUtils.isNotBlank(sqlString.toString())) { BaseEntity baseEntity = (BaseEntity) joinPoint.getArgs()[0]; baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")"); } }
Example 16
Source File: RedisCachePlugin.java From pybbs with GNU Affero General Public License v3.0 | 4 votes |
@After("co.yiiu.pybbs.hook.TopicServiceHook.update()") public void topicUpdate(JoinPoint joinPoint) { Topic topic = (Topic) joinPoint.getArgs()[0]; // 缓存到redis里 redisService.setString(String.format(RedisKeys.REDIS_TOPIC_KEY, topic.getId()), JsonUtil.objectToJson(topic)); }
Example 17
Source File: OptLogAspect.java From codeway_service with GNU General Public License v3.0 | 4 votes |
/** * 异常通知 用于拦截记录异常日志 * @param joinPoint 切点 * @author : LGG * @date :2019年5月4日12:41:30 */ @SuppressWarnings("all") @AfterThrowing(pointcut = "controllerAspect()", throwing="e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //读取session中的用户 /*SysUser user = (SysUser) session.getAttribute("user"); if(user==null){ user=new SysUser(); user.setUserName("非注册用户"); }*/ String ipAddr = HttpServletUtil.getIpAddr(request); try { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); int operationType = 0; String operationName = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { operationType = method.getAnnotation(OptLog.class).operationType(); operationName = method.getAnnotation(OptLog.class).operationName(); break; } } } /*========控制台输出=========*/ System.out.println("=====异常通知开始====="); System.out.println("异常代码:" + e.getClass().getName()); System.out.println("异常信息:" + e.getMessage()); System.out.println("异常方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")+"."+operationType); System.out.println("方法描述:" + operationName); System.out.println("请求人:" + "临时"); System.out.println("请求IP:" + ipAddr); //==========数据库日志========= com.codeway.pojo.base.OptLog log = new com.codeway.pojo.base.OptLog(); log.setClientIp(HttpServletUtil.getIpAddr(request)); log.setUserId("临时用户"); UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); log.setBrowser(userAgent.getBrowser().getName()); log.setOsInfo(userAgent.getOperatingSystem().getName()); log.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"); log.setExceptionDetail(e.getClass().getName() + ":--->" +e.getMessage()); String argumentParam = ""; for (Object argument : arguments) { if (!(argument instanceof ServletRequest)){ argumentParam += JsonUtil.toJsonString(argument); } } //log.setParams(argumentParam); /*SysLog log = new SysLog(); log.setDescription(operationName); log.setExceptionCode(e.getClass().getName()); log.setLogType(1); log.setExceptionDetail(e.getMessage()); log.setMethod((joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()")); log.setParams(params); log.setCreateBy(user.getUserName()); log.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); log.setRequestIp(ip);*/ //保存数据库 optLogServiceRpc.insertOptLog(log); System.out.println("=====异常通知结束====="); } catch (Exception ex) { //记录本地异常日志 LogBack.error("==异常通知异常=="); LogBack.error("异常信息:{}", ex.getMessage(),ex); } //==========记录本地异常日志========== LogBack.error("异常方法:{}异常代码:{}异常信息:{}", joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), e.getClass().getName(), e.getMessage()); }
Example 18
Source File: RedisCachePlugin.java From pybbs with GNU Affero General Public License v3.0 | 4 votes |
@After("co.yiiu.pybbs.hook.CommentServiceHook.delete()") public void commentDelete(JoinPoint joinPoint) { Comment comment = (Comment) joinPoint.getArgs()[0]; redisService.delString(String.format(RedisKeys.REDIS_COMMENTS_KEY, comment.getTopicId())); }
Example 19
Source File: OptLogAspect.java From codeway_service with GNU General Public License v3.0 | 4 votes |
/** * 前置通知 用于拦截Controller层记录用户的操作 * @param joinPoint 切点 * @author : LGG * @date :2019年5月4日12:41:30 */ @Before("controllerAspect()") @SuppressWarnings("all") public void doBefore(JoinPoint joinPoint) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); HttpSession session = request.getSession(); //读取token /*SysUser user = (SysUser) session.getAttribute("user"); if(user==null){ user=new SysUser(); user.setUserName("非注册用户"); }*/ //请求的IP final String token = request.getHeader(HttpHeaders.AUTHORIZATION); if (token == null) { LogBack.error("token为空,结束AOP前置通知"); return; } Map<String, String> user = JWTAuthentication.parseJwtToClaims(JWTAuthentication.getFullAuthorization(token)); String ipAddr = HttpServletUtil.getIpAddr(request); try { String targetName = joinPoint.getTarget().getClass().getName(); String methodName = joinPoint.getSignature().getName(); Object[] arguments = joinPoint.getArgs(); Class targetClass = Class.forName(targetName); Method[] methods = targetClass.getMethods(); Integer operationType = 0; String operationName = ""; for (Method method : methods) { if (method.getName().equals(methodName)) { Class[] clazzs = method.getParameterTypes(); if (clazzs.length == arguments.length) { operationType = method.getAnnotation(OptLog.class).operationType(); operationName = method.getAnnotation(OptLog.class).operationName(); break; } } } //*========数据库日志=========*// com.codeway.pojo.base.OptLog log = new com.codeway.pojo.base.OptLog(); log.setClientIp(HttpServletUtil.getIpAddr(request)); log.setUserId(user.get("id")); UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent")); log.setBrowser(userAgent.getBrowser().getName()); log.setType(operationType); log.setMethod(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"); log.setOsInfo(userAgent.getOperatingSystem().getName()); String argumentParam = ""; for (Object argument : arguments) { if (!(argument instanceof ServletRequest)) { argumentParam += JsonUtil.toJsonString(argument); } } //log.setParams(argumentParam); optLogServiceRpc.insertOptLog(log); LogBack.info("=====controller前置通知结束====="); } catch (Exception e) { //记录本地异常日志 LogBack.error("==前置通知异常=="); LogBack.error("异常信息:{}", e.getMessage(),e); } }
Example 20
Source File: WebLogAcpect.java From charging_pile_cloud with MIT License | 4 votes |
/** * 前置通知:在连接点之前执行的通知 * * @param joinPoint * @throws Throwable */ @Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); // 接收到请求,记录请求内容 Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); Object params[] = joinPoint.getArgs(); //自定义注解的方法操作别名 LogMenthodName logMenthodName = method.getAnnotation(LogMenthodName.class); //判断方法是否存在这个注解 if (method.isAnnotationPresent(LogMenthodName.class)) { logAdminAgent = new LogAdminAgent(); logAdminAgent.setRequestUrl(request.getRequestURL().toString()); logAdminAgent.setRequestWay(request.getMethod()); logAdminAgent.setCreateTime(DateUtil.getCurrentDateTime()); logAdminAgent.setIp(request.getRemoteAddr()); logAdminAgent.setMethodUrl(signature.getDeclaringTypeName() + "." + signature.getName()); logAdminAgent.setMethodName(logMenthodName.name()); if (params.length == 0) { logAdminAgent.setRequestParam("无参数"); } else { logAdminAgent.setRequestParam(Arrays.toString(params)); } } else { //设置日期格式 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 记录下请求内容 logger.info("------------------------------------------------------------------------------------------------"); logger.info("请求地址: " + request.getRequestURL().toString()); logger.info("请求方式: " + request.getMethod()); logger.info("请求时间: " + df.format(new Date())); logger.info("IP : " + request.getRemoteAddr()); logger.info("方法地址 : " + signature.getDeclaringTypeName() + "." + signature.getName()); if (logMenthodName == null) { logger.info("方法别名 : 未知"); } else { logger.info("方法别名 : " + logMenthodName.name()); } if (params.length == 0) { logger.info("请求参数 : 无参"); } else { logger.info("请求参数 : " + Arrays.toString(params)); } } }