@Around("loggingPointcut()")
  public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
    if (log.isDebugEnabled()) {
      log.debug(
          "Enter: {}.{}() with argument[s] = {}",
          joinPoint.getSignature().getDeclaringTypeName(),
          joinPoint.getSignature().getName(),
          Arrays.toString(joinPoint.getArgs()));
    }
    try {
      Object result = joinPoint.proceed();
      if (log.isDebugEnabled()) {
        log.debug(
            "Exit: {}.{}() with result = {}",
            joinPoint.getSignature().getDeclaringTypeName(),
            joinPoint.getSignature().getName(),
            result);
      }
      return result;
    } catch (IllegalArgumentException e) {
      log.error(
          "Illegal argument: {} in {}.{}()",
          Arrays.toString(joinPoint.getArgs()),
          joinPoint.getSignature().getDeclaringTypeName(),
          joinPoint.getSignature().getName());

      throw e;
    }
  }
示例#2
0
  @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;
  }
 @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(value = "deleteOperation()||athenaServiceOperation()||spartanServiceOperation()")
 @Order(2)
 public Object aroundAdvice2Delete(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
   System.out.println(
       "In aroundAdvice Order 2 Delete: Calling method : "
           + proceedingJoinPoint.getSignature().getName());
   Object returnObject = new Object();
   if (proceedingJoinPoint.getArgs().length > 0) {
     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;
 }
 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);
           }
         }
       }
     }
   }
 }
 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(
     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;
 }
示例#8
0
	@Around(value = "updateOperation()")
	@Order(2)
	public Object aroundAdvice2Update(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
		System.out.println("In aroundAdvice Order 2 Update: Calling method : " + proceedingJoinPoint.getSignature().getName());
		boolean isValidEntity = true;
		Object returnObject = new Object();
		if (proceedingJoinPoint.getArgs().length > 0) {
			Object methodInputParam = proceedingJoinPoint.getArgs()[0];
			if (methodInputParam != null && methodInputParam instanceof CommonEntityInterface) {
				CommonEntityInterface entity = (CommonEntityInterface) methodInputParam;
				try {
					preSaveUpdateOperation(entity, CommonEntityInterface.RECORD_TYPE.UPDATE);
				} catch (SpartanConstraintViolationException e) {
					isValidEntity = false;
					sprinkler.logger.log(runtimeLogInfoHelper.getRuntimeLogInfo(), 2008, e);
					ResponseBean exceptionbean = e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo(), "Constraints violated by input "
							+ methodInputParam.getClass().getSimpleName());
					return new ResponseEntity<ResponseBean>(exceptionbean, e.getHttpStatus());
				}
			} 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 object : listOfEntities) {
							CommonEntityInterface entity = (CommonEntityInterface) object;
							try {
								preSaveUpdateOperation(entity, CommonEntityInterface.RECORD_TYPE.UPDATE);
							} catch (SpartanConstraintViolationException e) {
								isValidEntity = false;
								sprinkler.logger.log(runtimeLogInfoHelper.getRuntimeLogInfo(), 2008, e);
								ResponseBean exceptionbean = e.prepareExceptionBean(sprinkler, runtimeLogInfoHelper.getRuntimeLogInfo(), "Constraints violated by input "
										+ methodInputParam.getClass().getSimpleName());
								return new ResponseEntity<ResponseBean>(exceptionbean, e.getHttpStatus());
							}
						}
					}
				}
			}
		}
		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;
	}
示例#9
0
  // 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);
  }
示例#10
0
  @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);
  }
示例#11
0
 @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;
 }
