private String getFullMethodInfo(InvocationContext ic) {
   StringBuilder sb = new StringBuilder();
   sb.append(ic.getMethod().getDeclaringClass().getName());
   sb.append(":");
   sb.append(ic.getMethod().getName());
   return sb.toString();
 }
Пример #2
0
 @AroundInvoke
 public Object invoke(InvocationContext ctx) throws Exception {
   Object[] params = ctx.getParameters();
   Secured secureAnnotation = ctx.getMethod().getAnnotation(Secured.class);
   if (params.length > 0) {
     // just verify first attribute
     Object param = params[0];
     SecuredEntity se = param.getClass().getAnnotation(SecuredEntity.class);
     if (se != null && param instanceof Entity<?>) {
       Entity<?> entity = (Entity<?>) param;
       if (entity.getId() == null) {
         // create mode, need to verify parent entity
         entity = (Entity<?>) PropertyUtils.getProperty(entity, se.parent());
       }
       if (!authorizationService.isUserAuthorizedFor(secureAnnotation.accessType(), entity)) {
         throw new org.perfrepo.web.security.SecurityException(
             "securityException.permissionDenied",
             ctx.getMethod().getName(),
             param.getClass().getSimpleName(),
             ((Entity<?>) param).getId().toString());
       }
     }
   }
   return ctx.proceed();
 }
Пример #3
0
 @AroundInvoke
 public Object manageTransaction(InvocationContext ctx) throws Exception {
   System.out.println(
       "before call to " + ctx.getMethod() + " with args " + Arrays.toString(ctx.getParameters()));
   Object returnMe = ctx.proceed();
   System.out.println("after call to " + ctx.getMethod() + " returned " + returnMe);
   return returnMe;
 }
Пример #4
0
 @AroundInvoke
 public Object logMethod(InvocationContext ic) throws Exception {
   logger.entering(ic.getTarget().getClass().getName(), ic.getMethod().getName());
   try {
     return ic.proceed();
   } finally {
     logger.exiting(ic.getTarget().getClass().getName(), ic.getMethod().getName());
   }
 }
  @AroundInvoke
  public Object checkArguments(InvocationContext ctx) throws Exception {
    try {
      log = Logger.getLogger(LogoutInterceptor.class);
      Object[] args = ctx.getParameters();
      String className = ctx.getTarget().getClass().getSimpleName();
      log.trace("Class name: " + className);
      String methodName = ctx.getMethod().getName();
      log.trace("Method: " + methodName);

      String sessionId = (String) args[0];
      if ((sessionId == null) || (sessionId.length() == 0)) {
        throw new Exception("sessionId should not be null");
      }

      cf = (QueueConnectionFactory) new InitialContext().lookup(QueueNames.CONNECTION_FACTORY);
      queue = (Queue) new InitialContext().lookup(QueueNames.LOGOUT_QUEUE);
      log.trace("Queue logout: " + queue.getQueueName());
      QueueConnection connection = cf.createQueueConnection();
      QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
      QueueSender sender = session.createSender(queue);

      Message logoutMessage = session.createTextMessage(sessionId);
      Timestamp time = new Timestamp(new Date().getTime());
      // Messages will not accept timestamp property- must change to string
      logoutMessage.setStringProperty(PropertyNames.TIME, time.toString());
      sender.send(logoutMessage);
      session.close();

    } catch (Exception e) {
      log.fatal("Error in LogoutInterceptor", e);
    }
    return ctx.proceed();
  }
Пример #6
0
 @AroundInvoke
 Object intercept(InvocationContext ctx) throws Exception {
   if (!ctx.getMethod().getName().equals("echo")) {
     return ctx.proceed();
   }
   return "#CDIInterceptor#" + ctx.proceed();
 }
