コード例 #1
0
ファイル: EhcacheAspect.java プロジェクト: ceeker/jeecg
  @Around("simplePointcut()")
  public Object aroundLogCalls(ProceedingJoinPoint joinPoint) throws Throwable {
    String targetName = joinPoint.getTarget().getClass().toString();
    String methodName = joinPoint.getSignature().getName();
    Object[] arguments = joinPoint.getArgs();

    // 试图得到标注的Ehcache类
    @SuppressWarnings("unused")
    Method[] methods = joinPoint.getTarget().getClass().getMethods();
    Ehcache flag = null;
    for (Method m : methods) {
      if (m.getName().equals(methodName)) {
        Class[] tmpCs = m.getParameterTypes();
        if (tmpCs.length == arguments.length) {
          flag = m.getAnnotation(Ehcache.class);
          break;
        }
      }
    }
    if (flag == null) {
      return null;
    }
    // Ehcache flag
    // =joinPoint.getTarget().getClass().getMethod(methodName).getAnnotation(Ehcache.class);
    Object result;
    String cacheKey = getCacheKey(targetName, methodName, arguments);

    Element element = null;
    if (flag.eternal()) {
      // 永久缓存
      element = dictCache.get(cacheKey);
    } else {
      // 临时缓存
      element = eternalCache.get(cacheKey);
    }

    if (element == null) {
      if ((arguments != null) && (arguments.length != 0)) {
        result = joinPoint.proceed(arguments);
      } else {
        result = joinPoint.proceed();
      }

      element = new Element(cacheKey, (Serializable) result);
      if (flag.eternal()) {
        // 永久缓存
        dictCache.put(element);
      } else {
        // 临时缓存
        eternalCache.put(element);
      }
    }
    return element.getValue();
  }
コード例 #2
0
  @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;
  }
コード例 #3
0
  /**
   * 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);
            }
          }
        });
  }
コード例 #4
0
 @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;
 }
コード例 #5
0
  @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;
  }
コード例 #6
0
 @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;
 }
コード例 #7
0
 @Around("execution (* com.boky.SubjectParser.services.services.EditServiceHelper.*(..))")
 public Object handleEditServiceExceptions(ProceedingJoinPoint joinPoint) throws Throwable {
   Object result;
   try {
     result = joinPoint.proceed();
   } catch (Exception e) {
     Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());
     logger.error(e.getMessage(), e);
     throw new EditServiceException(e);
   }
   return result;
 }
コード例 #8
0
  public Object invoke(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

    ProxyRequest proxyRequest = createProxyRequest(proceedingJoinPoint);

    BaseProxyBean baseProxyBean = (BaseProxyBean) proceedingJoinPoint.getTarget();

    if (proxyRequest.isSynchronous()) {
      return doInvokeSynchronous(proxyRequest, baseProxyBean);
    } else {
      doInvokeAsynchronous(proxyRequest, baseProxyBean);

      return null;
    }
  }
コード例 #9
0
ファイル: Logger.java プロジェクト: tiaped/gravity-simulation
 /**
  * Do basic logging.
  *
  * @param pjp the pjp
  * @return the object
  * @throws Throwable the throwable
  */
 public Object doBasicLogging(final ProceedingJoinPoint pjp) throws Throwable {
   // start stopwatch
   System.out.println("Kind : " + pjp.getKind());
   System.out.println("args : " + pjp.getArgs());
   System.out.println("signature : " + pjp.getSignature());
   System.out.println("target : " + pjp.getTarget());
   System.out.println("this : " + pjp.getThis());
   final long start = System.nanoTime();
   final Object retVal = pjp.proceed();
   // stop stopwatch
   System.out.println("time taken : " + (System.nanoTime() - start));
   System.out.println(retVal);
   return retVal;
 }
コード例 #10
0
ファイル: LogAspect.java プロジェクト: soffredo/cours-spring
 @Around(value = cut)
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
   try {
     Object result = joinPoint.proceed();
     System.out.println("--------- ICI ON LOG AROUND ---------");
     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());
     return result;
   } catch (Throwable e) {
     // e.printStackTrace();
     throw e;
   }
 }
コード例 #11
0
 private Method getAnnotatedMethod(final ProceedingJoinPoint proceedingJoinPoint)
     throws NoSuchMethodException {
   final MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
   Method operation = signature.getMethod();
   // is it an interface? if yes, fetch the method from interface implementation
   if (operation.getDeclaringClass().isInterface()) {
     operation =
         proceedingJoinPoint
             .getTarget()
             .getClass()
             .getDeclaredMethod(operation.getName(), operation.getParameterTypes());
   }
   return operation;
 }
