@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();
   }
 }
Пример #2
0
 @AroundInvoke
 Object intercept(InvocationContext ctx) throws Exception {
   if (!ctx.getMethod().getName().equals("echo")) {
     return ctx.proceed();
   }
   return "#CDIInterceptor#" + ctx.proceed();
 }
Пример #3
0
 // TODO MISSING JAVADOC
 @AroundInvoke
 public Object call(final InvocationContext invocationContext) throws Exception {
   final String id = MDC.get(TRANSACTION_ID);
   if (id != null) {
     return invocationContext.proceed();
   }
   MDC.put(TRANSACTION_ID, Long.toHexString(RANDOM.nextLong()));
   try {
     return invocationContext.proceed();
   } finally {
     MDC.remove(TRANSACTION_ID);
   }
 }
Пример #4
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();
 }
  @AroundInvoke
  public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction trx = manager.getTransaction();
    boolean criador = false;

    try {
      if (!trx.isActive()) {
        // truque para fazer rollback no que já passou
        // (senão, um futuro commit, confirmaria até mesmo operações sem transação)
        trx.begin();
        trx.rollback();

        // agora sim inicia a transação
        trx.begin();

        criador = true;
      }

      return context.proceed();
    } catch (Exception e) {
      if (trx != null && criador) {
        trx.rollback();
      }

      throw e;
    } finally {
      if (trx != null && trx.isActive() && criador) {
        trx.commit();
      }
    }
  }
Пример #6
0
 @AroundInvoke
 public Object interceptCall(InvocationContext ctx) throws Exception {
   System.out.println("In InterceptorA.AroundInvoke");
   BaseBean b = (BaseBean) ctx.getTarget();
   System.out.println("AroundInvoke on : " + b);
   return ctx.proceed();
 }
  @PostConstruct
  public void postConstruct(InvocationContext ctx) throws Exception {
    log.debug("postConstruct " + ctx);

    Class<?> businessInterfaces[];
    InterceptorContainer container = (InterceptorContainer) ctx.getTarget();
    Local local = container.getAnnotation(Local.class);
    if (local != null) businessInterfaces = local.value();
    else if (container.getBeanClass().getInterfaces().length == 1)
      businessInterfaces = new Class<?>[] {container.getBeanClass().getInterfaces()[0]};
    else throw new IllegalArgumentException("TODO");

    // TODO: determine JNDI name
    String jndiName = container.getBeanClass().getSimpleName() + "/local";
    log.debug("jndiName = " + jndiName);

    Object proxy =
        Proxy.newProxyInstance(
            Thread.currentThread().getContextClassLoader(),
            businessInterfaces,
            new LocalProxy(container));

    Util.createSubcontext(new InitialContext(), container.getBeanClass().getSimpleName());
    NonSerializableFactory.rebind(new InitialContext(), jndiName, proxy);

    ctx.proceed();
  }
  /**
   * Validates the Bean Validation constraints specified at the parameters and/or return value of
   * the intercepted constructor.
   *
   * @param ctx The context of the intercepted constructor invocation.
   * @throws Exception Any exception caused by the intercepted constructor invocation. A {@link
   *     ConstraintViolationException} in case at least one constraint violation occurred either
   *     during parameter or return value validation.
   */
  @AroundConstruct
  public void validateConstructorInvocation(InvocationContext ctx) throws Exception {
    ExecutableValidator executableValidator = validator.forExecutables();
    Set<? extends ConstraintViolation<?>> violations =
        executableValidator.validateConstructorParameters(
            ctx.getConstructor(), ctx.getParameters());

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

    ctx.proceed();
    Object createdObject = ctx.getTarget();

    violations =
        validator
            .forExecutables()
            .validateConstructorReturnValue(ctx.getConstructor(), createdObject);

    if (!violations.isEmpty()) {
      throw new ConstraintViolationException(
          getMessage(ctx.getConstructor(), ctx.getParameters(), violations), violations);
    }
  }
  @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();
  }
 @AroundInvoke
 public Object aroundInvoke(final InvocationContext context) throws Exception {
   result.add(Call.BEAN_AROUND_INVOKE_BEGIN);
   final Object o = context.proceed();
   result.add(Call.BEAN_AROUND_INVOKE_AFTER);
   return o;
 }
