@Before("metodosDeServico()") public void logaNoComeco(JoinPoint joinPoint) { String methodName = joinPoint.getSignature().getName(); String typeName = joinPoint.getSignature().getDeclaringTypeName(); logger.info("Executando antes do metodo: " + methodName + " da classe: " + typeName); }
public void simpleBeforeAdvice(JoinPoint jp, int intValue) { System.out.println( "Выполняется: DeclaringTypeName=" + jp.getSignature().getDeclaringTypeName() + " Signature=" + jp.getSignature().getName()); if (intValue == 100) System.out.println("Абзац. Значение действительно=" + intValue); }
@After("persistenceExecution()") public void AfterMethodtrace(JoinPoint joinPoint) { String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); logger.info(preffix + " LEAVING " + target); preffix = preffix.substring(0, preffix.length() - append.length()); }
@Before("persistenceExecution()") public void beforeMethodtrace(JoinPoint joinPoint) { preffix += append; String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); logger.info(preffix + " ENTERING " + target); }
@Before("execution(* *.*(..))") public void logJoinPoint(JoinPoint joinPoint) { log.info("Join point kind : " + joinPoint.getKind()); log.info("Signature declaring type : " + joinPoint.getSignature().getDeclaringTypeName()); log.info("Signature name : " + joinPoint.getSignature().getName()); log.info("Arguments : " + Arrays.toString(joinPoint.getArgs())); log.info("Target class : " + joinPoint.getTarget().getClass().getName()); log.info("This class : " + joinPoint.getThis().getClass().getName()); }
@AfterThrowing(pointcut = "com.energysh.egame.aop.SystemArchitecture.webLayer()", throwing = "ex") public void doWebLog(JoinPoint point, Exception ex) { log.info( "web exception:[class:" + point.getSignature().getDeclaringTypeName() + ",method:" + point.getSignature().getName() + "] exception:", ex); }
@AfterThrowing(pointcut = "execution(* someBusinessMethod(..))", throwing = "ex") public void handleException(JoinPoint jp, RuntimeException ex) throws Throwable { System.out.println("Routine exception handling code here."); System.out.println("Let's see who has raised an exception!"); System.out.println("==================================="); System.out.println(jp.getSignature().getName()); System.out.println("==================================="); throw new BusinessException( messageSource.getMessage(jp.getSignature().getName(), null, Locale.getDefault())); }
@AfterReturning(value = "allOperation()||athenaServiceOperation()||spartanServiceOperation()") public void afterReturning(JoinPoint join) throws IOException { counterService.increment( "counter.HttpStatus." + httpStatusCode.name() + "." + join.getSignature().getDeclaringType().getSimpleName() + "." + join.getSignature().getName() + ".calls"); counterService.increment("counter.numberof.calls"); }
@Before(cut) public void logBefore(JoinPoint joinPoint) { System.out.println("--------- ICI ON LOG BEFORE ---------"); System.out.println("classe appelée : " + joinPoint.getTarget().getClass()); System.out.println("méthode appelée : " + joinPoint.getSignature().getName()); // System.out.println("paramètres de la méthode : " + joinPoint.getArgs()); }
@After("execution(* com.spring.aop.aspectj.CustomerBo.addCustomer(..))") public void logAfter(JoinPoint joinPoint) { System.out.println("logAfter() is running!"); System.out.println("hijacked : " + joinPoint.getSignature().getName()); System.out.println("******"); }
public void beforeExecute(JoinPoint thisJoinPoint) { String serviceNM = AuditInfoCollector.getClassNm(thisJoinPoint.getTarget(), HOPCONS.PKG_PREFIX) + "." + thisJoinPoint.getSignature().getName(); LOGGER.debug("Spring AOP ..... Touching " + HOPCONS.QUEUE_LOGGER_SEG + serviceNM); ReqNotes.setStatus(ReqNotes.STATUS_KEY.IS_AUDITED, ReqNotes.H_YES); if (isExcludedService(serviceNM)) { ReqNotes.setStatus(ReqNotes.STATUS_KEY.IS_EXCLUDED, ReqNotes.H_YES); return; } else { ReqNotes.setStatus(ReqNotes.STATUS_KEY.IS_EXCLUDED, ReqNotes.H_NO); } // Only record first including service into thread local if (ReqNotes.isInvokeEmpty()) { ReqNotes.ERRNotes.resetNotes(); ReqNotes.SQLNotes.resetNotes(); ReqNotes.setInvokeNotes(serviceNM, thisJoinPoint.hashCode(), System.currentTimeMillis()); ReqNotes.setStatus(ReqNotes.STATUS_KEY.IS_INCLUDE_AUDITED, ReqNotes.H_YES); LOGGER.debug("Spring AOP ..... Recording " + HOPCONS.QUEUE_LOGGER_SEG + serviceNM); } }
@AfterReturning( value = "@annotation(com.kcp.platform.common.log.annotation.Log)", returning = "returnVal") public void logAfterReturning(JoinPoint pjp, Object returnVal) throws Throwable { try { if (pjp.toLongString().equals(SqlContextHolder.getJoinPoint())) { MethodSignature joinPointObject = (MethodSignature) pjp.getSignature(); Method method = joinPointObject.getMethod(); MethodSysLogDefinition definition = parser.parseLogAnnotation(method); String logType = definition.getType(); String moduleName = definition.getModuleName(); String operateDesc = definition.getOperateDesc(); String operateContent = SqlContextHolder.getSql(); if (definition.isUseSpel()) { /** 对日志描述和日志备注加入SPEL支持 */ LogOperationContext context = getOperationContext(definition, method, pjp.getArgs(), pjp.getClass()); operateDesc = context.desc(); } Logger.getInstance().addSysLog(logType, operateContent, moduleName, operateDesc); SqlContextHolder.clear(); } } catch (Exception e) { logger.error("记录系统操作日志失败", e); } }
/** Test case where the current user has both the namespace and the appropriate permissions. */ @Test public void checkPermissionAssertNoExceptionWhenHasPermissions() throws Exception { // Mock a join point of the method call // mockMethod("foo"); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser .getNamespaceAuthorizations() .add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ))); SecurityContextHolder.getContext() .setAuthentication( new TestingAuthenticationToken( new SecurityUserWrapper( userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); } catch (AccessDeniedException e) { fail(); } }
@Test public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception { // Mock a join point of the method call // mockMethod("foo"); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"}); SecurityContextHolder.getContext() .setAuthentication(new TestingAuthenticationToken(null, null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals( "Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"", e.getMessage()); } }
@Test public void checkPermissionAssertErrorWhenAnnotationFieldRefersToNonString() throws Exception { // Mock a join point of the method call // mockMethod(1); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", Integer.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"aNumber"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); when(joinPoint.getArgs()).thenReturn(new Object[] {1}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); SecurityContextHolder.getContext() .setAuthentication( new TestingAuthenticationToken( new SecurityUserWrapper( userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(IllegalStateException.class, e.getClass()); assertEquals( "Object must be of type class java.lang.String or interface java.util.Collection. Actual object.class = class java.lang.Integer", e.getMessage()); } }
public void afterExecute(JoinPoint thisJoinPoint) { if (!ReqNotes.isInvokeEmpty()) { String sNM = AuditInfoCollector.getClassNm(thisJoinPoint.getTarget(), HOPCONS.PKG_PREFIX) + "." + thisJoinPoint.getSignature().getName(); long bf = ReqNotes.getInvokeNotes().getStartTime(); long af = System.currentTimeMillis(); // To avoid any children service call statistics if (isExcludedService(sNM)) { if (!ReqNotes.getStatus(ReqNotes.STATUS_KEY.IS_INCLUDE_AUDITED)) { ReqNotes.resetEXNotes(); } return; } if (!sNM.equals(ReqNotes.getInvokeNotes().getApiNM())) { return; } else { if (thisJoinPoint.hashCode() != ReqNotes.getJointHashCode()) { return; } try { InvokeSum.add(ReqNotes.getInvokeNotes().getApiNM(), af - bf); } catch (Exception e) { LOGGER.error("Can not set value into memory summary queue", e); } finally { ReqNotes.clearInvokeNotes(); ReqNotes.resetEXNotes(); } } } }
public List<String> getOwners(final JoinPoint joinPoint) { final List<String> owners = new ArrayList<>(); final MethodSignature signature = (MethodSignature) joinPoint.getSignature(); final Object[] parameterValues = joinPoint.getArgs(); final Class[] parameterTypes = signature.getParameterTypes(); final Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations(); for (int i = 0; i < parameterAnnotations.length; i++) { final OwnerParam paramAnnotation = getAnnotationByType(parameterAnnotations[i], OwnerParam.class); if (paramAnnotation != null) { if (paramAnnotation.getter().isEmpty()) { if (String.class.equals(parameterTypes[i])) { final String owner = (String) parameterValues[i]; owners.add(owner); } } else { final String owner = callGetter(parameterValues[i], paramAnnotation.getter(), String.class); owners.add(owner); } } } return owners; }
@Test public void checkPermissionAssertAccessDeniedWhenComplexCaseAndUserHasWrongPermission() throws Exception { // Mock a join point of the method call // mockMethod(request); JoinPoint joinPoint = mock(JoinPoint.class); MethodSignature methodSignature = mock(MethodSignature.class); Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod( "mockMethod", BusinessObjectDataNotificationRegistrationCreateRequest.class); when(methodSignature.getParameterNames()).thenReturn(new String[] {"request"}); when(methodSignature.getMethod()).thenReturn(method); when(joinPoint.getSignature()).thenReturn(methodSignature); BusinessObjectDataNotificationRegistrationCreateRequest request = new BusinessObjectDataNotificationRegistrationCreateRequest(); request.setBusinessObjectDataNotificationRegistrationKey( new NotificationRegistrationKey("ns1", null)); request.setBusinessObjectDataNotificationFilter( new BusinessObjectDataNotificationFilter("ns2", null, null, null, null, null, null, null)); request.setJobActions( Arrays.asList(new JobAction("ns3", null, null), new JobAction("ns4", null, null))); when(joinPoint.getArgs()).thenReturn(new Object[] {request}); String userId = "userId"; ApplicationUser applicationUser = new ApplicationUser(getClass()); applicationUser.setUserId(userId); applicationUser.setNamespaceAuthorizations(new HashSet<>()); applicationUser .getNamespaceAuthorizations() .add(new NamespaceAuthorization("ns1", Arrays.asList(NamespacePermissionEnum.WRITE))); applicationUser .getNamespaceAuthorizations() .add(new NamespaceAuthorization("ns2", Arrays.asList(NamespacePermissionEnum.READ))); applicationUser .getNamespaceAuthorizations() .add(new NamespaceAuthorization("ns3", Arrays.asList(NamespacePermissionEnum.EXECUTE))); // User does not have the expected EXECUTE permission on ns4 applicationUser .getNamespaceAuthorizations() .add(new NamespaceAuthorization("ns4", Arrays.asList(NamespacePermissionEnum.READ))); SecurityContextHolder.getContext() .setAuthentication( new TestingAuthenticationToken( new SecurityUserWrapper( userId, "", false, false, false, false, Arrays.asList(), applicationUser), null)); try { namespaceSecurityAdvice.checkPermission(joinPoint); fail(); } catch (Exception e) { assertEquals(AccessDeniedException.class, e.getClass()); assertEquals( String.format( "User \"%s\" does not have \"[EXECUTE]\" permission(s) to the namespace \"ns4\"", userId), e.getMessage()); } }
public void before(JoinPoint jp) { // メソッド開始時にWeavingするAdvice System.out.println("Hello Before! *** メソッドが呼ばれる前に出てくるよ!"); Signature sig = jp.getSignature(); System.out.println("-----> メソッド名を取得するよ:" + sig.getName()); Object[] o = jp.getArgs(); System.out.println("-----> 仮引数の値を取得するよ:" + o[0]); }
@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 = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause(), e); } else { log.error( "Exception in {}.{}() with cause = {}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName(), e.getCause()); } }
@Before("CalculatorPointcuts.loggingOperation()") public void logBefore(JoinPoint joinPoint) { log.info( "The method " + joinPoint.getSignature().getName() + "() begins with " + Arrays.toString(joinPoint.getArgs())); }
public void afterReturning(JoinPoint jp, Product product) { // メソッド呼出が例外の送出なしに終了した際に呼ばれるAdvice System.out.println("Hello AfterReturning! *** メソッドを呼んだ後に出てくるよ"); // System.out.println("-----> return value = " + ret); Signature sig = jp.getSignature(); System.out.println("-----> メソッド名を取得するよ:" + sig.getName()); Object[] o = jp.getArgs(); System.out.println("-----> 仮引数の値を取得するよ:" + o[0]); }
/** * 流程初始化 * * @param joinPoint * @throws Throwable */ @Before( value = "execution(public * com.wonders.dataExchange.service.DataExchangeService.flowStep*(..))") public void beforeServiceFlowStep(JoinPoint joinPoint) { initService(joinPoint); String stepCode = joinPoint.getSignature().getName(); executeCheckMethod(stepCode); }
@AfterThrowing(pointcut = "CalculatorPointcuts.loggingOperation()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, IllegalArgumentException e) { log.error( "Illegal argument " + Arrays.toString(joinPoint.getArgs()) + " in " + joinPoint.getSignature().getName() + "()"); }
public void enter(JoinPoint joinPoint) { String method = joinPoint.getSignature().toLongString(); Object[] arguments = joinPoint.getArgs(); Object target = joinPoint.getTarget(); LOG.debug( String.format( "Method '%1$s' entered with arguments %2$s on target %3$s", method, Arrays.asList(arguments), target)); }
@AfterThrowing( pointcut = "execution(* com.spring.aop.aspectj.CustomerBo.addCustomerThrowException(..))", throwing = "error") public void logAfterThrowing(JoinPoint joinPoint, Throwable error) { System.out.println("logAfterThrowing() is running!"); System.out.println("hijacked : " + joinPoint.getSignature().getName()); System.out.println("Exception : " + error); System.out.println("******"); }
@AfterReturning( pointcut = "execution(* com.spring.aop.aspectj.CustomerBo.addCustomerReturnValue(..))", returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("logAfterReturning() is running!"); System.out.println("hijacked : " + joinPoint.getSignature().getName()); System.out.println("Method returned value is : " + result); System.out.println("******"); }
// 此方法将作为后置通知 public void myAfterReturnAdvice(JoinPoint jionpoint) { // 获取被调用的类名 String targetClassName = jionpoint.getTarget().getClass().getName(); // 获取被调用的方法名 String targetMethodName = jionpoint.getSignature().getName(); // 日志格式字符串 String logInfoText = "后置通知:" + targetClassName + "类的" + targetMethodName + "方法开始执行"; // 将日志信息写入配置的文件中 logger.info(logInfoText); }
// 此方法将作为异常通知 public void myThrowingAdvice(JoinPoint jionpoint, Exception e) { // 获取被调用的类名 String targetClassName = jionpoint.getTarget().getClass().getName(); // 获取被调用的方法名 String targetMethodName = jionpoint.getSignature().getName(); // 日志格式字符串 String logInfoText = "异常通知:执行" + targetClassName + "类的" + targetMethodName + "方法时发生异常"; // 将日志信息写入配置的文件中 logger.info(logInfoText); }
public void before(JoinPoint point) { Object target = point.getTarget(); String method = point.getSignature().getName(); Class<?>[] classz = target.getClass().getInterfaces(); Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes(); try { Method m = classz[0].getMethod(method, parameterTypes); if (m != null && m.isAnnotationPresent(DataSource.class)) { DataSource data = m.getAnnotation(DataSource.class); DynamicDataSourceHolder.setDataSource(data.value()); if (log.isDebugEnabled()) { log.debug("DataSourceAspect:=======================" + data.value()); } } } catch (Exception e) { log.error(e.getMessage(), e); } }