コード例 #12
0
 @Around("execution(* es.rubenjgarcia.aop.Foo.*(..))")
 public Object measureMethod(ProceedingJoinPoint pjp) throws Throwable {
   StopWatch sw = new StopWatch();
   Object retVal;
   try {
     sw.start(pjp.getTarget() + "." + pjp.getSignature());
     retVal = pjp.proceed();
   } catch (Throwable e) {
     throw e;
   } finally {
     sw.stop();
     System.out.println(sw.prettyPrint());
   }
   return retVal;
 }
コード例 #13
0
 @Around("findOperation()||getOperation()")
 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;
   setCustomerIdInEntityManager();
   try {
     Log.out.println(
         "ABSAA314900100",
         runtimeLogInfoHelper.getRequestHeaderBean(),
         joinPoint.getSignature().getDeclaringTypeName(),
         joinPoint.getSignature().getName(),
         joinPoint.getSignature().getDeclaringTypeName()
             + ":"
             + joinPoint.getSignature().getName());
     object = joinPoint.proceed();
     methodCallDetails.setPostCallDetails(HealthConstants.METHOD_NORMAL_EXECUTION);
     Log.out.println(
         "ABSAA347900100",
         runtimeLogInfoHelper.getRequestHeaderBean(),
         joinPoint.getSignature().getDeclaringTypeName(),
         joinPoint.getSignature().getName(),
         joinPoint.getSignature().getDeclaringTypeName(),
         methodCallDetails.getExecution_Time());
   } catch (Exception e) {
     AppAlarm appAlarm = Log.getExceptionAlarm("ABS", "AA", e.getClass().getName());
     Log.out.println(
         appAlarm.getAlarmID(),
         runtimeLogInfoHelper.getRequestHeaderBean(),
         joinPoint.getSignature().getDeclaringTypeName(),
         joinPoint.getSignature().getName(),
         e.getMessage(),
         e);
     throw e;
   } finally {
     requestDetails.addMethodCallDetails(methodCallDetails);
   }
   return object;
 }
コード例 #14
0
 private Object debug(ProceedingJoinPoint pjp, MethodTimeDebugger timeDebugger) throws Throwable {
   if (!timeDebugger.value()) {
     return pjp.proceed();
   }
   String type = timeDebugger.type();
   StringBuffer msg = new StringBuffer();
   msg.append(type + "[")
       .append(pjp.getTarget().getClass().getName())
       .append(".")
       .append(getMethod(pjp.getSignature()).getName())
       .append("(..)");
   ExecutionStack.push(msg.toString());
   Object result = pjp.proceed();
   ExecutionStack.pop(msg.toString());
   return result;
 }
コード例 #15
0
ファイル: MyProxy.java プロジェクト: zhonglinlin1305/Spring
 public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
   // 加逻辑的时候, 不要依赖执行的的先后顺序
   //		System.out.println("method around start!");
   //		org.aspectj.lang.Signature signature = pjp.getSignature();
   //		Object[] obs = pjp.getArgs();
   //		org.aspectj.lang.JoinPoint.StaticPart part = pjp.getStaticPart();
   Object o = pjp.getTarget();
   logger.info(
       "------------------------------before excute method,method name is:'"
           + o.getClass().getName()
           + "."
           + pjp.getSignature().getName()
           + "'");
   Object proceed = pjp.proceed();
   logger.info("------------------------------after excute method");
   return proceed;
 }
コード例 #16
0
ファイル: MutexAspect.java プロジェクト: hafsky/ironrhino
 @Around("execution(public * *(..)) and @annotation(mutex)")
 public Object control(ProceedingJoinPoint jp, Mutex mutex) throws Throwable {
   String key = mutex.key();
   StringBuilder sb = new StringBuilder();
   if (StringUtils.isBlank(key)) {
     Class<?> beanClass = jp.getTarget().getClass();
     String beanName = NameGenerator.buildDefaultBeanName(beanClass.getName());
     Component comp = beanClass.getAnnotation(Component.class);
     if (StringUtils.isNotBlank(comp.value())) beanName = comp.value();
     sb.append(beanName).append('.').append(jp.getSignature().getName()).append('(');
     Object[] args = jp.getArgs();
     if (args.length > 0) {
       for (int i = 0; i < args.length; i++) {
         sb.append(args[i]);
         if (i != args.length - 1) sb.append(',');
       }
     }
     sb.append(')');
   } else {
     Map<String, Object> context = buildContext(jp);
     sb.append(ExpressionUtils.evalString(key, context));
   }
   switch (mutex.scope()) {
     case GLOBAL:
       break;
     case APPLICATION:
       sb.append('-').append(AppInfo.getAppName());
       break;
     case LOCAL:
       sb.append('-').append(AppInfo.getAppName()).append('-').append(AppInfo.getHostName());
       break;
     default:
       break;
   }
   String lockName = sb.toString();
   if (lockService.tryLock(lockName)) {
     try {
       return jp.proceed();
     } finally {
       lockService.unlock(lockName);
     }
   } else {
     throw new ErrorMessage("tryLock failed and skip execute [" + jp.getSignature() + "]");
   }
 }
