Exemple #1
0
 /**
  * Unwraps a join point that may be nested due to layered proxies.
  *
  * @param point Join point to unwrap.
  * @return Innermost join point; if not nested, simply returns the argument.
  */
 public static JoinPoint unWrapJoinPoint(final JoinPoint point) {
   JoinPoint naked = point;
   while (naked.getArgs().length > 0 && naked.getArgs()[0] instanceof JoinPoint) {
     naked = (JoinPoint) naked.getArgs()[0];
   }
   return naked;
 }
  @AfterReturning(
      value = "@annotation(com.kcp.platform.common.log.annotation.Log)",
      returning = "returnVal")
  public void logAfterReturning(JoinPoint pjp, Object returnVal) throws Throwable {
    try {
      if (pjp.toLongString().equals(SqlContextHolder.getJoinPoint())) {
        MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
        Method method = joinPointObject.getMethod();
        MethodSysLogDefinition definition = parser.parseLogAnnotation(method);

        String logType = definition.getType();
        String moduleName = definition.getModuleName();
        String operateDesc = definition.getOperateDesc();
        String operateContent = SqlContextHolder.getSql();
        if (definition.isUseSpel()) {
          /** 对日志描述和日志备注加入SPEL支持 */
          LogOperationContext context =
              getOperationContext(definition, method, pjp.getArgs(), pjp.getClass());
          operateDesc = context.desc();
        }
        Logger.getInstance().addSysLog(logType, operateContent, moduleName, operateDesc);
        SqlContextHolder.clear();
      }
    } catch (Exception e) {
      logger.error("记录系统操作日志失败", e);
    }
  }
  public List<String> getOwners(final JoinPoint joinPoint) {
    final List<String> owners = new ArrayList<>();
    final MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    final Object[] parameterValues = joinPoint.getArgs();
    final Class[] parameterTypes = signature.getParameterTypes();

    final Annotation[][] parameterAnnotations = signature.getMethod().getParameterAnnotations();
    for (int i = 0; i < parameterAnnotations.length; i++) {
      final OwnerParam paramAnnotation =
          getAnnotationByType(parameterAnnotations[i], OwnerParam.class);
      if (paramAnnotation != null) {
        if (paramAnnotation.getter().isEmpty()) {
          if (String.class.equals(parameterTypes[i])) {
            final String owner = (String) parameterValues[i];
            owners.add(owner);
          }
        } else {
          final String owner =
              callGetter(parameterValues[i], paramAnnotation.getter(), String.class);
          owners.add(owner);
        }
      }
    }
    return owners;
  }
  /** Test case where the current user has both the namespace and the appropriate permissions. */
  @Test
  public void checkPermissionAssertNoExceptionWhenHasPermissions() throws Exception {
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser
        .getNamespaceAuthorizations()
        .add(new NamespaceAuthorization("foo", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext()
        .setAuthentication(
            new TestingAuthenticationToken(
                new SecurityUserWrapper(
                    userId, "", false, false, false, false, Arrays.asList(), applicationUser),
                null));

    try {
      namespaceSecurityAdvice.checkPermission(joinPoint);
    } catch (AccessDeniedException e) {
      fail();
    }
  }
  @Test
  public void checkPermissionAssertAccessDeniedWhenPrincipalIsNull() throws Exception {
    // Mock a join point of the method call
    // mockMethod("foo");
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method = NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", String.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"namespace"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {"foo"});

    SecurityContextHolder.getContext()
        .setAuthentication(new TestingAuthenticationToken(null, null));

    try {
      namespaceSecurityAdvice.checkPermission(joinPoint);
      fail();
    } catch (Exception e) {
      assertEquals(AccessDeniedException.class, e.getClass());
      assertEquals(
          "Current user does not have \"[READ]\" permission(s) to the namespace \"foo\"",
          e.getMessage());
    }
  }
  @Test
  public void checkPermissionAssertErrorWhenAnnotationFieldRefersToNonString() throws Exception {
    // Mock a join point of the method call
    // mockMethod(1);
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method =
        NamespaceSecurityAdviceTest.class.getDeclaredMethod("mockMethod", Integer.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"aNumber"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    when(joinPoint.getArgs()).thenReturn(new Object[] {1});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    SecurityContextHolder.getContext()
        .setAuthentication(
            new TestingAuthenticationToken(
                new SecurityUserWrapper(
                    userId, "", false, false, false, false, Arrays.asList(), applicationUser),
                null));

    try {
      namespaceSecurityAdvice.checkPermission(joinPoint);
      fail();
    } catch (Exception e) {
      assertEquals(IllegalStateException.class, e.getClass());
      assertEquals(
          "Object must be of type class java.lang.String or interface java.util.Collection. Actual object.class = class java.lang.Integer",
          e.getMessage());
    }
  }
  @AfterReturning(
      pointcut =
          "execution(public String at.ac.tuwien.infosys.jcloudscale.server.JCloudScaleServer.createNewCloudObject(..))",
      returning = "ret")
  public void matchObjectCreated(JoinPoint jp, String ret) throws JCloudScaleException {

    try {
      ObjectCreatedEvent event = new ObjectCreatedEvent();
      initializeBaseEventProperties(event);
      UUID objectId = UUID.fromString(ret);
      event.setObjectId(objectId);
      JCloudScaleServer server = (JCloudScaleServer) jp.getThis();
      // XXX AbstractJCloudScaleServerRunner
      // UUID serverId = JCloudScaleServerRunner.getInstance().getId();
      UUID serverId = AbstractJCloudScaleServerRunner.getInstance().getId();
      event.setHostId(serverId);
      ClassLoader cl = server.getCloudObjectClassLoader(objectId);
      Class<?> theClazz = Class.forName((String) (jp.getArgs()[0]), true, cl);
      event.setObjectType(theClazz);
      getMqHelper().sendEvent(event);
      log.finer("Sent object created for object " + objectId.toString());
    } catch (Exception e) {
      e.printStackTrace();
      log.severe("Error while triggering ObjectCreatedEvent: " + e.getMessage());
    }
  }
  @Test
  public void checkPermissionAssertAccessDeniedWhenComplexCaseAndUserHasWrongPermission()
      throws Exception {
    // Mock a join point of the method call
    // mockMethod(request);
    JoinPoint joinPoint = mock(JoinPoint.class);
    MethodSignature methodSignature = mock(MethodSignature.class);
    Method method =
        NamespaceSecurityAdviceTest.class.getDeclaredMethod(
            "mockMethod", BusinessObjectDataNotificationRegistrationCreateRequest.class);
    when(methodSignature.getParameterNames()).thenReturn(new String[] {"request"});
    when(methodSignature.getMethod()).thenReturn(method);
    when(joinPoint.getSignature()).thenReturn(methodSignature);
    BusinessObjectDataNotificationRegistrationCreateRequest request =
        new BusinessObjectDataNotificationRegistrationCreateRequest();
    request.setBusinessObjectDataNotificationRegistrationKey(
        new NotificationRegistrationKey("ns1", null));
    request.setBusinessObjectDataNotificationFilter(
        new BusinessObjectDataNotificationFilter("ns2", null, null, null, null, null, null, null));
    request.setJobActions(
        Arrays.asList(new JobAction("ns3", null, null), new JobAction("ns4", null, null)));
    when(joinPoint.getArgs()).thenReturn(new Object[] {request});

    String userId = "userId";
    ApplicationUser applicationUser = new ApplicationUser(getClass());
    applicationUser.setUserId(userId);
    applicationUser.setNamespaceAuthorizations(new HashSet<>());
    applicationUser
        .getNamespaceAuthorizations()
        .add(new NamespaceAuthorization("ns1", Arrays.asList(NamespacePermissionEnum.WRITE)));
    applicationUser
        .getNamespaceAuthorizations()
        .add(new NamespaceAuthorization("ns2", Arrays.asList(NamespacePermissionEnum.READ)));
    applicationUser
        .getNamespaceAuthorizations()
        .add(new NamespaceAuthorization("ns3", Arrays.asList(NamespacePermissionEnum.EXECUTE)));
    // User does not have the expected EXECUTE permission on ns4
    applicationUser
        .getNamespaceAuthorizations()
        .add(new NamespaceAuthorization("ns4", Arrays.asList(NamespacePermissionEnum.READ)));
    SecurityContextHolder.getContext()
        .setAuthentication(
            new TestingAuthenticationToken(
                new SecurityUserWrapper(
                    userId, "", false, false, false, false, Arrays.asList(), applicationUser),
                null));

    try {
      namespaceSecurityAdvice.checkPermission(joinPoint);
      fail();
    } catch (Exception e) {
      assertEquals(AccessDeniedException.class, e.getClass());
      assertEquals(
          String.format(
              "User \"%s\" does not have \"[EXECUTE]\" permission(s) to the namespace \"ns4\"",
              userId),
          e.getMessage());
    }
  }
 /**
  * 变量初始化
  *
  * @param joinPoint
  */
 private void initService(JoinPoint joinPoint) {
   Object[] args = joinPoint.getArgs();
   DataExchangeService target = (DataExchangeService) joinPoint.getTarget();
   MainParamVo params = (MainParamVo) args[0];
   // resultInfo = params.resultInfo;
   target.init(params);
   checkService.init(params);
 }
 @Before("CalculatorPointcuts.loggingOperation()")
 public void logBefore(JoinPoint joinPoint) {
   log.info(
       "The method "
           + joinPoint.getSignature().getName()
           + "() begins with "
           + Arrays.toString(joinPoint.getArgs()));
 }
Exemple #11
0
 public void before(JoinPoint jp) {
   // メソッド開始時にWeavingするAdvice
   System.out.println("Hello Before! *** メソッドが呼ばれる前に出てくるよ!");
   Signature sig = jp.getSignature();
   System.out.println("-----> メソッド名を取得するよ:" + sig.getName());
   Object[] o = jp.getArgs();
   System.out.println("-----> 仮引数の値を取得するよ:" + o[0]);
 }
 @AfterThrowing(pointcut = "CalculatorPointcuts.loggingOperation()", throwing = "e")
 public void logAfterThrowing(JoinPoint joinPoint, IllegalArgumentException e) {
   log.error(
       "Illegal argument "
           + Arrays.toString(joinPoint.getArgs())
           + " in "
           + joinPoint.getSignature().getName()
           + "()");
 }
 @Before("execution(* *.*(..))")
 public void logJoinPoint(JoinPoint joinPoint) {
   log.info("Join point kind : " + joinPoint.getKind());
   log.info("Signature declaring type : " + joinPoint.getSignature().getDeclaringTypeName());
   log.info("Signature name : " + joinPoint.getSignature().getName());
   log.info("Arguments : " + Arrays.toString(joinPoint.getArgs()));
   log.info("Target class : " + joinPoint.getTarget().getClass().getName());
   log.info("This class : " + joinPoint.getThis().getClass().getName());
 }
Exemple #14
0
 public void afterReturning(JoinPoint jp, Product product) {
   // メソッド呼出が例外の送出なしに終了した際に呼ばれるAdvice
   System.out.println("Hello AfterReturning! *** メソッドを呼んだ後に出てくるよ");
   // System.out.println("-----> return value = " + ret);
   Signature sig = jp.getSignature();
   System.out.println("-----> メソッド名を取得するよ:" + sig.getName());
   Object[] o = jp.getArgs();
   System.out.println("-----> 仮引数の値を取得するよ:" + o[0]);
 }
 public void enter(JoinPoint joinPoint) {
   String method = joinPoint.getSignature().toLongString();
   Object[] arguments = joinPoint.getArgs();
   Object target = joinPoint.getTarget();
   LOG.debug(
       String.format(
           "Method '%1$s' entered with arguments %2$s on target %3$s",
           method, Arrays.asList(arguments), target));
 }
 @AfterReturning(
     "execution(* org.osforce.connect.service.gallery.PhotoService.createPhoto(..)) ||"
         + "execution(* org.osforce.connect.service.gallery.PhotoService.updatePhoto(..))")
 public void updatePhoto(JoinPoint jp) {
   Photo photo = (Photo) jp.getArgs()[0];
   Map<Object, Object> context = CollectionUtil.newHashMap();
   context.put("photoId", photo.getId());
   context.put("template", TEMPLATE_PHOTO_UPDATE);
   photoActivityStreamTask.doAsyncTask(context);
 }
 @AfterReturning(
     "execution(* org.osforce.connect.service.gallery.AlbumService.createAlbum(..)) ||"
         + "execution(* org.osforce.connect.service.gallery.AlbumService.updateAlbum(..))")
 public void updateAlbum(JoinPoint jp) {
   Album album = (Album) jp.getArgs()[0];
   Map<Object, Object> context = CollectionUtil.newHashMap();
   context.put("albumId", album.getId());
   context.put("template", TEMPLATE_ALBUM_UPDATE);
   albumActivityStreamTask.doAsyncTask(context);
 }
 /**
  * After 核心业务逻辑退出后(包括正常执行结束和异常退出),执行此Advice
  *
  * <p>有参的日志方法
  *
  * <p>此处意在执行核心业务逻辑之后,做一些日志记录操作等等 可通过joinPoint来获取所需要的内容
  *
  * @param point
  */
 public void afterAdvice(JoinPoint point) {
   Object[] args = point.getArgs();
   System.out.println("目标参数列表:");
   if (args != null) {
     for (Object obj : args) {
       System.out.println(obj + ",");
     }
     System.out.println();
   }
 }
 /**
  * AfterReturning 核心业务逻辑调用正常退出后,不管是否有返回值,正常退出后,均执行此Advice
  *
  * <p>有参有返回值的方法
  *
  * <p>此处可以对返回值做进一步处理 可通过joinPoint来获取所需要的内容
  *
  * @param point
  * @param returnObj
  */
 public void afterReturningAdvice(JoinPoint point, Object returnObj) {
   Object[] args = point.getArgs();
   System.out.println("目标参数列表:");
   if (args != null) {
     for (Object obj : args) {
       System.out.println(obj + ",");
     }
     System.out.println();
     System.out.println("执行结果是:" + returnObj);
   }
 }
 @AfterReturning(
     pointcut =
         "execution(* com.epam.practice.services.discount.impl.DiscountServiceImpl.getPrice(..))",
     returning = "result")
 public void discountCount(JoinPoint joinPoint, BigDecimal result) {
   for (StackTraceElement stackTraceElement : Thread.currentThread().getStackTrace()) {
     if (stackTraceElement.getClassName().contains(CLASS_NAME)
         && stackTraceElement.getMethodName().contains(METHOD_NAME)) {
       User user = (User) joinPoint.getArgs()[1];
       BigDecimal price = (BigDecimal) joinPoint.getArgs()[2];
       for (DiscountStrategy discountStrategy : discountStrategies) {
         BigDecimal tmpPrice = discountStrategy.getDiscount(user, price);
         if (tmpPrice.equals(result) && !price.equals(tmpPrice)) {
           statisticDAO.addDiscountStrategy(discountStrategy.getClass().getName());
         }
       }
       break;
     }
   }
 }
Exemple #21
0
 public static Object proceedAroundCallAtAspectJ(JoinPoint thisJoinPoint) throws Throwable {
   Object ret = null;
   Object args[] = thisJoinPoint.getArgs();
   if (args.length > 0) {
     int proceedIndex = (args.length - 1);
     if (args[proceedIndex] instanceof ProceedingJoinPoint) {
       ret = ((ProceedingJoinPoint) args[proceedIndex]).proceed();
     }
   }
   return ret;
 }
 // @Before("execution(* getImages())")
 @Before("execution(* getAbrSummary(*))")
 public void logBefore(JoinPoint joinPoint) {
   logger =
       Logger.getLogger(
           ""
               + joinPoint.getTarget().getClass().getName()
               + "."
               + joinPoint.getSignature().getName());
   logger.info("***************************************");
   logger.info("service called");
   logger.info("Arguments - " + getStringForArgs(joinPoint.getArgs()));
 }
Exemple #23
0
 /**
  * Public ctor.
  *
  * @param point Joint point
  */
 Key(final JoinPoint point) {
   this.start = System.currentTimeMillis();
   this.accessed = new AtomicInteger();
   this.method = MethodSignature.class.cast(point.getSignature()).getMethod();
   this.target = MethodCacher.Key.targetize(point);
   this.arguments = point.getArgs();
   if (this.method.isAnnotationPresent(Loggable.class)) {
     this.level = this.method.getAnnotation(Loggable.class).value();
   } else {
     this.level = Loggable.DEBUG;
   }
 }
  //	@Before("execution(public * com.spring.service.UserService.findUserById(..)) &&
  // args(com.flipswap.domain.Item,..)")
  @Before("execution(public * com.spring.service.UserService.findUserById(..))")
  public void logBefore(JoinPoint joinPoint) {

    Object[] methodArgs = joinPoint.getArgs();
    Long userId = (Long) methodArgs[0];
    String password = (String) methodArgs[1];
    System.out.println("userId @@ " + userId + " Password @@ " + password);

    System.out.println("logBefore() is running!");
    System.out.println("hijacked : " + joinPoint.getSignature().getName());
    System.out.println("******");
  }
Exemple #25
0
  @Before("execution(public * org.fluidlearn.*.*(..))")
  // Log prima delle invocazioni di un metodo
  public void before(JoinPoint jp) {

    System.out.println(
        "[DEBUG-before] "
            + "\tpackage: "
            + jp.getTarget().getClass()
            + "."
            + jp.getSignature().getName()
            + "\n\tArgomenti: "
            + Arrays.toString(jp.getArgs()));
  }
  @AfterReturning(value = "methodCallThree()", returning = "aValue")
  public void afterReturingAdvice(JoinPoint joinPoint, int aValue) {
    logger.info(
        "LoggingAfterReturn Call ClassName: " + joinPoint.getTarget().getClass().getSimpleName());
    logger.info("LoggingAfterReturn Call MethodName: " + joinPoint.getSignature().getName());
    logger.info("LoggingAfterReturn Call aValue: " + aValue);

    Object[] objs = joinPoint.getArgs();

    for (int i = 0; i < objs.length; i++) {
      logger.info("objs[" + i + "] -->" + objs[i]);
    }
  }
 /**
  * 拦截时间
  *
  * @param jp
  */
 @Before("serviceExecution()")
 public void setDynamicDataSource(JoinPoint jp) {
   Object[] objs = jp.getArgs();
   // 默认第一个参数 代表当前业务类需要的数据源的类型的简称
   String dsName = objs[0].toString();
   if (dsName.equals("userDs")) {
     DBContextUtil.setDbTypeName(DBContextUtil.DATA_SOURCE_USER);
   } else if (dsName.equals("dbDs")) {
     DBContextUtil.setDbTypeName(DBContextUtil.DATA_SOURCE_DS);
   } else {
     DBContextUtil.setDbTypeName(DBContextUtil.DATA_SOURCE_USER);
   }
 }
Exemple #28
0
 public static Object proceedAroundCall(JoinPoint thisJoinPoint) throws Throwable {
   Object ret = null;
   Object[] args = thisJoinPoint.getArgs();
   if (args.length > 0) {
     int i = (args.length - 1);
     if (args[i] instanceof AroundClosure) {
       ret = ((AroundClosure) args[i]).run(args);
     }
   }
   for (Object object : args) {
     System.out.println(object);
   }
   return ret;
 }
Exemple #29
0
  public void updateIndex(JoinPoint jp) {
    this.logger.info("被代理方法名字:" + jp.getSignature().getName());
    this.logger.info("被代理方法参数:" + jp.getArgs());
    this.logger.info("被代理对象:" + jp.getTarget());

    Object object = null;
    if (jp.getArgs().length > 0) {
      object = jp.getArgs()[0];
    }
    if (object == null) {
      return;
    }
    try {
      HttpSolrServer server = new HttpSolrServer(this.solrServerUrl);
      SolrInputDocument doc = new SolrInputDocument();
      doc.addField("id", getAttrValueByKey(object, "id"));
      doc.addField("title", getAttrValueByKey(object, "title"));
      doc.addField("url", getAttrValueByKey(object, "imgLarge"));
      doc.addField("rtype", "goods");
      doc.addField("num", getAttrValueByKey(object, "goodsNumber"));
      doc.addField("last_modified", getAttrValueByKey(object, "gmtCreate"));
      doc.addField("catid", getAttrValueByKey(object, "catCode"));
      doc.addField("memo", getAttrValueByKey(object, "goodsDesc"));
      doc.addField("shopid", "10001");
      doc.addField("shopname", "我的测试店铺");
      if ((doc.getField("id") != null) && (doc.getField("title") != null)) {
        server.add(doc);
        server.commit();
        this.logger.info("实体保存后更新索引,名称为:" + doc.getField("title") + ".");
      } else {
        this.logger.error("实体未找到构建索引所需要的属性!");
      }
    } catch (Exception e) {
      e.printStackTrace();
      this.logger.error("更新索引失败.");
    }
  }
  /**
   * Helper to find the first {@link HttpServletRequest} in the method being called.
   *
   * @param jp The joinpoint
   * @return The first {@link HttpServletRequest} arg.
   */
  private HttpServletRequest findRequest(JoinPoint jp) {
    HttpServletRequest ret = null;

    Object[] args = jp.getArgs();
    if (args != null) {
      for (int i = 0; i < args.length; i++) {
        if (args[i] instanceof HttpServletRequest) {
          ret = (HttpServletRequest) args[i];
          break;
        }
      }
    }

    return ret;
  }