示例#1
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;
  }
 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();
 }
 @AroundInvoke
 public Object overrideParameters(InvocationContext invocationContext) throws Exception {
   if (invocationContext.getMethod().getName().equals("echoLong")) {
     invocationContext.setParameters(new Character[] {'z'});
   }
   return invocationContext.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();
  }
  /**
   * 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;
  }
示例#7
0
 @AroundInvoke
 Object intercept(InvocationContext ctx) throws Exception {
   if (!ctx.getMethod().getName().equals("echo")) {
     return ctx.proceed();
   }
   return "#CDIInterceptor#" + ctx.proceed();
 }
 @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 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();
   }
 }
  @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();
  }
 public Object invoke(InvocationContext invocationContext) throws Exception {
   try {
     return businessMethod.invoke(
         invocationContext.getTarget(), invocationContext.getParameters());
   } catch (InvocationTargetException e) {
     throw (Exception) e.getTargetException();
   }
 }
示例#12
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 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;
 }
示例#14
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());
   }
 }
示例#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");
   }
 }
 @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();
 }
示例#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));
   }
 }
示例#18
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>();
 }
示例#19
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);
   }
 }
  /**
   * 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);
    }
  }
示例#21
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();
 }
示例#23
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();
   }
 }
示例#24
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);
   }
 }
示例#25
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);
   }
 }
  @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);
    }
  }
示例#28
0
  @AroundInvoke
  public Object aroundInvoke(final InvocationContext invocation) throws Exception {
    System.err.println("invocation = " + invocation);

    used = true;
    return invocation.proceed();
  }
 private void validateAllRepresentations(InvocationContext ic) {
   for (Object obj : ic.getParameters()) {
     if (obj instanceof Representation) {
       validate(obj);
     }
   }
 }
  @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();
      }
    }
  }