Пример #7
0
  @AroundInvoke
  public Object cachePut(InvocationContext ctx) throws Throwable {

    CachePut annotation = ctx.getMethod().getAnnotation(CachePut.class);
    PayaraCacheKeyInvocationContext<CachePut> pctx =
        new PayaraCacheKeyInvocationContext<>(ctx, annotation);
    if (!annotation.afterInvocation()) {
      doPut(pctx);
    }

    Object result = null;
    try {
      result = ctx.proceed();
    } catch (Throwable e) {
      if (annotation.afterInvocation()) {
        if (shouldICache(annotation.cacheFor(), annotation.noCacheFor(), e, false)) {
          doPut(pctx);
        }
      }
      throw e;
    }

    if (annotation.afterInvocation()) {
      doPut(pctx);
    }

    return result;
  }
 @AroundInvoke
 public Object overrideParameters(InvocationContext invocationContext) throws Exception {
   if (invocationContext.getMethod().getName().equals("echoLong")) {
     invocationContext.setParameters(new Character[] {'z'});
   }
   return invocationContext.proceed();
 }
Пример #9
0
 @PostConstruct
 void postConstruct(InvocationContext ctx) {
   log.info("PostConstruct on MethodInterceptor called");
   if (ctx.getMethod() != null) {
     throw new RuntimeException("InvocationContext.getMethod() on lifecycle event has to be null");
   }
 }
 @AroundInvoke
 public Object checkPermissions(InvocationContext context) throws Exception {
   try {
     logger.trace(Thread.currentThread().getName());
     HivePrincipal principal = ThreadLocalVariablesKeeper.getPrincipal();
     AccessKey key = principal.getKey();
     if (key == null) {
       return context.proceed();
     }
     if (key.getUser() == null || !key.getUser().getStatus().equals(UserStatus.ACTIVE)) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     Timestamp expirationDate = key.getExpirationDate();
     if (expirationDate != null
         && expirationDate.before(new Timestamp(System.currentTimeMillis()))) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     Method method = context.getMethod();
     AllowedKeyAction allowedActionAnnotation = method.getAnnotation(AllowedKeyAction.class);
     List<AllowedKeyAction.Action> actions = Arrays.asList(allowedActionAnnotation.action());
     boolean isAllowed = CheckPermissionsHelper.checkAllPermissions(key, actions);
     if (!isAllowed) {
       throw new HiveException(UNAUTHORIZED.getReasonPhrase(), UNAUTHORIZED.getStatusCode());
     }
     return context.proceed();
   } finally {
     ThreadLocalVariablesKeeper.clean();
   }
 }
  /**
   * This authorization method provides the validation logic for resources annotated with the
   * security annotation {@link AllowedRole}.
   *
   * <p>Note that this method is also annotated with {@link Secures}, which is an annotation from
   * Apache DeltaSpike. This annotation tells the @{link SecurityInterceptor} that this method must
   * be called before the execution of methods annotated with {@checkDeclaredRoles} in order to
   * perform authorization checks.
   *
   * @param invocationContext
   * @param manager
   * @return true if the user can execute the method or class
   * @throws Exception
   */
  @Secures
  @AllowedRole
  public boolean checkDeclaredRoles(InvocationContext invocationContext, BeanManager manager)
      throws Exception {
    // administrators can access everything
    if (hasRole(ApplicationRole.ADMINISTRATOR.name())) {
      return true;
    }

    Object targetBean = invocationContext.getTarget();

    AllowedRole declareRoles = targetBean.getClass().getAnnotation(AllowedRole.class);

    if (declareRoles == null) {
      declareRoles = invocationContext.getMethod().getAnnotation(AllowedRole.class);
    }

    ApplicationRole[] requiredRoles = declareRoles.value();

    if (requiredRoles.length == 0) {
      throw new IllegalArgumentException("@DeclaredRoles does not define any role.");
    }

    for (ApplicationRole requiredRole : requiredRoles) {
      if (hasRole(requiredRole.name())) {
        return true;
      }
    }

    return false;
  }
Пример #12
0
 @AroundInvoke
 public Object log(InvocationContext context) throws Exception {
   System.out.println("---" + context.getMethod());
   QueueConnection conn = qcf.createQueueConnection();
   conn.start();
   QueueSession session = conn.createQueueSession(true, Session.SESSION_TRANSACTED);
   TextMessage msg = session.createTextMessage();
   msg.setText(
       context.getMethod().getDeclaringClass().getSimpleName()
           + ";"
           + context.getMethod().getName()
           + ";"
           + sessionContext.getCallerPrincipal().getName());
   QueueSender queueSender = session.createSender(queue);
   queueSender.send(msg);
   return context.proceed();
 }
