Example #1
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());
   }
 }
  /**
   * 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);
    }
  }
  /**
   * 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;
  }
  @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();
  }
 @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();
 }
  @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();
  }
 public Object invoke(InvocationContext invocationContext) throws Exception {
   try {
     return businessMethod.invoke(
         invocationContext.getTarget(), invocationContext.getParameters());
   } catch (InvocationTargetException e) {
     throw (Exception) e.getTargetException();
   }
 }
  @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;
  }
  @Test
  public void shouldWorkForFalse() throws Exception {
    when(context.getTarget()).thenReturn(false);

    interceptor.invoke(context);

    verify(logger, never()).info(anyString());
    verify(logger, never()).error(anyString());
  }
Example #10
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);
   }
 }
 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;
 }
 @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;
  }
  @PostConstruct
  private void afterCreation(InvocationContext ctx) {
    System.out.println("In InterceptorA.PostConstruct");

    try {
      BaseBean b = (BaseBean) ctx.getTarget();
      System.out.println("PostConstruct on : " + b);
      if (b.pc) throw new Exception("PostConstruct already called for " + b);
      ctx.proceed();
      b.pc = true;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  @AroundConstruct
  private void create(InvocationContext ctx) {
    System.out.println("In InterceptorA.AroundConstruct");

    try {
      java.lang.reflect.Constructor<?> c = ctx.getConstructor();
      System.out.println("Using Constructor: " + c);
      ctx.proceed();
      BaseBean b = (BaseBean) ctx.getTarget();
      System.out.println("Created instance: " + b);
      b.ac = true;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  /**
   * 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 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;
    }
  }
 @PostConstruct
 public void startupGuice(InvocationContext ctx) throws Exception {
   ctx.proceed();
   injector = Guice.createInjector(/* new AppConfigModule() */ );
   injector.injectMembers(ctx.getTarget());
 }
 private Set<String> clazzMetadata(InvocationContext ctx) {
   Secure annotation = ctx.getTarget().getClass().getAnnotation(Secure.class);
   return new HashSet<String>(Arrays.asList(annotation.value()));
 }
 @Override
 @AroundInvoke
 public Object invoke(InvocationContext context) throws Exception {
   try {
     try {
       return context.proceed();
     } catch (EJBException ejbExc) {
       if (ejbExc.getCause() != null && ejbExc.getCause() instanceof RuntimeException) {
         throw (RuntimeException) ejbExc.getCause();
       } else {
         throw ejbExc;
       }
     }
   } catch (EJBException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (SystemException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (ApplicationException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (InvalidStateException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (SQLException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (StaleObjectStateException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (StaleStateException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (HibernateException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (OptimisticLockException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (PersistenceException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (RuntimeException e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   } catch (Error e) {
     afterThrowing(context.getMethod(), context.getParameters(), context.getTarget(), e);
     throw e;
   }
 }