示例#12
0
  /**
   * 取得field中spel表达是的值
   *
   * @param pjp
   * @param field
   * @return
   */
  private String getSpelKey(ProceedingJoinPoint pjp, String field) {
    Method method = getMethod(pjp);
    Object[] args = pjp.getArgs();
    // String field = cache.field();

    if (StringUtils.isEmpty(field)) {
      LOGGER.error(
          "method {}.{}'s annotation field is empty. This may be an error.",
          method.getClass(),
          method.getName());
    }
    LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();

    String[] paraNameArr = u.getParameterNames(method);

    // 应用SPEL进行key的解析

    ExpressionParser parser = new SpelExpressionParser();

    // SPEL高低文

    StandardEvaluationContext context = new StandardEvaluationContext();

    // 把办法参数放入SPEL高低文中

    for (int i = 0; i < paraNameArr.length; i++) {
      context.setVariable(paraNameArr[i], args[i]);
    }
    if (field.contains(",")) {
      return getKeyForStr(parser, context, field);
    }
    String value = parser.parseExpression(field).getValue(context, String.class);
    return value;
  }
 /** 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("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;
  }
  @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;
  }
 @Test
 public void shouldNoProceedWithValidationErrors() throws Throwable {
   given(Boolean.valueOf(checkoutStep.checkIfValidationErrors(ValidationResults.FAILED)))
       .willReturn(Boolean.TRUE);
   given(checkoutStep.validate((RedirectAttributesModelMap) pjp.getArgs()[1]))
       .willReturn(ValidationResults.FAILED);
   Assert.assertTrue(checkoutStepValidationAspect.validateCheckoutStep(pjp).equals(FAILURE));
 }
示例#17
0
 @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;
 }
示例#18
0
 @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(
     value =
         "findOperation()||getOperation()||athenaServiceOperation()||spartanServiceOperation()")
 @Order(2)
 protected Object aroundAdvicefindOperation(ProceedingJoinPoint proceedingJoinPoint)
     throws Throwable {
   System.out.println(
       "In aroundOperation Order 2 find*: Calling method : "
           + proceedingJoinPoint.getSignature().getName());
   Object returnObject = new Object();
   if (proceedingJoinPoint.getArgs().length > 0) {
     Object methodInputParam = proceedingJoinPoint.getArgs()[0];
     if (methodInputParam != null) {
       sprinkler.logger.log(
           runtimeLogInfoHelper.getRuntimeLogInfo(),
           1000,
           proceedingJoinPoint.getSignature().getDeclaringTypeName(),
           proceedingJoinPoint.getSignature().getName(),
           methodInputParam.getClass().getSimpleName(),
           methodInputParam.toString());
       returnObject = proceedingJoinPoint.proceed();
       sprinkler.logger.log(
           runtimeLogInfoHelper.getRuntimeLogInfo(),
           1001,
           proceedingJoinPoint.getSignature().getDeclaringTypeName(),
           proceedingJoinPoint.getSignature().getName(),
           methodInputParam.toString());
     }
   } else {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         1000,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         "none",
         "none");
     returnObject = proceedingJoinPoint.proceed();
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         1001,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         "none");
   }
   return returnObject;
 }
示例#20
0
  @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();
  }
示例#21
0
 /**
  * Type of arguments of an executed method
  *
  * @param proceedPoint The method to be invoked from aspect advice
  * @return String arguments
  */
 public String arguments(ProceedingJoinPoint proceedPoint) {
   StringBuilder arguments = new StringBuilder();
   for (int i = 0; i < proceedPoint.getArgs().length; i++) {
     MethodSignature sig = (MethodSignature) proceedPoint.getSignature();
     String methodArgument = "";
     if (proceedPoint.getArgs()[i].toString().contains("->")) {
       methodArgument = proceedPoint.getArgs()[i].toString().split("->")[1].replace("]", "");
     } else {
       methodArgument = proceedPoint.getArgs()[i].toString();
     }
     arguments.append(
         "(" + sig.getParameterNames()[i].toString() + " ---> " + methodArgument + ") ");
   }
   if (arguments.toString().isEmpty()) {
     return "";
   } else {
     return arguments.toString().trim();
   }
 }
示例#22
0
  @Around(value = "userServicePointcut() && cacheablePointcut()")
  public Object cacheableAdvice(ProceedingJoinPoint pjp) throws Throwable {

    String methodName = pjp.getSignature().getName();
    Object arg = pjp.getArgs().length >= 1 ? pjp.getArgs()[0] : null;

    String key = "";
    boolean isIdKey = false;
    if ("findOne".equals(methodName)) {
      key = idKey(String.valueOf(arg));
      isIdKey = true;
    } else if ("findByUsername".equals(methodName)) {
      key = usernameKey((String) arg);
    } else if ("findByEmail".equals(methodName)) {
      key = emailKey((String) arg);
    } else if ("findByMobilePhoneNumber".equals(methodName)) {
      key = mobilePhoneNumberKey((String) arg);
    }

    User user = null;
    if (isIdKey == true) {
      user = get(key);
    } else {
      Long id = get(key);
      if (id != null) {
        key = idKey(String.valueOf(id));
        user = get(key);
      }
    }
    // cache hit
    if (user != null) {
      log.debug("cacheName:{}, hit key:{}", cacheName, key);
      return user;
    }
    log.debug("cacheName:{}, miss key:{}", cacheName, key);

    // cache miss
    user = (User) pjp.proceed();

    // put cache
    put(user);
    return user;
  }