Пример #11
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();
 }
  /* The annotation @AroundInvoke sign this method for to be called automatically before the
  method annotated with @Transactional */
  @AroundInvoke
  public Object invoke(InvocationContext context) throws Exception {
    EntityTransaction entityTransaction = entityManager.getTransaction();
    boolean owner = false;

    try {
      if (!entityTransaction.isActive()) {
        // A way to grant any operation pending will be rollback, preventing possible errors.
        entityTransaction.begin();
        entityTransaction.rollback();

        // Now, after check about posible errors, the transaction is started.
        entityTransaction.begin();
        owner = true;
      }
      // After  transaction started, the content of any method intercepted as @Transactional is run.
      return context.proceed();
    } catch (Exception e) {
      if (entityTransaction != null && owner) {
        // Any anomaly operation and the changes are undone
        entityTransaction.rollback();
      }
      throw e;
    } finally {
      if (entityTransaction != null && entityTransaction.isActive() && owner) {
        // Finaly, without any errors, the changes are sended to the database.
        entityTransaction.commit();
      }
    }
  }
Пример #14
0
  @AroundInvoke
  public Object aroundInvoke(final InvocationContext invocation) throws Exception {
    System.err.println("invocation = " + invocation);

    used = true;
    return invocation.proceed();
  }
    public Object invoke() throws Exception {
      // invoke the callback
      super.invoke();

      // we need to call proceed so callbacks in subclasses get invoked
      Object value = invocationContext.proceed();
      return value;
    }
Пример #16
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;
 }
Пример #17
0
 @AroundInvoke
 public Object log(InvocationContext ctx) throws Exception {
   Object returnedObject = ctx.proceed();
   Map<String, Object> ctxData = ctx.getContextData();
   Object object = ctxData.get("entity");
   JPA_LOGGER.info("Entity: " + object);
   return returnedObject;
 }
  @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;
  }
Пример #19
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());
   }
 }
Пример #20
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");
   }
 }
Пример #21
0
 @PreDestroy
 public void preDestroy(InvocationContext ctx) {
   ActionSequence.addAction("preDestroy", AirborneInterceptor.class.getSimpleName());
   try {
     ctx.proceed();
   } catch (Throwable e) {
     throw new RuntimeException(e);
   }
 }
Пример #22
0
 @AroundConstruct
 public void aroundConstruct(InvocationContext ctx) {
   ActionSequence.addAction("aroundConstruct", AirborneInterceptor.class.getSimpleName());
   try {
     ctx.proceed();
   } catch (Throwable e) {
     throw new RuntimeException(e);
   }
 }
Пример #23
0
 @PreDestroy
 private void preDestroy(InvocationContext ctx) {
   System.out.println("In InterceptorA.PreDestroy");
   try {
     ctx.proceed();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Пример #24
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));
   }
 }
  @AroundInvoke
  public Object manage(InvocationContext ic) throws Exception {

    if (!currentPlayer.get().isShot()) {
      // I'am doing science and I'am still alive!
      return ic.proceed();
    }

    return null;
  }
Пример #26
0
  @AroundInvoke
  public Object intercept(InvocationContext ctx) throws Exception {
    wasCalled = true;

    // change entity's ID to 2 before persisting
    // Employee emp = (Employee) ctx.getParameters()[0];
    // emp.setId(emp.getId() + 1);

    return ctx.proceed();
  }
Пример #27
0
  @AroundInvoke
  public Object logPerformance(InvocationContext ic) throws Exception {
    long start = System.currentTimeMillis();

    Object value = ic.proceed();

    result = System.currentTimeMillis() - start;

    return value;
  }
 @SuppressWarnings("unchecked")
 @PostConstruct
 void intercept(InvocationContext ctx) throws Exception {
   contextDataBindings =
       (Set<Annotation>) ctx.getContextData().get(InvocationContextInterceptorBindingsTest.KEY);
   if (ctx instanceof WeldInvocationContext) {
     contextBindings = ((WeldInvocationContext) ctx).getInterceptorBindings();
   }
   ctx.proceed();
 }
Пример #29
0
 @PostConstruct
 public void postConstruct(InvocationContext ctx) {
   AbstractLion lion = (AbstractLion) ctx.getTarget();
   lion.setPostConstructInterceptor(this);
   try {
     ctx.proceed();
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
 @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();
 }