@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); }
private String createKey(JoinPoint jp) { Object[] args = jp.getArgs(); if (args.length <= 0) { throw new IllegalArgumentException(RATE_LIMIT_PRECONDITION_FAIL); } for (Object arg : args) { if (arg instanceof HttpServletRequest) { HttpServletRequest request = (HttpServletRequest) arg; String ipAddress = request.getHeader("X-Forwarded-For"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } return ipAddress; } } throw new IllegalArgumentException(RATE_LIMIT_PRECONDITION_FAIL); }
private static String renderParams(JoinPoint joinPoint, String[] params, String[] includeParamNames, String[] excludeParamNames, boolean inputCollectionAware) { Set<String> includeSet = prepareNameSet(includeParamNames); Set<String> excludeSet = prepareNameSet(excludeParamNames); List<String> requestList = new ArrayList<>(); Map<String, Object> paramMap = joinPointToParamMap(joinPoint, params); if (!includeSet.isEmpty()) { includeSet .stream().filter(paramMap::containsKey) .forEach(key -> requestList.add(buildParam(key, paramMap.get(key), inputCollectionAware))); } else if (!excludeSet.isEmpty()) { paramMap.forEach((key, value) -> { if (!excludeSet.contains(key)) { requestList.add(buildParam(key, value, inputCollectionAware)); } }); } else { paramMap.forEach((key, value) -> requestList.add(buildParam(key, value, inputCollectionAware))); } return StringUtils.join(requestList, ','); }
/** * @param data * @throws ClassNotFoundException * @throws HttpMessageNotWritableException * @throws IOException */ @AfterReturning(pointcut = "point()", returning = "data") public void after(JoinPoint jp, Object data) throws Exception { MethodInvocationProceedingJoinPoint joinPoint = (MethodInvocationProceedingJoinPoint) jp; Class<?> clazz = joinPoint.getSignature().getDeclaringType(); if (AnnotationUtils.findAnnotation(clazz, FeignClient.class) == null) { log.debug("未找到feign 客户端"); return; } CustomSecurityContext securityContext = SecurityContextHystrixRequestVariable.getInstance().get(); ErrorResult errorResult = null; if (securityContext != null && (errorResult = securityContext.getErrorResult()) != null) { if (errorResult.getHttpStatus() != HttpStatus.OK.value()) { Class<?> exceptionClass = Class.forName(errorResult.getException()); Constructor<?> constructor = exceptionClass.getConstructor(new Class[]{String.class, String.class}); throw (CustomException) constructor .newInstance(new Object[]{errorResult.getMessage(), errorResult.getCode()}); } } SecurityContextHystrixRequestVariable.getInstance().remove(); }
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { startTime.set(System.currentTimeMillis()); // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 LOGGER.info("**************Start API Request**************"); LOGGER.info("URL : " + request.getRequestURI().toString()); LOGGER.info("HTTP_METHOD : " + request.getMethod()); LOGGER.info("IP : " + request.getRemoteAddr()); LOGGER.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); LOGGER.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); }
/** * Advice that logs methods throwing exceptions. */ @AfterThrowing(pointcut = "loggingPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles("dev")) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL", e.getMessage(), e ); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null ? e.getCause() : "NULL" ); } }
/** * 配置前置通知,使用在方法aspect()上注册的切入点 */ @Before("aspect()") public void before(JoinPoint point) { String className = point.getTarget().getClass().getName(); String method = point.getSignature().getName(); logger.info(className + "." + method + "(" + StringUtils.join(point.getArgs(), ",") + ")"); try { L: for (String key : ChooseDataSource.METHODTYPE.keySet()) { for (String type : ChooseDataSource.METHODTYPE.get(key)) { if (method.startsWith(type)) { logger.info(key); HandleDataSource.putDataSource(key); break L; } } } } catch (Exception e) { logger.error(e); HandleDataSource.putDataSource("write"); } }
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws ParamException, JsonProcessingException { startTime.set(System.currentTimeMillis()); // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); if (joinPoint.getArgs().length == 2 ) { logger.info("ARGS : " + JsonUtil.toJson(joinPoint.getArgs()[0])); } }
/** * @param joinPoint */ @AfterReturning("logAnnoAspect()") public void afterReturn(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); LogDelete logDelete = method.getAnnotation(LogDelete.class); if (null != logDelete) { BaseEntity entity = (BaseEntity) joinPoint.getArgs()[0]; Log log = new Log(); log.setUserId(((User) SecurityUtils.getSubject().getSession().getAttribute("curUser")).getId()); log.setAction(Constants.LOG_ACTION_DELETE + logDelete.resource()); log.setResource(entity.getLogResource()); log.setResourceId(entity.getId()); logService.insert(log); } }
@Test public void verifyResolverSecurityContext() throws Exception { final UserDetails ud = mock(UserDetails.class); when(ud.getUsername()).thenReturn("pid"); final Authentication authn = mock(Authentication.class); when(authn.getPrincipal()).thenReturn(ud); final SecurityContext securityContext = mock(SecurityContext.class); when(securityContext.getAuthentication()).thenReturn(authn); SecurityContextHolder.setContext(securityContext); final TicketOrCredentialPrincipalResolver res = new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService()); final JoinPoint jp = mock(JoinPoint.class); when(jp.getArgs()).thenReturn(new Object[]{ud}); final String result = res.resolveFrom(jp, null); assertNotNull(result); assertEquals(result, ud.getUsername()); }
@Before("execution(* cn.org.once.cstack.ServerService.updateType(..))") public void beforeServer(JoinPoint joinPoint) throws MonitorException, ServiceException { Server server = (Server) joinPoint.getArgs()[0]; User user = getAuthentificatedUser(); Message message = null; // String applicationName = server.getApplication().getName(); String applicationDisplayName = server.getApplication().getDisplayName(); switch (joinPoint.getSignature().getName().toUpperCase()) { case updateType: message = MessageUtils.writeBeforeApplicationMessage(user, applicationDisplayName, updateType); break; } logger.info(message.toString()); messageService.create(message); }
public static RestResp printRestResult(final JoinPoint joinPoint, final Object res, final boolean printBody) { if (res == null) { return new RestResp("OK", "null", printBody); } Class<?> respClass = res.getClass(); String status; Object bodyToPrint; if (ResponseEntity.class.isAssignableFrom(respClass)) { ResponseEntity<?> respEn = ResponseEntity.class.cast(res); status = String.valueOf(respEn.getStatusCode()); Object body = respEn.getBody(); bodyToPrint = LogObjectPrinter.printResult(joinPoint, body, printBody); } else { status = "OK"; bodyToPrint = LogObjectPrinter.printResult(joinPoint, res, printBody); } return new RestResp(status, bodyToPrint, printBody); }
@Test public void verifyResolverServiceTicket() throws Exception { final Credential c = CoreAuthenticationTestUtils.getCredentialsWithSameUsernameAndPassword(); final AuthenticationResult ctx = CoreAuthenticationTestUtils.getAuthenticationResult(getAuthenticationSystemSupport(), c); final TicketGrantingTicket ticketId = getCentralAuthenticationService() .createTicketGrantingTicket(ctx); final ServiceTicket st = getCentralAuthenticationService().grantServiceTicket(ticketId.getId(), CoreAuthenticationTestUtils.getService(), ctx); final TicketOrCredentialPrincipalResolver res = new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService()); final JoinPoint jp = mock(JoinPoint.class); when(jp.getArgs()).thenReturn(new Object[] {st.getId()}); final String result = res.resolveFrom(jp, null); assertNotNull(result); assertEquals(result, c.getId()); }
@AfterReturning(pointcut = "empController() && anyMethod() && args(request)", returning = "result") public void handleAfterMethodAllEmp(JoinPoint joinPoint, Object result, HttpServletRequest request) { int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature()) .getMethod()).getAnnotation(RequestMapping.class).name()); ResponseEntity<List<Employee>> list = (ResponseEntity<List<Employee>>) result; for (Employee e: list.getBody()) { AuditInfo auditRecord = new AuditInfo(null, e.getEmpID(), request.getRemoteAddr(), "Get all emp", action); auditService.createRecord(auditRecord); } }
@Before("apiPointcut()") public void before(JoinPoint joinPoint) { Object obj[] = joinPoint.getArgs(); if (obj.length > 0) { APIRequest request = (APIRequest) obj[0]; Set set = request.getParams().entrySet(); Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]); for (Map.Entry entry : entries) { logger.info("[Params] " + entry.getKey() + ":" + entry.getValue()); } } else { logger.info("[Params] null"); } }
@AfterReturning(pointcut = "empController() && anyMethod() && args(empId, request)", returning = "result", argNames = "joinPoint,result,empId,request") public void handleAfterMethodWithEmpIdRequestParams(JoinPoint joinPoint, Object result, Integer empId, HttpServletRequest request) { int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature()) .getMethod()).getAnnotation(RequestMapping.class).name()); AuditInfo auditRecord = new AuditInfo(null, empId, request.getRemoteAddr(), "Id: "+empId, action); auditService.createRecord(auditRecord); }
@AfterThrowing(pointcut = "logPointcut()", throwing = "ex") public void exceptionLog(JoinPoint point, Exception ex) { //详细错误信息 String errorMsg = ""; StackTraceElement[] trace = ex.getStackTrace(); for (StackTraceElement s : trace) { errorMsg += "\tat " + s + "\r\n"; } //写入异常日志 writeLog(errorMsg, point, ex); }
/** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "loggingPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } }
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // Get request ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // Save request content logger.info("URL : " + request.getRequestURL().toString()); logger.info("HTTP_METHOD : " + request.getMethod()); logger.info("IP : " + request.getRemoteAddr()); logger.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName()); logger.info("ARGS : " + Arrays.toString(joinPoint.getArgs())); }
private void execute(JoinPoint joinPoint) { CodeSignature codeSignature = (CodeSignature) joinPoint.getSignature(); Class<?> cls = codeSignature.getDeclaringType(); String methodName = codeSignature.getName(); Log.v(getTag(cls), "\u21E2 " + methodName); }
@Before("weblog()") public void doBefore(JoinPoint joinpoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 logger.info("Started " + request.getMethod() + " " + request.getRequestURL().toString() + " for " + request.getRemoteAddr() + " at " + LocalDateTime.now()); logger.info("Processing by " + joinpoint.getSignature().getDeclaringTypeName() + "." + joinpoint.getSignature().getName() + " " + request.getContentType()); logger.info("Parameters: " + mapper.writeValueAsString(request.getParameterMap())); }
@AfterThrowing( pointcut = "allPublicControllerMethodsPointcut() && " + "methodLoggingNotDisabledPointcut() && " + "methodOrClassLoggingEnabledPointcut()", throwing = "t") public void onException(@Nonnull JoinPoint joinPoint, @Nonnull Throwable t) { String methodName = joinPoint.getSignature().getName() + "()"; LOG.info(methodName + " threw exception: [" + t + "]"); }
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; }
@Before("webLog()") public void doBefore(JoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); // 记录下请求内容 LOGGER.info("URL : " + request.getRequestURL().toString() + ",IP : " + request.getRemoteAddr() + ",CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName() + ",ARGS : " + Arrays.toString(joinPoint.getArgs())); }
/** * 获取注解中对方法的描述信息 用于Service层注解 * @param joinPoint 切点 * @return 方法描述 * @throws Exception */ public static String getServiceMethodDescription(JoinPoint joinPoint) throws Exception{ //获取目标类名 String targetName = joinPoint.getTarget().getClass().getName(); //获取方法名 String methodName = joinPoint.getSignature().getName(); //获取相关参数 Object[] arguments = joinPoint.getArgs(); //生成类对象 Class targetClass = Class.forName(targetName); //获取该类中的方法 Method[] methods = targetClass.getMethods(); String description = ""; for(Method method : methods) { if(!method.getName().equals(methodName)) { continue; } Class[] clazzs = method.getParameterTypes(); if(clazzs.length != arguments.length) {//比较方法中参数个数与从切点中获取的参数个数是否相同,原因是方法可以重载哦 continue; } description = method.getAnnotation(SystemServiceLog.class).description(); } return description; }
/** * 前置通知 */ @Before("log()") public void doBeforeController(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Action action = method.getAnnotation(Action.class); System.out.println("action名称 " + action.value()); // ⑤ }
@AfterThrowing(pointcut = "deptController() && anyMethod() && args(depId,..,request)", throwing = "e") public void handleAfterMethodWithDepIdRequestParams(JoinPoint joinPoint, Integer depId, HttpServletRequest request, Throwable e) { int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature()) .getMethod()).getAnnotation(RequestMapping.class).name()); AuditInfo auditRecord = new AuditInfo(depId, null, request.getRemoteAddr(), "Id: "+depId, action, e.getMessage() ); auditService.createRecord(auditRecord); }
/** * 获取注解中对方法的描述信息 用于Controller层注解 * * @param joinPoint 切点 * @return discription */ public static String getControllerMethodDescriptionInfo(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SystemControllerLog controllerLog = method .getAnnotation(SystemControllerLog.class); String discription = controllerLog.description(); return discription; }
/** * Binds to RateLimit annotation * * @param joinPoint the join point * @param limit the limit annotation data * @throws RequestLimitExceeded hard error if limit is exceeded */ @Before("@annotation(limit)") public void rateLimt(final JoinPoint joinPoint, final RateLimit limit) throws RequestLimitExceeded { final String key = getOrCreate(joinPoint, limit); handleHardRateLimiting(key, limit); handleSoftRateLimiting(key, joinPoint, limit); }
@AfterThrowing(pointcut = "empController() && anyMethod() && args(start, num, request) )", throwing = "e") public void handleAfterMethodPartEmpThrow(JoinPoint joinPoint, Throwable e, int start, int num, HttpServletRequest request) { int action = Integer.parseInt((((MethodSignature)joinPoint.getSignature()) .getMethod()).getAnnotation(RequestMapping.class).name()); AuditInfo auditRecord = new AuditInfo(null,null, request.getRemoteAddr(), "Start:num - " +start +":"+num, action, e.getMessage()); auditService.createRecord(auditRecord); }
@AfterThrowing(pointcut = "loggingPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(Constants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = {} and exception {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause()); } }
/** * Advice that logs methods throwing exceptions. */ @AfterThrowing(pointcut = "loggingPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } }
@AfterReturning(pointcut = "pointcut()", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("******"); System.out.println("logAfterReturning() is running!"); System.out.println("hijacked : " + joinPoint.getSignature().getName()); System.out.println("Method returned value is : " + result); System.out.println("******"); }
@Before("logAnnoAspect()") public void before(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); LogModify log = method.getAnnotation(LogModify.class); if (null != log) { aspectEntity = (BaseEntity) joinPoint.getArgs()[0]; if (null == aspectEntity.getId()) { ACTION = Constants.LOG_ACTION_CREATE; } else { ACTION = Constants.LOG_ACTION_MODIFY; } } }
@After("execution(org.junit.runner.notification.RunNotifier.new())") public void addListener(final JoinPoint point) { final RunNotifier notifier = (RunNotifier) point.getThis(); notifier.removeListener(allure); notifier.addListener(allure); }
@Before("execution(* twitter.nlp.service.ISentiment.calculateSentiment(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("logBefore() is running!"); System.out.println("the method is : " + joinPoint.getSignature().getName()); System.out.println("******"); }
private boolean maybeBindJoinPoint(Class<?> candidateParameterType) { if (candidateParameterType.equals(JoinPoint.class)) { this.joinPointArgumentIndex = 0; return true; } else { return false; } }
/** * Advice that logs methods throwing exceptions. * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "applicationPackagePointcut() && springBeanPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) { if (env.acceptsProfiles(JHipsterConstants.SPRING_PROFILE_DEVELOPMENT)) { log.error("Exception in {}.{}() with cause = \'{}\' and exception = \'{}\'", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL", e.getMessage(), e); } else { log.error("Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause() != null? e.getCause() : "NULL"); } }
/** * 前置通知 , 接收请求并记录请求内容 */ @Before("webLog()") public void invokeBefore(JoinPoint point) { logtime.set(System.currentTimeMillis()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); LOGGER.info("URL : " + request.getRequestURL().toString()); LOGGER.info("HTTP_METHOD : " + request.getMethod()); LOGGER.info("IP : " + request.getRemoteAddr()); LOGGER.info("CLASS_METHOD : " + getMethodName(point)); LOGGER.info("ARGS : " + Arrays.toString(point.getArgs())); }
@Test public void verifyResolverCredential() { final TicketOrCredentialPrincipalResolver res = new TicketOrCredentialPrincipalResolver(getCentralAuthenticationService()); final JoinPoint jp = mock(JoinPoint.class); final Credential c = TestUtils.getCredentialsWithSameUsernameAndPassword(); when(jp.getArgs()).thenReturn(new Object[] {c}); final String result = res.resolveFrom(jp, null); assertNotNull(result); assertEquals(result, c.toString()); }