コード例 #17
0
  /**
   * 创建并保存日志对象
   *
   * @param logMethod
   * @param jp
   */
  private void doLog(LogMethod logMethod, ProceedingJoinPoint jp) {
    String logText = logMethod.name();
    String classStr = jp.getTarget().getClass().getName();

    Object obj = jp.getThis();
    if (obj instanceof AbstractAction) {
      AbstractAction action = (AbstractAction) obj;
      HttpServletRequest request = action.getRequest();
      logText += "\r\n请求:" + request.getRequestURI() + "\r\n";
      Enumeration params = request.getParameterNames();
      while (params.hasMoreElements()) {
        String param = (String) params.nextElement();
        String value = request.getParameter(param);
        logText += ("参数->" + param + ":" + value + "\r\n");
      }
    }
    saveLog(jp, logText, classStr);
  }
コード例 #18
0
 @Around("execution(public java.lang.String *.getCounter(..))")
 public Object logBefore(ProceedingJoinPoint joinPoint) throws Throwable {
   String msg = "(null) -> ";
   Object target = joinPoint.getTarget();
   try {
     Field counterField = target.getClass().getDeclaredField("counter");
     int counter = (int) counterField.get(target);
     msg = String.valueOf(counter) + " -> ";
   } catch (NoSuchFieldException
       | SecurityException
       | IllegalArgumentException
       | IllegalAccessException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   String s = (String) joinPoint.proceed();
   return msg + s;
 }
コード例 #19
0
ファイル: ExecuteLogger.java プロジェクト: holmesycl/draw
 @Around("logger()")
 public Object around(ProceedingJoinPoint pjp) throws Throwable {
   MethodSignature signature = (MethodSignature) pjp.getSignature();
   Method method = signature.getMethod();
   logger.debug(
       "{}.{}({})",
       pjp.getTarget().getClass().getName(),
       method.getName(),
       Arrays.toString(pjp.getArgs()));
   Object rtn = null;
   try {
     rtn = pjp.proceed();
   } catch (Throwable e) {
     logger.error(e.toString());
     throw e;
   }
   logger.debug(String.valueOf(rtn));
   return rtn;
 }
コード例 #20
0
  @Around(value = "memcacheGet() && @annotation(memcached)", argNames = "memcached")
  public Object memcacheGetQuery(ProceedingJoinPoint pjp, Memcached me) throws Throwable {
    pjp.proceed();

    pjp.getTarget();
    MethodInvocation invocation = null;
    String targetName = invocation.getThis().getClass().getName();
    String methodName = invocation.getMethod().getName();
    Object[] arguments = invocation.getArguments();

    String cacheKey = getCacheKey(targetName, methodName, arguments);
    Object element = /*getCacheHandler().get(cacheKey)*/ null;
    if (logger.isDebugEnabled()) {
      logger.debug("++++++++++++ interceptor method:" + methodName);
    }
    if (element == null) {
      /*
      	Object result = invocation.proceed();
      	element = result;
      	if(!NullUtil.isNull(result)){
      		long expireTime ;
      		if( this.getExpireTime() != 0 ){
      			expireTime = 	this.getExpireTime();
      		}else{
      			expireTime = getCacheHandler().getExpireTime();
      		}


      		boolean f = getCacheHandler().set(cacheKey, result,expireTime);
      		if(logger.isDebugEnabled()){
      			logger.debug("set the obj["+element+"] to the memcached with key:"+cacheKey+".set state:"+f);
      			logger.debug("expireTime:"+expireTime);
      		}
      	}
      */
    } else {
      if (logger.isDebugEnabled()) {
        logger.debug("Get the obj[" + element + "] from the memcached with key:" + cacheKey);
      }
    }

    return element;
  }
コード例 #21
0
ファイル: DaoAspect.java プロジェクト: dalinhuang/DC
  @Around(value = "studentDao() || systemDao() || coreDao() ")
  public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    long startTime = System.currentTimeMillis();
    Object proceed = proceedingJoinPoint.proceed();
    long endTime = System.currentTimeMillis();

    // 拦截的实体类
    String className = proceedingJoinPoint.getTarget().getClass().getName();
    // 拦截的方法名称
    String methodName = proceedingJoinPoint.getSignature().getName();

    SystemLogger systemLogger = new SystemLogger();
    systemLogger.setType(CodeConstant.LOGGER_TYPE_DAO);
    systemLogger.setClassName(className);
    systemLogger.setMethordName(methodName);
    systemLogger.setExecuteTime((int) (endTime - startTime));
    LoggerUtil.log(systemLogger);
    return proceed;
  }