示例#23
0
  @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();
  }
示例#24
0
  public Object proxy(ProceedingJoinPoint call) throws Throwable {
    log.trace("PROXY.IN");

    try {

      if (call.getArgs().length > 0 && paperProxyMap.containsKey(call.getArgs()[0])) {
        log.info("ProxyMap" + paperProxyMap);

        return paperProxyMap.get(call.getArgs()[0]);
      }

      Object returned = call.proceed();
      if (returned instanceof Paper) {
        paperProxyMap.put(((Paper) returned).getId(), (Paper) returned);
      }
      return returned;
    } finally {
      log.trace("PROXY.OUT");
    }
  }
示例#25
0
 /**
  * 获取被拦截方法对象
  *
  * <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;
 }
 @Around("findOperation()||getOperation()")
 @Order(2)
 public Object aroundAdvicefindOperation(ProceedingJoinPoint proceedingJoinPoint)
     throws Throwable {
   Object returnObject = new Object();
   if (proceedingJoinPoint.getArgs().length > 0) {
     Object methodInputParam = proceedingJoinPoint.getArgs()[0];
     if (methodInputParam != null) {
       sprinkler.logger.log(
           runtimeLogInfoHelper.getRuntimeLogInfo(),
           1000,
           proceedingJoinPoint.getSignature().getDeclaringTypeName(),
           proceedingJoinPoint.getSignature().getName(),
           methodInputParam.getClass().getSimpleName(),
           methodInputParam.toString());
       returnObject = proceedingJoinPoint.proceed();
       sprinkler.logger.log(
           runtimeLogInfoHelper.getRuntimeLogInfo(),
           1001,
           proceedingJoinPoint.getSignature().getDeclaringTypeName(),
           proceedingJoinPoint.getSignature().getName(),
           methodInputParam.toString());
     }
   } else {
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         1000,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         "none",
         "none");
     returnObject = proceedingJoinPoint.proceed();
     sprinkler.logger.log(
         runtimeLogInfoHelper.getRuntimeLogInfo(),
         1001,
         proceedingJoinPoint.getSignature().getDeclaringTypeName(),
         proceedingJoinPoint.getSignature().getName(),
         "none");
   }
   return returnObject;
 }
 @Around("execution(* *.*(..))")
 public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
   log.info(
       "The method "
           + joinPoint.getSignature().getName()
           + "() begins with "
           + Arrays.toString(joinPoint.getArgs()));
   try {
     Object result = joinPoint.proceed();
     log.info("The method " + joinPoint.getSignature().getName() + "() ends with " + result);
     return result;
   } catch (IllegalArgumentException e) {
     log.error(
         "Illegal argument "
             + Arrays.toString(joinPoint.getArgs())
             + " in "
             + joinPoint.getSignature().getName()
             + "()");
     throw e;
   }
 }
  private void setupPjp() throws Throwable {
    final MethodSignature signature = Mockito.mock(MethodSignature.class);
    final Method testMethod = this.getClass().getMethod("annotatedMethod");
    given(signature.getMethod()).willReturn(testMethod);

    given(pjp.getSignature()).willReturn(signature);
    given(pjp.proceed()).willReturn(PROCEED);

    final Object[] args = new Object[2];
    args[1] = Mockito.mock(RedirectAttributesModelMap.class);
    given(pjp.getArgs()).willReturn(args);
  }
示例#29
0
  @Around("execution(* com.spring.aop.aspectj.CustomerBo.addCustomerAround(..))")
  public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {

    System.out.println("logAround() is running!");
    System.out.println("hijacked method : " + joinPoint.getSignature().getName());
    System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));

    System.out.println("Around before is running!");
    joinPoint.proceed(); // continue on the intercepted method
    System.out.println("Around after is running!");

    System.out.println("******");
  }
 @Around("createIndicacao()")
 public Object createIndicacaoMethodInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
   Object[] args = joinPoint.getArgs();
   IndicacaoDTO indicacao = (IndicacaoDTO) args[0];
   TurmaEfetivaDTO turma = atividadesEnsinoService.findTurmaEfetiva(indicacao.getTurma().getId());
   SimpleDateFormat df = new SimpleDateFormat("yyyy");
   String exercicio = df.format(turma.getExercicio());
   String organizacao = turma.getOrganizacaoGestoraId().toString();
   String key = exercicio + "-" + organizacao;
   clearChacheTurmas(key);
   clearChachePendencias(key);
   return joinPoint.proceed();
 }