Пример #13
0
 private List<String> invalidParameters(InvocationContext context) {
   List<String> invalidParameters = new ArrayList<String>();
   Annotation[][] parameterAnnotations = context.getMethod().getParameterAnnotations();
   for (int i = 0; i < parameterAnnotations.length; i++) {
     for (Annotation annotation : parameterAnnotations[i]) {
       if (annotation instanceof NotNull) {
         Object value = context.getParameters()[i];
         if (value == null) {
           Class parameterType = context.getMethod().getParameterTypes()[i];
           invalidParameters.add(
               i + " parameter of type " + parameterType.getName() + " is null!");
         }
       }
     }
   }
   return invalidParameters;
 }
  @AroundInvoke
  public Object execute(InvocationContext invocationContext) throws Exception {

    // Execute following logic only if @Test method
    Test testAnnotation = invocationContext.getMethod().getAnnotation(Test.class);
    if (testAnnotation == null) {
      return invocationContext.proceed();
    }

    dbUnitSetup();
    DbUnitTestContext testContext = new DbUnitTestContext();

    Object returnValue = null;
    Class<?> testClass = ProxyUtils.getUnproxiedClass(invocationContext.getTarget().getClass());
    testContext.setTestClass(testClass);
    testContext.setTestInstance(invocationContext.getTarget());
    testContext.setTestMethod(invocationContext.getMethod());

    DbUnitConfiguration dbUnitConfiguration = testClass.getAnnotation(DbUnitConfiguration.class);
    try {
      dbUnitRunner.prepareTesterSetup(testContext, dbUnitConfiguration, databaseTester);

      //            try {
      databaseTester.onSetup();
      //            } catch (Throwable e) { // do not propagate db setup exception or transaction
      // will not rollback
      //                e.printStackTrace();
      //            }

      returnValue = invocationContext.proceed();

      dbUnitRunner.verifyExpected(testContext);
    } finally {
      dbUnitRunner.prepareTesterTearDown(testContext, dbUnitConfiguration, databaseTester);
      databaseTester.onTearDown();
      try {
        if (connection != null) {
          connection.close();
        }
      } catch (Exception e) {
        connection = null;
      }
    }
    return returnValue;
  }
Пример #15
0
 @AroundInvoke
 public Object intercept(InvocationContext ctx) throws Exception {
   System.out.println("*** DefaultInterceptor intercepting " + ctx.getMethod().getName());
   try {
     return ctx.proceed();
   } finally {
     System.out.println("*** DefaultInterceptor exiting");
   }
 }
Пример #16
0
 public QueryInvocationContext(
     InvocationContext invocation, DaoMethod daoMethod, EntityManager entityManager) {
   this.entityManager = entityManager;
   this.params = Parameters.create(invocation.getMethod(), invocation.getParameters());
   this.invocation = invocation;
   this.daoMethod = daoMethod;
   this.entityClass = daoMethod.getDao().getEntityClass();
   this.queryPostProcessors = new LinkedList<QueryStringPostProcessor>();
   this.jpaPostProcessors = new LinkedList<JpaQueryPostProcessor>();
 }
Пример #17
0
 @AroundInvoke
 public Object performanceAuditor(InvocationContext context) throws Exception {
   long start = System.currentTimeMillis();
   try {
     System.out.println("Method: " + context.getMethod());
     return context.proceed();
   } finally {
     System.out.println("---- " + (System.currentTimeMillis() - start));
   }
 }
 protected boolean isRollbackOnly(InvocationContext context) {
   Class targetClass =
       (context.getTarget() != null
           ? context.getTarget().getClass()
           : context.getMethod().getDeclaringClass());
   DatabaseNoRollbackTest databaseNoRollbackTest =
       AnnotationUtils.extractAnnotationFromMethodOrClass(
           beanManager, context.getMethod(), targetClass, DatabaseNoRollbackTest.class);
   if (databaseNoRollbackTest != null) {
     return false;
   }
   TransactionalTest transactionalTest =
       AnnotationUtils.extractAnnotationFromMethodOrClass(
           beanManager, context.getMethod(), targetClass, TransactionalTest.class);
   if (transactionalTest != null) {
     return transactionalTest.rollback();
   }
   // default is true
   return true;
 }
