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(); } } } }
/** * Unwraps a join point that may be nested due to layered proxies. * * @param point Join point to unwrap. * @return Innermost join point; if not nested, simply returns the argument. */ public static JoinPoint unWrapJoinPoint(final JoinPoint point) { JoinPoint naked = point; while (naked.getArgs().length > 0 && naked.getArgs()[0] instanceof JoinPoint) { naked = (JoinPoint) naked.getArgs()[0]; } return naked; }
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); } }
@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()); }
@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()); } }
@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()); } }
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; }
@AfterReturning( pointcut = "execution(public String at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.createNewCloudObject(..))", returning = "ret") public void matchObjectCreated(JoinPoint jp, String ret) throws JCloudScaleException { try { ObjectCreatedEvent event = new ObjectCreatedEvent(); initializeBaseEventProperties(event); UUID objectId = UUID.fromString(ret); event.setObjectId(objectId); JCloudScaleServer server = (JCloudScaleServer) jp.getThis(); // XXX AbstractJCloudScaleServerRunner // UUID serverId = JCloudScaleServerRunner.getInstance().getId(); UUID serverId = AbstractJCloudScaleServerRunner.getInstance().getId(); event.setHostId(serverId); ClassLoader cl = server.getCloudObjectClassLoader(objectId); Class<?> theClazz = Class.forName((String) (jp.getArgs()[0]), true, cl); event.setObjectType(theClazz); getMqHelper().sendEvent(event); log.finer("Sent object created for object " + objectId.toString()); } catch (Exception e) { e.printStackTrace(); log.severe("Error while triggering ObjectCreatedEvent: " + e.getMessage()); } }
@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()); } }
@Before("CalculatorPointcuts.loggingOperation()") public void logBefore(JoinPoint joinPoint) { log.info( "The method " + joinPoint.getSignature().getName() + "() begins with " + Arrays.toString(joinPoint.getArgs())); }
@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); }
/** * 变量初始化 * * @param joinPoint */ private void initService(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); DataExchangeService target = (DataExchangeService) joinPoint.getTarget(); MainParamVo params = (MainParamVo) args[0]; // resultInfo = params.resultInfo; target.init(params); checkService.init(params); }
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]); }
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()); }
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)); }
@Before("persistenceExecution()") public void beforeMethodtrace(JoinPoint joinPoint) { preffix += append; String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName(); logger.info(preffix + " ENTERING " + target); }
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]); }
@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 myAfterReturnAdvice(JoinPoint jionpoint) { // 获取被调用的类名 String targetClassName = jionpoint.getTarget().getClass().getName(); // 获取被调用的方法名 String targetMethodName = jionpoint.getSignature().getName(); // 日志格式字符串 String logInfoText = "后置通知:" + targetClassName + "类的" + targetMethodName + "方法开始执行"; // 将日志信息写入配置的文件中 logger.info(logInfoText); }
@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); }
/** * Calculate its target. * * @param point Proceeding point * @return The target */ private static Object targetize(final JoinPoint point) { final Object tgt; final Method method = MethodSignature.class.cast(point.getSignature()).getMethod(); if (Modifier.isStatic(method.getModifiers())) { tgt = method.getDeclaringClass(); } else { tgt = point.getTarget(); } return tgt; }
// 此方法将作为异常通知 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); }
@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())); }
@After("execution(* getAbrSummary(*))") public void logAfter(JoinPoint joinPoint) { logger = Logger.getLogger( "" + joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()); logger.info("reterived successfully."); logger.info("***************************************"); }
/** * 判断JoinPoint的方法是否注册过,注册过就返回注册的字符串,否则返回NULL * * @param jp * @return * @author 朱启亮 * @date 2008-1-31 */ public LogMethod LogMethodText(JoinPoint jp) { LogMethod tag = null; Class logObjectClazz = jp.getTarget().getClass(); try { Method method = logObjectClazz.getMethod(jp.getSignature().getName()); tag = method.getAnnotation(LogMethod.class); } catch (Exception e) { } return tag; }
@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"); }
@AfterReturning(value = cut, returning = "result") public void logAfterReturning(JoinPoint joinPoint, Object result) { System.out.println("--------- ICI ON LOG AFTER RETURNING ---------"); 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()); try { System.out.println("returning : " + result.toString()); } catch (NullPointerException e) { e.printStackTrace(); } }