コード例 #22
0
ファイル: CacheAspect.java プロジェクト: wenjianping/ichano
 /**
  * 获取被拦截方法对象
  *
  * <p>MethodSignature.getMethod() 获取的是顶层接口或者父类的方法对象 而缓存的注解在实现类的方法上 所以应该使用反射获取当前对象的方法对象
  */
 public Method getMethod(ProceedingJoinPoint pjp) {
   // 获取参数的类型
   Object[] args = pjp.getArgs();
   @SuppressWarnings("rawtypes")
   Class[] argTypes = new Class[pjp.getArgs().length];
   for (int i = 0; i < args.length; i++) {
     if (args[i] != null) {
       argTypes[i] = args[i].getClass();
     }
   }
   Method method = null;
   try {
     method = pjp.getTarget().getClass().getMethod(pjp.getSignature().getName(), argTypes);
   } catch (NoSuchMethodException e) {
     LOGGER.error("", e);
   } catch (SecurityException e) {
     LOGGER.error("", e);
   }
   return method;
 }
コード例 #23
0
  public void setUp(final Object testService) {
    MockitoAnnotations.initMocks(this);
    when(cache.getName()).thenReturn(AnnotationConstants.DEFAULT_CACHE_NAME);
    when(cache.getProperties()).thenReturn(new CacheProperties());
    advice = createAdvice();
    CacheBase cacheBase = new CacheBase();
    cacheBase.addCache(cache);
    advice.setCacheBase(cacheBase);

    when(signature.getName()).thenReturn(methodName);
    when(signature.getParameterTypes()).thenReturn(paramTypes);
    when(pjp.getSignature()).thenReturn(signature);
    when(pjp.toShortString()).thenReturn(methodName);
    when(pjp.getArgs()).thenReturn(params);

    when(signature.getDeclaringType()).thenReturn(testService.getClass());
    when(pjp.getTarget()).thenReturn(testService);

    if (isValid && cacheKey == null) {
      cacheKey = getKey(getNamespace(), params);
    }
  }
コード例 #24
0
  /**
   * Runs a method call through the spring managed {@link
   * org.springframework.retry.support.RetryTemplate} instance indicated by the annotations "name"
   * attribute.
   *
   * @param pjp a {@link org.aspectj.lang.ProceedingJoinPoint} representing an annotated method
   *     call.
   * @param retryTemplateAnnotation the {@link org.fishwife.jrugged.spring.aspects.RetryTemplate}
   *     annotation that wrapped the method.
   * @throws Throwable if the method invocation itself or the wrapping {@link
   *     org.springframework.retry.support.RetryTemplate} throws one during execution.
   * @return The return value from the method call.
   */
  @Around("@annotation(retryTemplateAnnotation)")
  public Object retry(final ProceedingJoinPoint pjp, final RetryTemplate retryTemplateAnnotation)
      throws Throwable {
    final String name = retryTemplateAnnotation.name();
    final String recoveryCallbackName = retryTemplateAnnotation.recoveryCallbackName();

    org.springframework.retry.support.RetryTemplate retryTemplate =
        beanFactory.getBean(name, org.springframework.retry.support.RetryTemplate.class);

    org.springframework.retry.RecoveryCallback recoveryCallback = null;
    if (!Strings.isNullOrEmpty(recoveryCallbackName)) {
      recoveryCallback =
          beanFactory.getBean(
              recoveryCallbackName, org.springframework.retry.RecoveryCallback.class);
    }

    if (logger.isDebugEnabled()) {
      logger.debug(
          "Have @RetryTemplate method with retryTemplate name {} and callback name {}, "
              + "wrapping call on method {} of target object {}",
          new Object[] {name, recoveryCallbackName, pjp.getSignature().getName(), pjp.getTarget()});
    }

    return retryTemplate.execute(
        new RetryCallback<Object>() {
          public Object doWithRetry(RetryContext context) throws Exception {
            try {
              return pjp.proceed();
            } catch (Error e) {
              throw e;
            } catch (Exception e) {
              throw e;
            } catch (Throwable e) {
              throw new RuntimeException(e);
            }
          }
        },
        recoveryCallback);
  }