Пример #19
0
 @AroundInvoke
 public Object trace(InvocationContext invocationContext) throws Exception {
   long start = System.nanoTime();
   try {
     return invocationContext.proceed();
   } finally {
     long executionTime = (System.nanoTime() - start);
     System.out.println(
         "Method: " + invocationContext.getMethod() + " executed in: " + executionTime + " ns");
   }
 }
 @AroundInvoke
 public Object aroundInvoke(InvocationContext ic) throws Exception {
   String methodName = ic.getMethod().getName();
   String time = DateFormat.getTimeInstance().format(new Date());
   if (methodName.equals("create")) {
     History.getItemHistory().add(String.format("Item created at %s", time));
   } else if (methodName.equals("getList")) {
     History.getItemHistory().add(String.format("List of Items retrieved at %s", time));
   }
   return ic.proceed();
 }
Пример #21
0
 @AroundInvoke
 public Object checkParameters(InvocationContext invocationContext) throws Exception {
   List<String> invalidParameters = invalidParameters(invocationContext);
   if (!invalidParameters.isEmpty()) {
     Method method = invocationContext.getMethod();
     escalateError(method, invalidParameters);
     throw new IllegalArgumentException(
         "The contract of the method: " + method + " was violated!");
   } else {
     return invocationContext.proceed();
   }
 }
Пример #22
0
 @AroundInvoke
 public Object annotateThread(InvocationContext invCtx) throws Exception {
   String originName = Thread.currentThread().getName();
   String beanName = invCtx.getTarget().getClass().getName();
   String tracingName = beanName + "#" + invCtx.getMethod().getName() + " " + originName;
   try {
     Thread.currentThread().setName(tracingName);
     return invCtx.proceed();
   } finally {
     Thread.currentThread().setName(originName);
   }
 }
  /**
   * Validates the Bean Validation constraints specified at the parameters and/or return value of
   * the intercepted method.
   *
   * @param ctx The context of the intercepted method invocation.
   * @return The result of the method invocation.
   * @throws Exception Any exception caused by the intercepted method invocation. A {@link
   *     ConstraintViolationException} in case at least one constraint violation occurred either
   *     during parameter or return value validation.
   */
  @AroundInvoke
  public Object validateMethodInvocation(InvocationContext ctx) throws Exception {
    ExecutableValidator executableValidator = validator.forExecutables();
    Set<ConstraintViolation<Object>> violations =
        executableValidator.validateParameters(
            ctx.getTarget(), ctx.getMethod(), ctx.getParameters());

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(
          getMessage(ctx.getMethod(), ctx.getParameters(), violations), violations);
    }

    Object result = ctx.proceed();

    violations = executableValidator.validateReturnValue(ctx.getTarget(), ctx.getMethod(), result);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(
          getMessage(ctx.getMethod(), ctx.getParameters(), violations), violations);
    }

    return result;
  }
