@Around("methodAnnotated() || constructorAnnotated()")//在连接点进行方法替换 public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); LogUtils.showLog("TimeLog getDeclaringClass", methodSignature.getMethod().getDeclaringClass().getCanonicalName()); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); long startTime = System.nanoTime(); Object result = joinPoint.proceed();//执行原方法 StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(methodName + ":"); for (Object obj : joinPoint.getArgs()) { if (obj instanceof String) keyBuilder.append((String) obj); else if (obj instanceof Class) keyBuilder.append(((Class) obj).getSimpleName()); } String key = keyBuilder.toString(); LogUtils.showLog("TimeLog", (className + "." + key + joinPoint.getArgs().toString() + " --->:" + "[" + (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) + "ms]"));// 打印时间差 return result; }
@Around("methodAnnotated()")//在连接点进行方法替换 public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String methodName = methodSignature.getName(); MemoryCacheManager mMemoryCacheManager = MemoryCacheManager.getInstance(); StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(methodName); for (Object obj : joinPoint.getArgs()) { if (obj instanceof String) keyBuilder.append((String) obj); else if (obj instanceof Class) keyBuilder.append(((Class) obj).getSimpleName()); } String key = keyBuilder.toString(); Object result = mMemoryCacheManager.get(key);//key规则 : 方法名+参数1+参数2+... LogUtils.showLog("MemoryCache", "key:" + key + "--->" + (result != null ? "not null" : "null")); if (result != null) return result;//缓存已有,直接返回 result = joinPoint.proceed();//执行原方法 if (result instanceof List && result != null && ((List) result).size() > 0 //列表不为空 || result instanceof String && !TextUtils.isEmpty((String) result)//字符不为空 || result instanceof Object && result != null)//对象不为空 mMemoryCacheManager.add(key, result);//存入缓存 LogUtils.showLog("MemoryCache", "key:" + key + "--->" + "save"); return result; }
private boolean needCheck(ProceedingJoinPoint point) { if (! MethodSignature.class.isAssignableFrom(point.getSignature().getClass())) { return false; } MethodSignature methodSignature = (MethodSignature) point.getSignature(); Method method = methodSignature.getMethod(); if (method.isAnnotationPresent(LoginCheck.class)) { return true; } Class glass = method.getDeclaringClass(); if (! glass.isAnnotationPresent(LoginCheck.class)) { return false; } LoginCheck loginCheck = (LoginCheck) glass.getAnnotation(LoginCheck.class); String[] methods = loginCheck.exclusions(); return ! ArrayUtils.contains(methods, method.getName()); }
@Around("interceptDao()") public Object intercept(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; try { Class clazz = MethodSignature.class.cast(joinPoint.getSignature()).getDeclaringType(); DynamicDS targetDataSource = AnnotationUtils.findAnnotation(clazz, DynamicDS.class); if (targetDataSource != null) { DataSourceContextHolder.setTargetDataSource(DataSourceEnum.valueOf(targetDataSource.value())); } else { DataSourceContextHolder.resetDefaultDataSource(); } result = joinPoint.proceed(); return result; } catch (Throwable ex) { throw new RuntimeException(ex); } }
@Around("anyPublicJdbcMethod()") public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { if (logger.isTraceEnabled()) { String enterMessage = MessageFormat.format("Entering method {0}({1})", MethodSignature.class.cast(proceedingJoinPoint.getSignature()).getMethod().getName(), proceedingJoinPoint.getArgs()); logger.trace(enterMessage); } Object response = proceedingJoinPoint.proceed(); if (logger.isTraceEnabled()) { String exitMessage = MessageFormat.format("Exiting method {0}({1}) : {2}", MethodSignature.class.cast(proceedingJoinPoint.getSignature()).getMethod().getName(), proceedingJoinPoint.getArgs(), response); logger.trace(exitMessage); } return response; }
@Around("execution(* org.assertj.core.api.AbstractAssert+.*(..)) " + "|| execution(* org.assertj.core.api.Assertions.assertThat(..))") public Object step(final ProceedingJoinPoint joinPoint) throws Throwable { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); final String name = joinPoint.getArgs().length > 0 ? String.format("%s \'%s\'", methodSignature.getName(), arrayToString(joinPoint.getArgs())) : methodSignature.getName(); final String uuid = UUID.randomUUID().toString(); final StepResult result = new StepResult() .withName(name); getLifecycle().startStep(uuid, result); try { final Object proceed = joinPoint.proceed(); getLifecycle().updateStep(uuid, s -> s.withStatus(Status.PASSED)); return proceed; } catch (Throwable e) { getLifecycle().updateStep(uuid, s -> s .withStatus(getStatus(e).orElse(Status.BROKEN)) .withStatusDetails(getStatusDetails(e).orElse(null))); throw e; } finally { getLifecycle().stopStep(uuid); } }
/** * @param method * @return <code>true</code> if the given method has the same signature as * the currently aspectJ extension-overridden method */ static boolean isLocalProceeder(Method method) { if (!ajLocalProceedingJoinPoints.get().isEmpty()) { ProceedingContext proceedingCotext = ajLocalProceedingJoinPoints.get().peek(); MethodSignature ms = (MethodSignature) proceedingCotext.proceedingJoinPoint.getSignature(); Method jpMethod = ms.getMethod(); return jpMethod.getName().endsWith(method.getName()) && Arrays.equals(jpMethod.getParameterTypes(), method.getParameterTypes()); } else { return false; } }
@Around("execution(org.springframework.web.servlet.ModelAndView org.gra4j.dataMigration.controller..*.*(..)) " + " and @annotation(org.springframework.web.bind.annotation.RequestMapping)") public Object before(ProceedingJoinPoint pjp) throws Throwable { // 从切点上获取目标方法 MethodSignature methodSignature = (MethodSignature) pjp.getSignature(); Method method = methodSignature.getMethod(); // 若目标方法忽略了安全性检查,则直接调用目标方法 if (method.isAnnotationPresent(UnCheck.class)) return pjp.proceed(); if (StringUtils.isEmpty(tokenName)) tokenName = DEFAULT_TOKEN_NAME; HttpServletRequest request = WebContext.getRequest(); HttpServletResponse response = WebContext.getResponse(); String token = tokenManager.createToken( ((SecurityContextImpl) request.getSession() .getAttribute("SPRING_SECURITY_CONTEXT")) .getAuthentication() .getName()); response.addHeader(tokenName,token); return pjp.proceed(); }
@AfterReturning ("@annotation(fr.gael.dhus.spring.cache.IncrementCache)") public void updateCache (JoinPoint joinPoint) { IncrementCache annotation = ((MethodSignature) joinPoint.getSignature ()) .getMethod ().getAnnotation (IncrementCache.class); Cache cache = getCacheManager().getCache(annotation.name()); if (cache != null) { synchronized (cache) { Integer old_value = cache.get (annotation.key (), Integer.class); cache.clear (); if (old_value == null) { return; } cache.put (annotation.key (), (old_value + annotation.value ())); } } }
TccTransaction providerBegin(TccTransactionContext context, ProceedingJoinPoint point) { LogUtil.debug(LOGGER, "参与方开始执行tcc事务!start:{}", context::toString); MethodSignature signature = (MethodSignature) point.getSignature(); Method method = signature.getMethod(); Class<?> clazz = point.getTarget().getClass(); TccTransaction transaction = new TccTransaction(context.getTransId()); //设置角色为提供者 transaction.setRole(TccRoleEnum.PROVIDER.getCode()); transaction.setStatus(TccActionEnum.PRE_TRY.getCode()); transaction.setTargetClass(clazz.getName()); transaction.setTargetMethod(method.getName()); //保存当前事务信息 coordinatorService.save(transaction); //传入当前threadLocal CURRENT.set(transaction); return transaction; }
@Around("@annotation(com.apssouza.monitoring.Monitored)") public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("callend"); Method method = ((MethodSignature) joinPoint.getSignature()).getMethod(); if (this.enabled) { StopWatch sw = new StopWatch(joinPoint.toShortString()); sw.start("invoke"); try { return joinPoint.proceed(); } finally { sw.stop(); synchronized (this) { this.callCount++; this.accumulatedCallTime += sw.getTotalTimeMillis(); } publisher.publishEvent(new MonitoringInvokedEvent( method.getName(), this.accumulatedCallTime )); } } else { return joinPoint.proceed(); } }
/** * @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); } }
public void logPreExecutionData( @Nonnull ProceedingJoinPoint proceedingJoinPoint, @Nullable RequestMapping methodRequestMapping) { MethodSignature methodSignature = (MethodSignature)proceedingJoinPoint.getSignature(); String methodName = methodSignature.getName() + "()"; Object argValues[] = proceedingJoinPoint.getArgs(); String argNames[] = methodSignature.getParameterNames(); String requestContext = RequestUtil.getRequestContext().toString(); Annotation annotations[][] = methodSignature.getMethod().getParameterAnnotations(); StringBuilder preMessage = new StringBuilder().append(methodName); if (argValues.length > 0) { logFunctionArguments(argNames, argValues, preMessage, annotations, methodRequestMapping); } preMessage.append(" called via ").append(requestContext); LOG.info(preMessage.toString()); }
/** * Get queues names separated with comma from {@link RabbitListener} annotation. * * @param call Call * @return Queues names */ private String[] getQueueNames(ProceedingJoinPoint call) { final MethodSignature signature = (MethodSignature) call.getSignature(); final Method method = signature.getMethod(); final RabbitListener rabbitListenerAnnotation = method.getAnnotation(RabbitListener.class); return rabbitListenerAnnotation.queues(); }
@Around("methodAnnotated() || constructorAnnotated()") public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); long startTime = System.nanoTime(); Object result = joinPoint.proceed();//执行原方法 long cost = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); Logger.d("TimeLog: 类 " + className + " 方法 " + methodName + " 耗时 [" + cost + "ms]"); /*Log.d("timeLog", "====================方法耗时检测===================="); Log.d("timeLog", "= 类名 : " + className); Log.d("timeLog", "= 方法名: " + methodName); Log.d("timeLog", "= 耗时 : [" + cost + "ms]"); Log.d("timeLog", "====================================================");*/ return result; }
@Around("methodAnnotated() || constructorAnnotated()")//在连接点进行方法替换 public Object aroundJoinPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Timber.i(methodSignature.getMethod().getDeclaringClass().getCanonicalName()); String className = methodSignature.getDeclaringType().getSimpleName(); String methodName = methodSignature.getName(); long startTime = System.nanoTime(); Object result = joinPoint.proceed();//执行原方法 StringBuilder keyBuilder = new StringBuilder(); keyBuilder.append(methodName + ":"); for (Object obj : joinPoint.getArgs()) { if (obj instanceof String) keyBuilder.append((String) obj); else if (obj instanceof Class) keyBuilder.append(((Class) obj).getSimpleName()); } String key = keyBuilder.toString(); Timber.i((className + "." + key + joinPoint.getArgs().toString() + " --->:" + "[" + (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime)) + "ms]"));// 打印时间差 return result; }
@Around("mapperCheckPoint()") private Object around(ProceedingJoinPoint point) throws Throwable { if(! check(point)) { return point.proceed(); } if (! (point.getSignature() instanceof MethodSignature)) { return point.proceed(); } MethodSignature methodSignature = (MethodSignature) point.getSignature(); Method method = methodSignature.getMethod(); if (! method.isAnnotationPresent(KeyParam.class)) { return point.proceed(); } KeyParam keyParam = method.getAnnotation(KeyParam.class); String[] ognl = keyParam.value(); String mapper = method.getDeclaringClass().getSimpleName() + "." + method.getName(); RequestHolder.initRequestHolder(mapper, ognl); Object result = point.proceed(); RequestHolder.resetRequest(); return result; }
public boolean checkIlluminatiIsIgnore (final ProceedingJoinPoint pjp) throws Throwable { try { final MethodSignature signature = (MethodSignature) pjp.getSignature(); final Method method = signature.getMethod(); Illuminati illuminati = method.getAnnotation(Illuminati.class); if (illuminati == null) { illuminati = pjp.getTarget().getClass().getAnnotation(Illuminati.class); } if (illuminati == null) { return true; } return illuminati.ignore(); } catch (Exception ex) { // ignore return true; } }
@Before("@annotation(com.nibado.example.springaop.aspects.Restrict) && execution(public * *(..))") public void restrict(final JoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Restrict annotation = signature.getMethod().getAnnotation(Restrict.class); HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .currentRequestAttributes()) .getRequest(); if (annotation.admin() && !isAdmin(request)) { throw new ForbiddenException("Need admin access"); } if (annotation.localOnly() && !request.getRemoteAddr().equals("127.0.0.1") && !request.getRemoteAddr().equals("0:0:0:0:0:0:0:1")) { throw new ForbiddenException("Only possible from localhost"); } }
@Around("aspect()&&@annotation(anno)") public Object interceptor(ProceedingJoinPoint invocation, CacheClear anno) throws Throwable { MethodSignature signature = (MethodSignature) invocation.getSignature(); Method method = signature.getMethod(); Class<?>[] parameterTypes = method.getParameterTypes(); Object[] arguments = invocation.getArgs(); String key = ""; if (StringUtils.isNotBlank(anno.key())) { key = getKey(anno, anno.key(), CacheScope.application, parameterTypes, arguments); cacheAPI.remove(key); } else if (StringUtils.isNotBlank(anno.pre())) { key = getKey(anno, anno.pre(), CacheScope.application, parameterTypes, arguments); cacheAPI.removeByPre(key); } else if (anno.keys().length > 1) { for (String tmp : anno.keys()) { tmp = getKey(anno, tmp, CacheScope.application, parameterTypes, arguments); cacheAPI.removeByPre(tmp); } } return invocation.proceed(); }
/** * generate the key based on SPel expression. */ protected Object generateKey(String key, ProceedingJoinPoint pjp) throws ExpirableCacheException { try { Object target = pjp.getTarget(); Method method = ((MethodSignature) pjp.getSignature()).getMethod(); Object[] allArgs = pjp.getArgs(); if (StringUtils.hasText(key)) { CacheExpressionDataObject cacheExpressionDataObject = new CacheExpressionDataObject(method, allArgs, target, target.getClass()); EvaluationContext evaluationContext = new StandardEvaluationContext(cacheExpressionDataObject); SpelExpression spelExpression = getExpression(key, method); spelExpression.setEvaluationContext(evaluationContext); return spelExpression.getValue(); } return keyGenerator.generate(target, method, allArgs); } catch (Throwable t) { throw new ExpirableCacheException("### generate key failed"); } }
private LimitIPRequestAnnotation getAnnotation(JoinPoint joinPoint) { Signature signature = joinPoint.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); if (method != null) { return method.getAnnotation(LimitIPRequestAnnotation.class); } return null; }
@Around("aspect()&&@annotation(anno)") public Object interceptor(ProceedingJoinPoint invocation, Cache anno) throws Throwable { MethodSignature signature = (MethodSignature) invocation.getSignature(); Method method = signature.getMethod(); Object result = null; Class<?>[] parameterTypes = method.getParameterTypes(); Object[] arguments = invocation.getArgs(); String key = ""; String value = ""; try { key = getKey(anno, parameterTypes, arguments); value = cacheAPI.get(key); Type returnType = method.getGenericReturnType(); result = getResult(anno, result, value, returnType); } catch (Exception e) { log.error("获取缓存失败:" + key, e); } finally { if (result == null) { result = invocation.proceed(); if (StringUtils.isNotBlank(key)) { cacheAPI.set(key, result, anno.expire()); } } } return result; }
/** * 获取注解中对方法的描述信息 用于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; }
private Object logMethod(final ProceedingJoinPoint joinPoint) throws Throwable { L.w(joinPoint.getSignature().toShortString() + " Args : " + (joinPoint.getArgs() != null ? Arrays.deepToString(joinPoint.getArgs()) : "")); Object result = joinPoint.proceed(); String type = ((MethodSignature) joinPoint.getSignature()).getReturnType().toString(); L.w(joinPoint.getSignature().toShortString() + " Result : " + ("void".equalsIgnoreCase(type)?"void":result)); return result; }
public void beforeTrans(JoinPoint point) { Signature signature = point.getSignature(); MethodSignature methodSignature = (MethodSignature) signature; Method method = methodSignature.getMethod(); // 获取目标类 Class<?> target = point.getTarget().getClass(); Method targetMethod = null; try { targetMethod = target.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException e) { e.printStackTrace(); } // 根据目标类方法中的注解,选择数据源 if (targetMethod != null) { Transactional transactional = targetMethod.getAnnotation(Transactional.class); if (transactional != null) { SpecifyDS specifyDSCls = target.getAnnotation(SpecifyDS.class); SpecifyDS specifyDS = targetMethod.getAnnotation(SpecifyDS.class); if (specifyDS != null) { DataSourceHolder.setDataSource(specifyDS.value()); } else if (specifyDSCls != null) { DataSourceHolder.setDataSource(specifyDSCls.value()); } else { DataSourceHolder.setDataSource(defaultTransDb); } } } }
private Object checkFailAndReturn(ProceedingJoinPoint point) throws Throwable { if (! MethodSignature.class.isAssignableFrom(point.getSignature().getClass())) { return point.proceed(); } MethodSignature methodSignature = (MethodSignature) point.getSignature(); Class r = methodSignature.getReturnType(); if (r == String.class) { return FORBIDDEN; } else { return point.proceed(); } }
@Around("execution(* com..*.proxy..*.* (..))") public Object doBasicProfiling(final ProceedingJoinPoint joinPoint) throws Throwable { long start_all = System.currentTimeMillis(); long end_all = 0L; String declaringTypeName = joinPoint.getSignature().getDeclaringTypeName(); String signatureName = joinPoint.getSignature().getName(); Object [] args = joinPoint.getArgs(); Transaction tran = Cat.newTransaction("Aspect-proxy", declaringTypeName + "." + signatureName); if (RpcContext.getContext().getRemoteAddressString() != null && RpcContext.getContext().getMethodName() != null && RpcContext.getContext().getUrl() != null) { MDC.put(HOST, RpcContext.getContext().getRemoteAddressString()); MDC.put(INTERFACE, RpcContext.getContext().getUrl().getServiceInterface()); MDC.put(METHOD, RpcContext.getContext().getMethodName()); } else { MDC.put(HOST, "127.0.0.1"); MDC.put(INTERFACE, "none"); MDC.put(METHOD, "none"); } final DataLogEntity de = new DataLogEntity(); de.setClassName(declaringTypeName); de.setMethodName(signatureName); de.setParams(args); String logJson = de.toJsonStr(); // 参数日志 if (logger.isDebugEnabled()) { logger.debug(de.toJsonStr()); } try { long start = System.currentTimeMillis(); final Object retVal = joinPoint.proceed(); long end = System.currentTimeMillis(); // 记录耗时 logger.info("{}, 耗时:{} ms, 进入aop到执行完耗时:{} ms", logJson, (end - start), (end - start_all)); Cat.logEvent(declaringTypeName, signatureName, "0", logJson+" 耗时:" + (end - start) + " ms" + " 时间戳:" + System.currentTimeMillis()); /** * 设置消息的状态,必须设置,0:标识成功,其他标识发生了异常 */ tran.setStatus(Transaction.SUCCESS); end_all = System.currentTimeMillis(); return retVal; } catch (final Exception e) { final ErrorLogEntity ele = new ErrorLogEntity(de); DataTransferObject dto = handleException(e, ele, tran); end_all = System.currentTimeMillis(); // 方法返回值类型 Class returnType = null; if (null != joinPoint.getSignature()) { returnType = ((MethodSignature) joinPoint.getSignature()).getReturnType(); } if (null != returnType && returnType.equals(String.class)){ return dto.toJsonString(); }else if (null != returnType && returnType.equals(DataTransferObject.class)){ return dto; }else{ throw e; } } finally { MDC.remove(HOST); MDC.remove(INTERFACE); MDC.remove(METHOD); tran.complete(); logger.info("{}, 接入cat后整体耗时: {} ms", logJson, (end_all - start_all)); } }
/** * @param joinPoint */ @AfterReturning("controllerAspect()") public void afterReturn(JoinPoint joinPoint) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); Log log = method.getAnnotation(Log.class); if (null != log) { logger.info(String.format("业务日志 : [%s]", log.value())); } }
/** * @param joinPoint * @param e */ @AfterThrowing(value = "doAfterThrowing()", throwing = "e") public void doAfterThrowing(JoinPoint joinPoint, Throwable e) { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); Method method = methodSignature.getMethod(); Map<String, Object> map = new HashMap<String, Object>(); map.put("className", joinPoint.getTarget().getClass().getName()); map.put("methodName", method.getName()); map.put("args", JSONUtils.toJSONString(joinPoint.getArgs().toString())); map.put("errorMsg", e.getMessage()); logger.error(JSONUtils.toJSONString(map)); }
@Around("@annotation(com.wise.core.aop.annotation.RetriableTransaction)") public Object retry(ProceedingJoinPoint pjp) throws Throwable { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); RetriableTransaction annotation = method.getAnnotation(RetriableTransaction.class); int maxAttempts = annotation.maxRetries(); int attemptCount = 0; List<Class<? extends Throwable>> exceptions = Arrays.asList(annotation.retryFor()); Throwable failure = null; TransactionStatus currentTransactionStatus = null; String businessName = pjp.getTarget().toString(); businessName = businessName.substring(0, businessName.lastIndexOf("@")) + "." + method.getName(); do { attemptCount++; try { DefaultTransactionDefinition transactionDefinition = new DefaultTransactionDefinition(); transactionDefinition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW); currentTransactionStatus = transactionManager.getTransaction(transactionDefinition); Object returnValue = pjp.proceed(); transactionManager.commit(currentTransactionStatus); return returnValue; } catch (Throwable t) { if (!exceptions.contains(t.getClass())) { throw t; } if (currentTransactionStatus != null && !currentTransactionStatus.isCompleted()) { transactionManager.rollback(currentTransactionStatus); failure = t; } LOGGER.debug("事务重试:["+businessName+":"+attemptCount+"/"+maxAttempts+"]"); } } while (attemptCount < maxAttempts); LOGGER.debug("事务重试:["+businessName+":已达最大重试次数]"); throw failure; }
private static Optional<Method> getCallingMethod(JoinPoint joinPoint) { if (joinPoint != null && joinPoint.getSignature() != null) { if (joinPoint.getSignature() instanceof MethodSignature) { final MethodSignature ms = (MethodSignature) joinPoint.getSignature(); return Optional.ofNullable(ms.getMethod()); } } return Optional.empty(); }
@Around("@annotation(com.icthh.xm.commons.lep.LogicExtensionPoint)") @SuppressWarnings("squid:S00112") // suppress throwable waring, this method cat throw any throwable public Object logicExtensionPoint(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Class<?> declaringType = signature.getDeclaringType(); if (!declaringType.isAnnotationPresent(LepService.class)) { throw new IllegalStateException("Bean class " + declaringType + " has no LepService annotation, " + "but have LogicExtensionPoint annotation on method: " + signature); } Method method = signature.getMethod(); LepService lepService = declaringType.getAnnotation(LepService.class); LogicExtensionPoint lep = method.getAnnotation(LogicExtensionPoint.class); Object resultValue; if (lep == null && lepService.explicitMethods()) { resultValue = joinPoint.proceed(); } else { resultValue = lepServiceHandler.onMethodInvoke(declaringType, joinPoint.getTarget(), method, joinPoint.getArgs()); } return resultValue; }
private Timer getTimerAnnotation(ProceedingJoinPoint joinPoint) throws NoSuchMethodException { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); Timer timer = method.getAnnotation(Timer.class); if (timer == null && method.getDeclaringClass().isInterface()) { final String methodName = signature.getName(); final Class<?> implementationClass = joinPoint.getTarget() .getClass(); final Method implementationMethod = implementationClass .getDeclaredMethod(methodName, method.getParameterTypes()); timer = implementationMethod.getAnnotation(Timer.class); } return timer; }
@Before("logPointCut()") public void saveSysLog(JoinPoint joinPoint) { MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); SysLogEntity sysLog = new SysLogEntity(); SysLog syslog = method.getAnnotation(SysLog.class); if(syslog != null){ //注解上的描述 sysLog.setOperation(syslog.value()); } //请求的方法名 String className = joinPoint.getTarget().getClass().getName(); String methodName = signature.getName(); sysLog.setMethod(className + "." + methodName + "()"); //请求的参数 Object[] args = joinPoint.getArgs(); String params = new Gson().toJson(args[0]); sysLog.setParams(params); //获取request HttpServletRequest request = HttpContextUtils.getHttpServletRequest(); //设置IP地址 sysLog.setIp(IPUtils.getIpAddr(request)); //用户名 String username = ((SysUserEntity) SecurityUtils.getSubject().getPrincipal()).getUsername(); sysLog.setUsername(username); sysLog.setCreateDate(new Date()); //保存系统日志 sysLogService.save(sysLog); }
/** * 前置通知 */ @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()); // ⑤ }
public String createTitle(final JoinPoint joinPoint) { final MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); final Step step = methodSignature.getMethod().getAnnotation(Step.class); return step.value().isEmpty() ? getName(methodSignature.getName(), joinPoint.getArgs()) : getTitle(step.value(), methodSignature.getName(), joinPoint.getThis(), joinPoint.getArgs()); }
private static Parameter[] getParameters(final MethodSignature signature, final Object... args) { return IntStream.range(0, args.length).mapToObj(index -> { final String name = signature.getParameterNames()[index]; final String value = Objects.toString(args[index]); return new Parameter().withName(name).withValue(value); }).toArray(Parameter[]::new); }
private void updateTestCase(final JoinPoint joinPoint) { final MethodSignature signature = (MethodSignature) joinPoint.getSignature(); final Object[] args = joinPoint.getArgs(); final Object target = joinPoint.getTarget(); final Allure1Annotations annotations = new Allure1Annotations(target, signature, args); getLifecycle().getCurrentTestCase().ifPresent(uuid -> { getLifecycle().updateTestCase(uuid, annotations::updateTitle); getLifecycle().updateTestCase(uuid, annotations::updateDescription); getLifecycle().updateTestCase(uuid, annotations::updateParameters); getLifecycle().updateTestCase(uuid, annotations::updateLabels); getLifecycle().updateTestCase(uuid, annotations::updateLinks); }); }