コード例 #25
0
ファイル: AccessLoger.java プロジェクト: gitter-badger/tower
 public static Object process(ProceedingJoinPoint pjp) throws Throwable {
   String reqId = RequestID.get();
   if (StringUtil.isEmpty(reqId)) {
     RequestID.set(null);
   }
   _logger.info("start process");
   Object target = pjp.getTarget();
   String ip = RpcContext.getContext().getRemoteAddressString();
   if (ip != null) {
     ip = ip + " ";
   }
   LoggerPoint point = getLoggerPoint(pjp);
   String keys = null;
   if (point != null) {
     keys = point.key();
     if ("none".equalsIgnoreCase(keys)) {
       return pjp.proceed();
     }
   }
   long time = System.currentTimeMillis();
   Map svcDef = AliasUtil.getAlias(keys, pjp, true);
   try {
     time = System.currentTimeMillis();
     return pjp.proceed();
   } catch (Exception ex) {
     _logger.error(ex);
     throw ex;
   } finally {
     time = System.currentTimeMillis() - time;
     _logger.info(
         "%s %,dms",
         ip + svcDef.get("className") + "." + svcDef.get("methodName") + svcDef.get("detail"),
         time);
     _logger.info("end process");
     RequestID.unset();
   }
 }
コード例 #26
0
ファイル: ServiceAspect.java プロジェクト: applifireAlgo/test
 @Around(value = "allOperation()||athenaServiceOperation()||spartanServiceOperation()")
 @Order(1)
 public Object aroundAdvice1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
   System.out.println(
       "In aroundAdvice Order 1 : Calling method : "
           + proceedingJoinPoint.getSignature().getName());
   HttpServletRequest request =
       ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   HttpSession session = request.getSession();
   long nextAutoNum = autoRequestId.getAndIncrement();
   methodCallStack.setRequestId(UUID.randomUUID().toString().toUpperCase());
   MethodCallDetails methodCallDetails =
       new MethodCallDetails(
           methodCallStack.getRequestId(),
           HealthConstants.CLASS_TYPE.SERVICE,
           request.getRemoteHost(),
           request.getMethod(),
           proceedingJoinPoint.getTarget().getClass().toString(),
           proceedingJoinPoint.getSignature().getName(),
           "",
           getSessionId(request));
   String entityName =
       incrementUricounter(
           proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName(),
           proceedingJoinPoint.getSignature().getName());
   // ResponseEntity<ResponseBean> responseEntity = new
   // ResponseEntity<>(HttpStatus.OK);
   Object responseEntity = null;
   /*
    * Needs to get user id from request header and pass it to entityAudit
    * and RuntimeLogInfo
    */
   /* create logging info object (Needs to call from login service only */
   runtimeLogInfoHelper.createRuntimeLogUserInfo(1, "", request.getRemoteHost());
   /* validate request */
   try {
     // validateRequest(session, request);
     // if (!sessionValidation.checkIgnoreURL(request)) {
     // runtimeLogInfoHelper.setUserAccessCode(Integer.parseInt(session.getAttribute("userAccessCode").toString()));
     // }
     Object obj = proceedingJoinPoint.proceed();
     // comment by maya
     /*
      * if (obj instanceof ResponseEntity<?>) { responseEntity =
      * (ResponseEntity<ResponseBean>) obj; httpStatusCode =
      * responseEntity.getStatusCode(); } else { httpStatusCode =
      * HttpStatus.OK; return obj; }
      */
     responseEntity = obj;
     // responseEntity = (ResponseEntity<ResponseBean>) obj;
     // httpStatusCode = responseEntity.getStatusCode();
     // methodCallDetails.setPostCallDetails(HealthConstants.METHOD_NORMAL_EXECUTION,
     // responseEntity.getStatusCode().name());
   } catch (SpartanAccessDeniedException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             " Access Denied " + e.getMessage());
     // methodCallDetails.setPostCallDetails(HealthConstants.METHOD_EXCEPTION,
     // e.getExceptionId(), responseEntity.getStatusCode().name());
     // return new ResponseEntity<ResponseBean>(exceptionbean,
     // responseEntity.getStatusCode());
   } catch (SpartanPersistenceException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             " Can not perform Operation on entity:" + e.getMessage());
     // methodCallDetails.setPostCallDetails(HealthConstants.METHOD_EXCEPTION,
     // e.getExceptionId(), responseEntity.getStatusCode().name());
     // return new ResponseEntity<ResponseBean>(exceptionbean,
     // responseEntity.getStatusCode());
   } catch (Exception e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean responseBean = new ResponseBean();
     responseBean.add("success", false);
     responseBean.add("message", " Access Denied:" + e.getMessage());
     // methodCallDetails.setPostCallDetails(HealthConstants.METHOD_EXCEPTION,
     // HealthConstants.DEFAULT_EXCEPTION_ID,
     // responseEntity.getStatusCode().name());
     // return new ResponseEntity<ResponseBean>(responseBean,
     // responseEntity.getStatusCode());
   } finally {
     // httpStatusCode = responseEntity.getStatusCode();
     // requestDetails.postRequestValue(httpStatusCode.name());
     methodCallStack.addServiceMethodCallDetails(methodCallDetails);
     healthmeter.apphealth.writeHealthLog((ArtMethodCallStack) methodCallStack.clone());
     Integer existingValue = 0;
     Metric metric = repository.findOne("gauge." + "total.Time " + entityName + "");
     if (metric != null) {
       existingValue = metric.getValue().intValue();
     }
     gaugeservice.submit(
         "total.Time " + entityName + "", executionTimer.getSystemTime + existingValue);
   }
   return responseEntity;
 }