Пример #24
0
  private Stats stats(InvocationContext invocationContext, Method callback) {
    Method method = callback == null ? invocationContext.getMethod() : callback;

    Stats stats = map.get(method);
    if (stats == null) {
      synchronized (map) {
        stats = map.get(method);
        if (stats == null) {
          stats = new Stats(method, monitor);
          map.put(method, stats);
        }
      }
    }
    return stats;
  }
  private String getKey(InvocationContext invocation) {
    final String method = invocation.getMethod().toString();

    final Object object = invocation.getTimer();
    if (!(object instanceof Timer)) {
      return method;
    }

    final Timer timer = (Timer) object;
    final Serializable info = timer.getInfo();
    if (info == null || info instanceof ScheduleExpression) {
      return method;
    } else {
      return info.toString();
    }
  }
  /**
   * Verify a the list of roles specified by {@link Secure} are present to the current logged in
   * user
   *
   * @param ctx context information
   * @return result of the next method invoked
   * @throws Exception
   */
  @AroundInvoke
  public Object invoke(InvocationContext ctx) throws Exception {

    Class clazz = ctx.getTarget().getClass();

    if (clazz.isAnnotationPresent(Secure.class)) {
      authorize(clazzMetadata(ctx));
    }

    Method method = ctx.getMethod();

    if (method.isAnnotationPresent(Secure.class)) {
      authorize(methodMetadata(ctx));
    }

    return ctx.proceed();
  }
  @AroundInvoke
  public Object exceptionInterceptor(InvocationContext context) throws Exception {

    Object result = null;

    try {
      result = context.proceed();
    } catch (PersistenceException pe) {
      String methodName = context.getMethod().getName();
      if (methodName.startsWith("delete")
          && (pe.getCause().getCause() instanceof SQLIntegrityConstraintViolationException)) {
        throw new ObjectInUseException(
            "Could not delete because object is referenced by another entity.", pe);
      } else {
        throw pe;
      }
    }

    return result;
  }
  @AroundInvoke
  public Object cacheResult(InvocationContext invocationContext) throws Exception {
    if (log.isTraceEnabled()) {
      log.tracef("Interception of method named '%s'", invocationContext.getMethod().getName());
    }

    final CacheKeyInvocationContext<CacheResult> cacheKeyInvocationContext =
        contextFactory.getCacheKeyInvocationContext(invocationContext);
    final CacheKeyGenerator cacheKeyGenerator =
        cacheKeyInvocationContext
            .unwrap(CacheKeyInvocationContextImpl.class)
            .getCacheKeyGenerator();
    final CacheResult cacheResult = cacheKeyInvocationContext.getCacheAnnotation();
    final CacheKey cacheKey = cacheKeyGenerator.generateCacheKey(cacheKeyInvocationContext);
    final Cache<CacheKey, Object> cache = cacheResolver.resolveCache(cacheKeyInvocationContext);

    Object result = null;

    if (!cacheResult.skipGet()) {
      result = cache.get(cacheKey);
      if (log.isTraceEnabled()) {
        log.tracef(
            "Entry with value '%s' has been found in cache '%s' with key '%s'",
            result, cache.getName(), cacheKey);
      }
    }

    if (result == null) {
      result = invocationContext.proceed();
      if (result != null) {
        cache.put(cacheKey, result);
        if (log.isTraceEnabled()) {
          log.tracef(
              "Value '%s' cached in cache '%s' with key '%s'", result, cache.getName(), cacheKey);
        }
      }
    }

    return result;
  }
  @AroundInvoke
  public Object execute(final InvocationContext ictx) throws Exception {
    try {
      return ictx.proceed();
    } catch (ConstraintViolationException e) {
      final Logger log = getLogger(ictx.getTarget().getClass());
      log.error("***********************************************************");
      log.error(
          ictx.getMethod().toGenericString()
              + asList(ictx.getParameters())
              + " had the following validation errors: ");

      Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
      for (ConstraintViolation<?> violation : violations) {
        log.error(buildViolationMessage(violation));
      }

      log.error("***********************************************************");

      throw e;
    }
  }
Пример #30
0
 @AroundInvoke
 public Object logCall(InvocationContext ic) throws Exception {
   long start = System.currentTimeMillis();
   try {
     StringBuilder builder = new StringBuilder("Invoke: ");
     builder.append(ic.getClass().getName() + "." + ic.getMethod().getName());
     builder.append("(");
     boolean first = true;
     if (ic.getParameters() != null)
       for (Object o : ic.getParameters()) {
         if (!first) builder.append(", ");
         builder.append(o);
         first = false;
       }
     builder.append(")");
     logger.finest(builder.toString());
     return ic.proceed();
   } finally {
     long duration = System.currentTimeMillis() - start;
     // nothing here for now.
   }
 }