@Around(POINT_CUT_QIANBAO) public Object peakLog(ProceedingJoinPoint jp) throws Throwable { Date startDate = new Date(); try { Object object = jp.proceed(); Date endDate = new Date(); log.info( "[qianBaoLog-executeTime] method:" + jp.getSignature() + ",startDate:" + DateUtil.formatDate(startDate, DateUtil.Format.HYPHEN_YYYYMMDDHHMMSS) + ",endDate:" + DateUtil.formatDate(endDate, DateUtil.Format.HYPHEN_YYYYMMDDHHMMSS) + ",timecosts:" + (endDate.getTime() - startDate.getTime())); return object; } catch (Throwable e) { Date endDate = new Date(); log.error( "[qianBaoLog-error] method:" + jp.getSignature() + ",startDate:" + DateUtil.formatDate(startDate, DateUtil.Format.HYPHEN_YYYYMMDDHHMMSS) + ",endDate:" + DateUtil.formatDate(endDate, DateUtil.Format.HYPHEN_YYYYMMDDHHMMSS) + ",timecosts:" + (endDate.getTime() - startDate.getTime())); log.error(e, e); throw e; } }
protected void repositoryLogic(ProceedingJoinPoint joinPoint) throws Throwable { setCustomerIdInEntityManager(); Object object = null; if (joinPoint.getArgs().length > 0) { Object methodInputParam = joinPoint.getArgs()[0]; if (methodInputParam != null && methodInputParam instanceof CommonEntityInterface) { CommonEntityInterface entity = (CommonEntityInterface) methodInputParam; preSaveUpdateOperation(entity); } else if (methodInputParam != null && methodInputParam instanceof List) { List listOfEntities = (List) methodInputParam; if (listOfEntities.size() > 0) { /* * Checking 0th element type. So no need to check type for * each element in the loop. */ if (listOfEntities.get(0) instanceof CommonEntityInterface) { for (Object object1 : listOfEntities) { CommonEntityInterface entity = (CommonEntityInterface) object1; preSaveUpdateOperation(entity); } } } } } }
@Around(value = "@annotation(com.idy.db.RwDateSource)") public Object invoke(ProceedingJoinPoint pjp) { try { Method method = ((MethodSignature) pjp.getSignature()).getMethod(); Method targetMethod = pjp.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes()); // 取注解@YRDatasource RwDateSource ds = targetMethod.getAnnotation(RwDateSource.class); if (ds != null) { /*//策略 metadata.setStrategy(ds.strategy()); LOGGER.debug("将数据源策略{}放入栈顶待用", ds.strategy()); //数据源 metadata.setDirectDatasource(ds.targetDatasource()); if(StringUtils.hasText(ds.targetDatasource())){ LOGGER.debug("将强制数据源{}放入栈顶待用",ds.targetDatasource()); }*/ } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } try { return pjp.proceed(); } catch (Throwable e) { // logger. e.printStackTrace(); } return pjp; }
@Around("updatePointCut()") public Object aroundUpdateMethod(ProceedingJoinPoint pcdJoinPoint) throws Throwable { logger.debug( "The method " + pcdJoinPoint.getSignature().getName() + "() around "); // + Arrays.toString(pcdJoinPoint.getArgs())); Object[] objs = pcdJoinPoint.getArgs(); Date currentDate = new Date(); Object[] modelArray = ((Model) objs[2]).asMap().values().toArray(); for (int i = 0; i < modelArray.length; i++) { if (modelArray[i] instanceof ArrayList) { ArrayList list = (ArrayList) modelArray[i]; for (Object base : list) { if (objs[0].getClass().equals(base.getClass())) { logger.debug("!! Match Found [{}]!! {}", base.getClass(), base); ((BaseEntity) objs[0]).setCreateUser(((BaseEntity) base).getCreateUser()); ((BaseEntity) objs[0]).setCreatedDate(((BaseEntity) base).getCreatedDate()); break; } } } } ((BaseEntity) objs[0]).setUpdateUser(UPDATEUSER); ((BaseEntity) objs[0]).setUpdatedDate(currentDate); return pcdJoinPoint.proceed(objs); }
public Object timerAspect(ProceedingJoinPoint jp) { Object ret = null; try { long start = System.currentTimeMillis(); jp.proceed(); long end = System.currentTimeMillis(); System.out.println("===================================="); System.out.println("TimerAspect.timerAspect running...."); System.out.println( "Method " + jp.getSignature().toShortString() + " took " + (end - start) + " milliseconds"); System.out.println("===================================="); } catch (Throwable t) { System.out.println("Error in timerAspect"); } return ret; }
@Around("updateOperation()") @Order(2) public Object aroundAdvice2Update(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { boolean isValidEntity = true; Object returnObject = new Object(); aroundAdviceSaveAndUpdateLogin(proceedingJoinPoint); if (isValidEntity) { sprinkler.logger.log( runtimeLogInfoHelper.getRuntimeLogInfo(), 1000, proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName(), proceedingJoinPoint.getArgs()[0].getClass().getSimpleName(), proceedingJoinPoint.getArgs()[0].toString()); returnObject = proceedingJoinPoint.proceed(); sprinkler.logger.log( runtimeLogInfoHelper.getRuntimeLogInfo(), 1001, proceedingJoinPoint.getSignature().getDeclaringTypeName(), proceedingJoinPoint.getSignature().getName(), proceedingJoinPoint.getArgs()[0].toString()); return returnObject; } return returnObject; }
@Around("com.energysh.egame.aop.SystemArchitecture.cacheLayer()") public Object doCache(ProceedingJoinPoint pjp) { String key = pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName(); try { if (!cacheMethod.containsKey(key)) return pjp.proceed(); // 需要缓冲的字段 String[] cachePro = cacheMethod.get(key).get("cacheKey").split("[,]"); String expirtTime = cacheMethod.get(key).get("expirtTime"); StringBuilder cacheKey = new StringBuilder(key); Object args0 = pjp.getArgs()[0]; if (args0 instanceof Map) { Map<String, String> para = (Map<String, String>) args0; for (String c : cachePro) { cacheKey.append("|").append(para.get(c)); } } else { cacheKey.append("|").append(args0); } Object returnObj = this.getMemProgrammer().get(cacheKey.toString()); if (null == returnObj) { MyUtil mu = MyUtil.getInstance(); returnObj = pjp.proceed(); if (null == returnObj) return null; if (mu.equals(expirtTime, "-1")) this.getMemProgrammer().set(cacheKey.toString(), returnObj); else this.getMemProgrammer().set(cacheKey.toString(), mu.toInt(expirtTime), returnObj); } return returnObj; } catch (Throwable e) { log.error("programer cache error: ", e); } return null; }
@Around("execution(@com.marcolenzo.gameboard.annotations.ActionLoggable * *(..))") public Object around(ProceedingJoinPoint point) throws Throwable { long start = System.currentTimeMillis(); Object result = point.proceed(); User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); Action action = new Action(); action.setName(MethodSignature.class.cast(point.getSignature()).getMethod().getName()); // Parse args List<String> jsonStrings = Lists.newArrayList(); for (Object obj : point.getArgs()) { jsonStrings.add(mapper.writeValueAsString(obj)); } action.setArgs(jsonStrings); action.setResult(mapper.writeValueAsString(result)); action.setUserId(currentUser.getId()); action.setDatetime(LocalDateTime.now()); repository.save(action); LOGGER.info( "#{}({}): in {} ms by {}", MethodSignature.class.cast(point.getSignature()).getMethod().getName(), point.getArgs(), System.currentTimeMillis() - start, currentUser.getId() + " " + currentUser.getEmail()); return result; }
// com.feilong.spring.aspects.UserManager @Around(value = "pointcut()") public void around(ProceedingJoinPoint joinPoint) throws Throwable { // LoggerFactory. // log. Method method = getMethod(joinPoint, Log.class); String methodName = method.getName(); Date begin = new Date(); // 通过反射执行目标对象的连接点处的方法 joinPoint.proceed(); // 在来得到方法名吧,就是通知所要织入目标对象中的方法名称 Date end = new Date(); Object[] args = joinPoint.getArgs(); // for (Object arg : args){ // log.info("arg:{}", arg.toString()); // } // log.info("{},{}", begin, end); _log = (Log) getAnnotation(joinPoint, Log.class); String level = _log.level(); // log.debug("level:{}", level); // 输出的日志 怪怪的 02:13:10 INFO (NativeMethodAccessorImpl.java:?) [invoke0()] method:addUser([1018, // Jummy]),耗时:0 // ReflectUtil.invokeMethod(log, level, "method:{}({}),耗时:{}", objects); String format = "method:%s(%s),耗时:%s"; Object[] objects = {methodName, args, DateUtil.getIntervalForView(begin, end)}; Object message = StringUtil.format(format, objects); log.log(Level.toLevel(level), message); }
/** * Runs a method call with retries. * * @param pjp a {@link ProceedingJoinPoint} representing an annotated method call. * @param retryableAnnotation the {@link org.fishwife.jrugged.aspects.Retryable} annotation that * wrapped the method. * @throws Throwable if the method invocation itself throws one during execution. * @return The return value from the method call. */ @Around("@annotation(retryableAnnotation)") public Object call(final ProceedingJoinPoint pjp, Retryable retryableAnnotation) throws Throwable { final int maxTries = retryableAnnotation.maxTries(); final int retryDelayMillies = retryableAnnotation.retryDelayMillis(); final Class<? extends Throwable>[] retryOn = retryableAnnotation.retryOn(); final boolean doubleDelay = retryableAnnotation.doubleDelay(); final boolean throwCauseException = retryableAnnotation.throwCauseException(); if (logger.isDebugEnabled()) { logger.debug( "Have @Retryable method wrapping call on method {} of target object {}", new Object[] {pjp.getSignature().getName(), pjp.getTarget()}); } ServiceRetrier serviceRetrier = new ServiceRetrier(retryDelayMillies, maxTries, doubleDelay, throwCauseException, retryOn); return serviceRetrier.invoke( new Callable<Object>() { public Object call() throws Exception { try { return pjp.proceed(); } catch (Exception e) { throw e; } catch (Error e) { throw e; } catch (Throwable t) { throw new RuntimeException(t); } } }); }
@Around( "saveOperation()||deleteOperation()||updateOperation()||findOperation()||getOperation()||allOperation()") public Object aroundfindAll(ProceedingJoinPoint joinPoint) throws Throwable { MethodCallDetails methodCallDetails = new MethodCallDetails( requestDetails.getRequestId(), requestDetails.getCallSequence(), HealthConstants.CLASS_TYPE.REPOSITORY, runtimeLogInfoHelper.getRuntimeLogInfo().getUserIpAddress(), "", joinPoint.getTarget().getClass().toString(), joinPoint.getSignature().getName(), runtimeLogInfoHelper.getRuntimeLogInfo().getUserId(), requestDetails.getAppSessionId()); Object object = null; repositoryLogic(joinPoint); try { object = handleRepositoryCall(joinPoint, runtimeLogInfoHelper.getRuntimeLogInfo()); methodCallDetails.setPostCallDetails(HealthConstants.METHOD_NORMAL_EXECUTION); } catch (SpartanPersistenceException e) { methodCallDetails.setPostCallDetails(HealthConstants.METHOD_EXCEPTION, e.getExceptionId()); e.printStackTrace(); throw e; } catch (Exception e) { methodCallDetails.setPostCallDetails( HealthConstants.METHOD_EXCEPTION, HealthConstants.DEFAULT_EXCEPTION_ID); e.printStackTrace(); throw e; } finally { requestDetails.addMethodCallDetails(methodCallDetails); } return object; }
/** 1.保证拿到锁才能调用。没有拿到的话,就等待 2.捕获异常,重发(总共5次机会) */ @SuppressWarnings("deprecation") @Around("actionMethod2()") public Object interceptor2(ProceedingJoinPoint pjp) throws Throwable { HopsException exception = null; Object[] args = pjp.getArgs(); try { Boolean processFlag = false; for (int i = 0; i < RETRY_TIME && processFlag == false; i++) { try { processFlag = (Boolean) pjp.proceed(); } catch (HopsException e) { exception = e; processFlag = false; logger.error("AccountServiceExceptionIntercept exception [" + i + "] times"); Thread.currentThread().sleep(random.nextInt(1000)); } } if (processFlag != true) { throw exception != null ? exception : new ApplicationException("identity101081"); } return processFlag; } catch (Exception e) { logger.error( "Account Service operation failed caused by:" + ExceptionUtil.getStackTraceAsString(e)); if (e instanceof HopsException) { throw e; } else { throw new SystemException( "identity101081", new String[] {ExceptionUtil.getStackTraceAsString(e)}, e); } } }
@Around("execution(* javax.validation.ConstraintValidator.isValid(..)) && args(value, context)") public Object aroundValid( ProceedingJoinPoint jointPoint, Object value, ConstraintValidatorContext context) throws Throwable { if (value == null) { // @NotNullのケースが有るため、処理させる。他Validationは通常Null時はパスなので return jointPoint.proceed(); } ValidateContext validateContext = ValidateContext.instance(); Object declaring = null; Condition condition = null; if (validateContext.isAnnotatedClass()) { condition = value.getClass().getAnnotation(Condition.class); declaring = value; } else if (validateContext.isAnnotatedField() || validateContext.isAnnotatedMethod()) { AccessibleObject accessible = (AccessibleObject) validateContext.getAnnotated(); condition = accessible.getAnnotation(Condition.class); declaring = validateContext.getDeclared(); } if (condition != null && declaring != null && !judgeCondition(condition, declaring)) { // @Condition判定処理結果がfalseなので、Validate処理外 return true; } return jointPoint.proceed(); }
@Around("findTurmaEfetiva()") public Object findTurmaEfetivaMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-efetivas-cache"); Object[] args = joinPoint.getArgs(); Long turmaId = (Long) args[0]; Element element = cache.get(turmaId); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(turmaId, result)); } else { Logger.getLogger(this.getClass().getName()) .log( Level.INFO, "Dados presentes no cache de turmas, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@SuppressWarnings("unchecked") @Around( "execution(* org.springframework.webflow.samples.booking.JpaBookingService.findHotels(org.springframework.webflow.samples.booking.SearchCriteria)) && args(criteria)") public List<Hotel> cacheHotelList(ProceedingJoinPoint joinPoint, SearchCriteria criteria) { List<Hotel> resultingHotelsList = null; if (isBugEnabled.get()) { resultingHotelsList = hotelCache.get(criteria); if (resultingHotelsList == null) { try { resultingHotelsList = (List<Hotel>) joinPoint.proceed(new Object[] {criteria}); hotelCache.put(criteria, resultingHotelsList); } catch (Throwable e) { e.printStackTrace(); } } } else { try { resultingHotelsList = (List<Hotel>) joinPoint.proceed(new Object[] {criteria}); } catch (Throwable e) { e.printStackTrace(); } } return resultingHotelsList; }
@Around("findAllComPendendias()") public Object findAllTurmasComPendenciasMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable { Object result = null; CacheManager cacheManager = CacheManager.create(new ClassPathResource("echache.xml").getInputStream()); Cache cache = cacheManager.getCache("turmas-pendencias-cache"); Object[] args = joinPoint.getArgs(); if (args[0] == null || args[1] == null) { result = joinPoint.proceed(); return result; } SimpleDateFormat df = new SimpleDateFormat("yyyy"); String exercicio = df.format((Date) args[0]); String organizacao = ((Long) args[1]).toString(); String key = exercicio + "-" + organizacao; Element element = cache.get(key); if (element == null) { result = joinPoint.proceed(); cache.put(new Element(key, result)); } else { Logger.getLogger(this.getClass().getName()) .log(Level.INFO, "Dados presentes no cache, não foi necessário acesso ao banco de dados"); result = element.getValue(); } return result; }
@Around("execution(* brut.androlib.res.data.ResPackage.addResSpec(..))") public void addResSpec(ProceedingJoinPoint joinPoint) { try { joinPoint.proceed(joinPoint.getArgs()); } catch (Throwable throwable) { LogHelper.warning(throwable.getMessage()); } }
@Around("com.zaliczenie.aspects.ConfigureAspect.aaa()") public Object ddd(ProceedingJoinPoint pjp) throws Throwable { Set<ConstraintViolation<Object>> bledy = validator.validate(pjp.getArgs()[0]); if (bledy.isEmpty()) { pjp.proceed(); } return bledy; }
public Object simpleAroundAdvice(ProceedingJoinPoint jp, int intValue) throws Throwable { System.out.println( "перед исполнением: " + jp.getSignature().getDeclaringTypeName() + " " + jp.getSignature()); Object proc = jp.proceed(); System.out.println( "исполнение после: " + jp.getSignature().getDeclaringTypeName() + " " + jp.getSignature()); return proc; }
@Around("execution(* com.baeldung.spring.service.SpringSuperService.*(..))") public Object auditMethod(ProceedingJoinPoint jp) throws Throwable { String methodName = jp.getSignature().getName(); accumulator.add("Call to " + methodName); Object obj = jp.proceed(); accumulator.add("Method called successfully: " + methodName); return obj; }
public Object checkServiceAOP(ProceedingJoinPoint call) throws Throwable { try { checkService((ServiceStatusDetectable) call.getThis()); } catch (Throwable e) { LOG.error("Could not check service status", e); } return call.proceed(); }
@Around("within(at.makubi.wuslng.services..*)") public Object aroundServiceCalls(ProceedingJoinPoint pjp) throws Throwable { try { return pjp.proceed(); } catch (JsonRpcClientException e) { handleServiceException(e); return pjp.proceed(); } }
public Object handle(String name, ProceedingJoinPoint joinpoint) throws Throwable { StackFrame stackFrame = new StackFrame(); stackFrame.name = name; stackFrame.arguments = joinpoint.getArgs(); stackFrame.returnValue = joinpoint.proceed(transform.tranform(joinpoint.getArgs())); stackFrames.add(stackFrame); LOGGER.log(Level.INFO, stackFrame.toString()); return stackFrame.returnValue; }
@Around("execution (@org.springframework.scheduling.annotation.Scheduled * *.*(..))") public Object traceBackgroundThread(final ProceedingJoinPoint pjp) throws Throwable { Trace trace = this.tracer.startTrace(pjp.toShortString()); try { return pjp.proceed(); } finally { this.tracer.close(trace); } }
/** * Profile the given method call. * * @param call ProceedingJoinPoint method call to profile * @return Object return object for method call * @throws Throwable if error */ public Object profile(ProceedingJoinPoint call) throws Throwable { try { getStopWatch().start(call.getSignature().toLongString()); return call.proceed(); } finally { getStopWatch().stop(call.getSignature().toLongString()); } }
@Around("trackFinishedPlaying()") public Object logDao(ProceedingJoinPoint pjp) throws Throwable { final QueueItem qi = (QueueItem) pjp.getArgs()[0]; System.out.println("Scrobbling " + qi.toString() + " to " + username); return pjp.proceed(); }
@Around("execution (* com.boky.SubjectParser..*.*(..))") public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable { Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass()); logger.trace(crateTabs(num++) + "Start " + "." + joinPoint.getSignature().getName()); Object result = joinPoint.proceed(); logger.trace(crateTabs(--num) + "End" + joinPoint.getSignature().getName()); return result; }
@Around("daoMethods()") public Object aroundDaoMethod(ProceedingJoinPoint joinpoint) throws Throwable { logger.info(joinpoint.getSignature() + " called..."); Object output = joinpoint.proceed(); logger.info(joinpoint.getSignature() + " execution complete..."); return output; }
@Around( value = "saveOperation()||deleteOperation()||updateOperation()||findOperation()||getOperation()||allOperation()") public Object aroundfindAll(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("In around repository aspect"); MethodCallDetails methodCallDetails = new MethodCallDetails( requestDetails.getRequestId(), HealthConstants.CLASS_TYPE.REPOSITORY, runtimeLogInfoHelper.getRuntimeLogInfo().getUserIpAddress(), "", joinPoint.getTarget().getClass().toString(), joinPoint.getSignature().getName(), runtimeLogInfoHelper.getRuntimeLogInfo().getUserId(), ""); setCustomerIdInEntityManager(); Object object = null; if (joinPoint.getArgs().length > 0) { Object methodInputParam = joinPoint.getArgs()[0]; if (methodInputParam != null && methodInputParam instanceof CommonEntityInterface) { CommonEntityInterface entity = (CommonEntityInterface) methodInputParam; preSaveUpdateOperation(entity); } else if (methodInputParam != null && methodInputParam instanceof List) { List listOfEntities = (List) methodInputParam; if (listOfEntities.size() > 0) { /* * Checking 0th element type. So no need to check type for * each element in the loop. */ if (listOfEntities.get(0) instanceof CommonEntityInterface) { for (Object object1 : listOfEntities) { CommonEntityInterface entity = (CommonEntityInterface) object1; preSaveUpdateOperation(entity); } } } } } try { object = handleRepositoryCall(joinPoint, runtimeLogInfoHelper.getRuntimeLogInfo()); methodCallDetails.setPostCallDetails(HealthConstants.METHOD_NORMAL_EXECUTION); } catch (SpartanPersistenceException e) { methodCallDetails.setPostCallDetails(HealthConstants.METHOD_EXCEPTION, e.getExceptionId()); e.printStackTrace(); throw e; } catch (Exception e) { methodCallDetails.setPostCallDetails( HealthConstants.METHOD_EXCEPTION, HealthConstants.DEFAULT_EXCEPTION_ID); e.printStackTrace(); throw e; } finally { requestDetails.addRepositoryMethodCallDetails(methodCallDetails); } return object; }
public String around2(ProceedingJoinPoint pjp) throws Throwable { // メソッド呼出の前後にWeavingするAdvice System.out.println("***pre proceed"); Signature sig = pjp.getSignature(); System.out.println("Sig: " + sig.getName()); String msg = (String) pjp.proceed(); // msg = msg + "fuga"; System.out.println("***post proceed"); return msg; }