コード例 #27
0
 @Around(value = "allOperation()||athenaServiceOperation()||spartanServiceOperation()")
 @Order(1)
 public Object aroundAdvice1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
   System.out.println(
       "In aroundAdvice Order 1 : Calling method : "
           + proceedingJoinPoint.getSignature().getName());
   HttpServletRequest request =
       ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   ServletWebRequest servletWebRequest = new ServletWebRequest(request);
   HttpServletResponse response = servletWebRequest.getResponse();
   HttpSession session = request.getSession();
   long nextAutoNum = autoRequestId.getAndIncrement();
   methodCallStack.setRequestId(UUID.randomUUID().toString().toUpperCase());
   MethodCallDetails methodCallDetails =
       new MethodCallDetails(
           methodCallStack.getRequestId(),
           HealthConstants.CLASS_TYPE.SERVICE,
           request.getRemoteHost(),
           request.getMethod(),
           proceedingJoinPoint.getTarget().getClass().toString(),
           proceedingJoinPoint.getSignature().getName(),
           loggedInUserId(request),
           getSessionId(request));
   String entityName =
       incrementUricounter(
           proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName(),
           proceedingJoinPoint.getSignature().getName());
   ResponseEntity<ResponseBean> responseEntity = new ResponseEntity<>(HttpStatus.OK);
   /*
    * Needs to get user id from request header and pass it to entityAudit
    * and RuntimeLogInfo
    */
   /* create logging info object (Needs to call from login service only */
   runtimeLogInfoHelper.setCustomerId(getCustomerId(request));
   runtimeLogInfoHelper.createRuntimeLogUserInfo(
       1, loggedInUserId(request), request.getRemoteHost());
   /* validate request */
   try {
     if (request.getHeader("Job-Execution") == null) {
       if (request.getHeader("isBeforeSession") == null) {
         validateRequest(session, request, response);
         if (!sessionValidation.checkIgnoreURL(request)) {
           /** Sets user's last access time in table */
           java.sql.Timestamp currentTime = new java.sql.Timestamp(System.currentTimeMillis());
           loginSessionRepo.updateLastAccessTime(
               loggedInUserId(request), session.getAttribute("usidHash").toString(), currentTime);
           runtimeLogInfoHelper.setUserAccessCode(
               Integer.parseInt(session.getAttribute("userAccessCode").toString()));
         }
       }
     }
     Object obj = proceedingJoinPoint.proceed();
     responseEntity = (ResponseEntity<ResponseBean>) obj;
     httpStatusCode = responseEntity.getStatusCode();
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_NORMAL_EXECUTION, responseEntity.getStatusCode().name());
   } catch (SpartanAccessDeniedException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             " Access Denied " + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanPersistenceException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             " Can not perform Operation on entity:" + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanTransactionException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo(), e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanDataNotFoundException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (com.athena.framework.server.exception.biz.SpartanBusinessValidationFailedException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (Exception e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean responseBean = new ResponseBean();
     responseBean.add("success", false);
     responseBean.add("message", " Access Denied:" + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         HealthConstants.DEFAULT_EXCEPTION_ID,
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(responseBean, responseEntity.getStatusCode());
   } finally {
     /** Sets user's last access time in table */
     /*if (request.getHeader("Job-Execution") == null) {
     if (request.getHeader("isBeforeSession") == null) {
     java.sql.Timestamp currentTime = new java.sql.Timestamp(System.currentTimeMillis());
     loginSessionRepo.updateLastAccessTime(loggedInUserId(request), session.getAttribute("usidHash").toString(), currentTime);
     }
     }*/
     methodCallStack.addServiceMethodCallDetails(methodCallDetails);
     healthmeter.apphealth.writeHealthLog((ArtMethodCallStack) methodCallStack.clone());
     Integer existingValue = 0;
     Metric metric = repository.findOne("gauge." + "total.Time " + entityName + "");
     if (metric != null) {
       existingValue = metric.getValue().intValue();
     }
     gaugeservice.submit(
         "total.Time " + entityName + "", executionTimer.getSystemTime + existingValue);
   }
   return responseEntity;
 }
コード例 #28
0
 private Object doInvoke(final ProceedingJoinPoint thisJoinPoint) throws Throwable {
   System.out.println(
       "Invoking : " + thisJoinPoint + "  " + thisJoinPoint.getTarget().getClass().getName());
   return thisJoinPoint.proceed();
 }
コード例 #29
0
 @Around("allOperation()")
 @Order(1)
 public Object aroundAdvice1(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
   HttpServletRequest request =
       ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
   ServletWebRequest servletWebRequest = new ServletWebRequest(request);
   HttpServletResponse response = servletWebRequest.getResponse();
   HttpSession session = request.getSession();
   long nextAutoNum = autoRequestId.getAndIncrement();
   methodCallStack.setRequestId(UUID.randomUUID().toString().toUpperCase());
   methodCallStack.setAppSessionId(getSessionId(request));
   MethodCallDetails methodCallDetails =
       new MethodCallDetails(
           methodCallStack.getRequestId(),
           methodCallStack.getCallSequence(),
           HealthConstants.CLASS_TYPE.SERVICE,
           request.getRemoteHost(),
           request.getMethod(),
           proceedingJoinPoint.getTarget().getClass().toString(),
           proceedingJoinPoint.getSignature().getName(),
           loggedInUserId(request),
           getSessionId(request));
   String entityName =
       incrementUricounter(
           proceedingJoinPoint.getSignature().getDeclaringType().getSimpleName(),
           proceedingJoinPoint.getSignature().getName());
   ResponseEntity<ResponseBean> responseEntity = new ResponseEntity<>(HttpStatus.OK);
   try {
     serviceLogic(session, request, response);
     Object obj = proceedingJoinPoint.proceed();
     responseEntity = (ResponseEntity<ResponseBean>) obj;
     httpStatusCode = responseEntity.getStatusCode();
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_NORMAL_EXECUTION, responseEntity.getStatusCode().name());
   } catch (SpartanAccessDeniedException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             "Access Denied" + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanPersistenceException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(
             sprinkler,
             runtimeLogInfoHelper.getRuntimeLogInfo(),
             "Can not perform Operation on entity:" + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanTransactionException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (SpartanDataNotFoundException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (com.athena.framework.server.exception.biz.SpartanBusinessValidationFailedException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (com.athena.framework.server.exception.biz.SpartanConstraintViolationException e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         e.getExceptionId(),
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean exceptionbean =
         e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         e.getExceptionId(),
         responseEntity.getStatusCode().name());
     httpStatusCode = HttpStatus.PRECONDITION_FAILED;
     return new ResponseEntity<ResponseBean>(exceptionbean, responseEntity.getStatusCode());
   } catch (Exception e) {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         4005,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         request.getRemoteHost(),
         e);
     ResponseBean responseBean = new ResponseBean();
     responseBean.add("success", false);
     responseBean.add("message", "Access Denied:" + e.getMessage());
     methodCallDetails.setPostCallDetails(
         HealthConstants.METHOD_EXCEPTION,
         HealthConstants.DEFAULT_EXCEPTION_ID,
         responseEntity.getStatusCode().name());
     return new ResponseEntity<ResponseBean>(responseBean, responseEntity.getStatusCode());
   } finally {
     methodCallStack.addMethodCallDetails(methodCallDetails);
     healthmeter.apphealth.writeHealthLog((ArtMethodCallStack) methodCallStack.clone());
     Integer existingValue = 0;
     Metric metric = repository.findOne("gauge." + "total.Time" + entityName + "");
     if (metric != null) {
       existingValue = metric.getValue().intValue();
     }
     gaugeservice.submit(
         "total.Time" + entityName + "", executionTimer.getSystemTime + existingValue);
   }
   return responseEntity;
 }
コード例 #30
0
ファイル: ControllerAop.java プロジェクト: dutao1/feeling
  @Around("anyMethod()")
  public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {

    long start = System.currentTimeMillis();
    StringBuilder methodSB = new StringBuilder();
    String methodName = joinPoint.getSignature().getName();
    String className = joinPoint.getTarget().getClass().getSimpleName();
    boolean paramError = false; // 是否参数不符合要求
    String paramErrorMsg = null; // 对应错误信息
    try {
      methodSB
          .append("execute web method is [")
          .append(className)
          .append(".")
          .append(methodName)
          .append("()],params==[");

      Object[] args = joinPoint.getArgs();
      if (args != null) {
        for (int i = 0; i < args.length; i++) {
          Object obj = args[i];
          if (obj != null) {
            if (obj.getClass().getName().indexOf("com.feeling.vo") < 0) {
              methodSB.append(obj + ",");
            } else {
              methodSB.append(JSON.toJSONString(obj));
            }
            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
              if (!paramError && field.isAnnotationPresent(NotNull.class)) {
                String filedName = field.getName();
                Object result = r.getInvoke(obj, filedName, false);
                if (result == null) {
                  paramErrorMsg = filedName + "不能为空";
                  paramError = true;
                  break;
                }

              } else if (!paramError && field.isAnnotationPresent(NotEmpty.class)) {

                String filedName = field.getName();
                Object result = r.getInvoke(obj, filedName, false);
                NotEmpty notEmpty = field.getAnnotation(NotEmpty.class);
                String desc = notEmpty.desc();
                if (StringUtils.isEmpty(desc)) {
                  desc = filedName;
                }
                if (result == null || result.toString().equals("")) {
                  paramErrorMsg = desc + "不能为空";
                  paramError = true;
                  break;
                } else {

                  int max = notEmpty.maxLength();
                  int min = notEmpty.minLength();
                  if (result.toString().length() < min) {
                    paramErrorMsg = desc + "长度不能小于[" + min + "]";
                    paramError = true;
                    break;
                  } else if (result.toString().length() > max) {
                    paramErrorMsg = desc + "长度不能大于[" + max + "]";
                    paramError = true;
                    break;
                  }
                }
              }
            }
          }
        }
        methodSB.append("]");
      }
      Object retVal = null;
      if (!paramError) {
        retVal = joinPoint.proceed();
        if (retVal != null) {
          methodSB.append(";result==[" + JSON.toJSONString(retVal) + "]");
        } else {
          methodSB.append(";result==[null]");
        }
      } else {
        String message = String.format(ReturnCodeEnum.PARAMETER_ERROR.getMessage(), paramErrorMsg);
        String result =
            new ReturnResult(ReturnCodeEnum.PARAMETER_ERROR.getCode(), message).toString();
        methodSB.append(";result==[" + result + "]");
        retVal = result;
      }
      return retVal;
    } catch (OptException ex) {
      //	LogInfo.WEB_LOG.error("LogAop->doAround;", methodSB.toString()+"; error is
      // "+ex.getMessage());
      String result = new ReturnResult(ex.getCode(), ex.getMessage()).toString();
      methodSB.append(";result==[" + result + "]");
      return result;
    } catch (Throwable e) {
      String result =
          new ReturnResult(ReturnCodeEnum.ERROR.getCode(), ReturnCodeEnum.ERROR.getMessage())
              .toString();
      LogInfo.WEB_LOG.error(
          "LogAop->doAround; had error , error is++++++++++[" + e.getMessage() + "]");
      methodSB.append(";result==[" + result + "]");
      return result;
    } finally {
      long end = System.currentTimeMillis();
      long expendTime = end - start;
      methodSB.append(";use time is [" + expendTime + "]ms ");
      LogInfo.WEB_LOG.info(methodSB.toString());
    }
  }