Java Code Examples for javax.interceptor.InvocationContext

The following examples show how to use javax.interceptor.InvocationContext. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: lib-ussd   Source File: Internal.java    License: Apache License 2.0 6 votes vote down vote up
@AroundInvoke
public Object logAroundInvoke(InvocationContext ic) throws Exception {
  Class clazz = ic.getMethod().getDeclaringClass();
  Log log = ic.getMethod().getAnnotation(Log.class);
  if (DataHelper.hasBlank(log)) {
    log = (Log) clazz.getAnnotation(Log.class);
  }

  boolean secure = (!DataHelper.hasBlank(log) && log.secure());
  Object[] params = new Object[]{clazz.getName(), ic.getMethod().getName(),
    Joiner.on(", ").useForNull("").join(ic.getParameters())};
  L.debug("Entering - {}#{} : " + (secure ? "*****" : "{}"), ic.getMethod().getDeclaringClass().getSimpleName(),
      ic.getMethod().getName(), params);

  Object result = ic.proceed();
  params[2] = result;
  L.debug("Exiting - {}#{} : " + (secure ? "*****" : "{}"), ic.getMethod().getDeclaringClass().getSimpleName(),
      ic.getMethod().getName(), result);

  return result;
}
 
Example 2
@AroundInvoke
public Object statisticMethod (InvocationContext invocationContext) throws Exception{
	System.out.println("Statistical method : "
			+ invocationContext.getMethod().getName() + " " 
			+ invocationContext.getMethod().getDeclaringClass()
			);
	
	// get the enrollment:
	TestRevisionTO testRevisionTO = (TestRevisionTO)invocationContext.getParameters()[0];
	
	System.out.println("Enrolment : " + testRevisionTO.getEnrollment());
	
	// event.fireAsync (testRevisionTO.getEnrollment());// fire an async statistical event. This is new in JEE8.
	event.fire (testRevisionTO.getEnrollment());
	
	Object o =  invocationContext.proceed();
	return o;
}
 
Example 3
Source Project: javamelody   Source File: MonitoringInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Intercepte une exécution de méthode sur un ejb.
 * @param context InvocationContext
 * @return Object
 * @throws Exception e
 */
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception { // NOPMD
	// cette méthode est appelée par le conteneur ejb grâce à l'annotation AroundInvoke
	if (DISABLED || !EJB_COUNTER.isDisplayed()) {
		return context.proceed();
	}
	// nom identifiant la requête
	final String requestName = getRequestName(context);

	boolean systemError = false;
	try {
		EJB_COUNTER.bindContextIncludingCpu(requestName);
		return context.proceed();
	} catch (final Error e) {
		// on catche Error pour avoir les erreurs systèmes
		// mais pas Exception qui sont fonctionnelles en général
		systemError = true;
		throw e;
	} finally {
		// on enregistre la requête dans les statistiques
		EJB_COUNTER.addRequestForCurrentContext(systemError);
	}
}
 
Example 4
Source Project: development   Source File: LdapInterceptorTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void isServiceProvider_LdapPropertiesNull() throws Exception {
    // given
    InvocationContext context = mock(InvocationContext.class);
    Object[] parameters = { new VOOrganization(), new VOUserDetails(),
            null, "marketplaceId" };
    doReturn(parameters).when(context).getParameters();
    doReturn(Boolean.TRUE).when(ldapInterceptor.configService)
            .isServiceProvider();
    doReturn(new OperatorServiceBean()).when(context).getTarget();

    // when
    ldapInterceptor.ensureLdapDisabledForServiceProvider(context);

    // then
    verify(context, times(1)).proceed();
}
 
Example 5
Source Project: tomee   Source File: AutoApplySessionInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
private AuthenticationStatus validateRequest(final InvocationContext invocationContext)
        throws Exception {

    final HttpMessageContext httpMessageContext = (HttpMessageContext) invocationContext.getParameters()[2];

    final Principal principal = httpMessageContext.getRequest().getUserPrincipal();
    if (principal == null) {
        final Object authenticationStatus = invocationContext.proceed();

        if (AuthenticationStatus.SUCCESS.equals(authenticationStatus)) {
            httpMessageContext.getMessageInfo().getMap().put("javax.servlet.http.registerSession", "true");
        }

        return (AuthenticationStatus) authenticationStatus;
    } else {
        final CallerPrincipalCallback callerPrincipalCallback =
                new CallerPrincipalCallback(httpMessageContext.getClientSubject(), principal);

        httpMessageContext.getHandler().handle(new Callback[] {callerPrincipalCallback});

        return AuthenticationStatus.SUCCESS;
    }
}
 
Example 6
Source Project: kumuluzee   Source File: ConfigBundleInterceptor.java    License: MIT License 6 votes vote down vote up
/**
 * Method initialises class fields from configuration.
 */
@PostConstruct
public Object loadConfiguration(InvocationContext ic) throws Exception {

    Object target = ic.getTarget();
    Class targetClass = target.getClass();

    if (targetClassIsProxied(targetClass)) {
        targetClass = targetClass.getSuperclass();
    }

    ConfigBundle configBundleAnnotation = (ConfigBundle) targetClass.getDeclaredAnnotation(ConfigBundle.class);

    processConfigBundleBeanSetters(target, targetClass, getKeyPrefix(targetClass), new HashMap<>(),
            configBundleAnnotation.watch());

    return ic.proceed();
}
 
Example 7
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    try {
        return context.proceed();
    } catch (Exception ex) {
        Set<Class<? extends Exception>> ignored = RegistryExceptionMapper.getIgnored();
        if (!ignored.contains(ex.getClass())) { // suspect and rethrow unless ignored
            check.suspectWithException(ex);
        }
        throw ex;
    }
}
 
Example 8
Source Project: apicurio-registry   Source File: RestMetricsInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    if (!init) {
        init(); // @PostConstruct causes MethodNotFound ex.
    }
    counter.inc();
    gauge.inc();
    Timer.Context time = timer.time();
    try {
        return context.proceed();
    } finally {
        time.stop();
        gauge.dec();
    }
}
 
Example 9
Source Project: quarkus   Source File: SimpleInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
Object mySuperCoolAroundInvoke(InvocationContext ctx) throws Exception {
    Object bindings = ctx.getContextData().get(ArcInvocationContext.KEY_INTERCEPTOR_BINDINGS);
    if (bindings == null) {
        throw new IllegalArgumentException("No bindings found");
    }
    return "" + counter.get() + ctx.proceed() + counter.incrementAndGet();
}
 
Example 10
@SuppressWarnings("unchecked")
private <T> T syncFlow(FaultToleranceOperation operation, InvocationContext invocationContext,
        MetricsCollector collector, InterceptionPoint point) throws Exception {
    FaultToleranceStrategy<T> strategy = cache.getStrategy(point,
            ignored -> prepareSyncStrategy(operation, point, collector));
    io.smallrye.faulttolerance.core.InvocationContext<T> ctx = new io.smallrye.faulttolerance.core.InvocationContext<>(
            () -> (T) invocationContext.proceed());
    ctx.set(InvocationContext.class, invocationContext);
    return strategy.apply(ctx);
}
 
Example 11
@SuppressWarnings("unchecked")
private <T> Future<T> futureFlow(FaultToleranceOperation operation, InvocationContext invocationContext,
        MetricsCollector collector, InterceptionPoint point) throws Exception {
    FaultToleranceStrategy<Future<T>> strategy = cache.getStrategy(point,
            ignored -> prepareFutureStrategy(operation, point, collector));
    io.smallrye.faulttolerance.core.InvocationContext<Future<T>> ctx = new io.smallrye.faulttolerance.core.InvocationContext<>(
            () -> (Future<T>) invocationContext.proceed());
    ctx.set(InvocationContext.class, invocationContext);
    return strategy.apply(ctx);
}
 
Example 12
@Override
protected void beforeProceed(InvocationContext invocationContext,
                             EntityManagerEntry entityManagerEntry,
                             EntityTransaction transaction)
{
    if (isInJtaTransaction())
    {
        super.beforeProceed(invocationContext, entityManagerEntry, transaction);
    }
}
 
Example 13
Source Project: deltaspike   Source File: MyBeanInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object wrapBeanCandidate(InvocationContext invocationContext) throws Exception
{
    ((MyBean) invocationContext.getTarget()).setIntercepted(true);
    
    return invocationContext.proceed();
}
 
Example 14
Source Project: quarkus   Source File: TransactionalInterceptorBase.java    License: Apache License 2.0 5 votes vote down vote up
public Object intercept(InvocationContext ic) throws Exception {
    final TransactionManager tm = transactionManager;
    final Transaction tx = tm.getTransaction();

    boolean previousUserTransactionAvailability = setUserTransactionAvailable(userTransactionAvailable);
    try {
        return doIntercept(tm, tx, ic);
    } finally {
        resetUserTransactionAvailability(previousUserTransactionAvailability);
    }
}
 
Example 15
Source Project: quarkus   Source File: InterceptedStaticMethodsProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private ResultHandle createForwardingFunction(MethodCreator init, ClassInfo target, MethodInfo method) {
    // Forwarding function
    // Function<InvocationContext, Object> forward = ctx -> Foo.interceptMe_original((java.lang.String)ctx.getParameters()[0])
    FunctionCreator func = init.createFunction(Function.class);
    BytecodeCreator funcBytecode = func.getBytecode();
    List<Type> paramTypes = method.parameters();
    ResultHandle[] paramHandles;
    String[] params;
    if (paramTypes.isEmpty()) {
        paramHandles = new ResultHandle[0];
        params = new String[0];
    } else {
        paramHandles = new ResultHandle[paramTypes.size()];
        ResultHandle ctxHandle = funcBytecode.getMethodParam(0);
        ResultHandle ctxParamsHandle = funcBytecode.invokeInterfaceMethod(
                MethodDescriptor.ofMethod(InvocationContext.class, "getParameters", Object[].class),
                ctxHandle);
        // autoboxing is handled inside Gizmo
        for (int i = 0; i < paramHandles.length; i++) {
            paramHandles[i] = funcBytecode.readArrayValue(ctxParamsHandle, i);
        }
        params = new String[paramTypes.size()];
        for (int i = 0; i < paramTypes.size(); i++) {
            params[i] = paramTypes.get(i).name().toString();
        }
    }
    ResultHandle ret = funcBytecode.invokeStaticMethod(
            MethodDescriptor.ofMethod(target.name().toString(), method.name() + ORGINAL_METHOD_COPY_SUFFIX,
                    method.returnType().name().toString(),
                    params),
            paramHandles);
    if (ret == null) {
        funcBytecode.returnValue(funcBytecode.loadNull());
    } else {
        funcBytecode.returnValue(ret);
    }
    return func.getInstance();
}
 
Example 16
Source Project: tomee   Source File: CdiDecoratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object aroundInvoke(final InvocationContext ctx) throws Exception {
    businessMethod.add(this.getClass().getSimpleName());
    System.out.println("In CDI Style Interceptor  : " + OrangeCdiInterceptor.class.getName());
    RUN = true;
    return ctx.proceed();
}
 
Example 17
Source Project: deltaspike   Source File: DefaultFutureableStrategy.java    License: Apache License 2.0 5 votes vote down vote up
private boolean equals(final InvocationContext ic1, final InvocationContext ic2)
{
    final Object[] parameters1 = ic1.getParameters();
    final Object[] parameters2 = ic2.getParameters();
    return ic2.getMethod().equals(ic1.getMethod()) &&
            (parameters1 == parameters2 ||
            (parameters1 != null && parameters2 != null && Arrays.equals(parameters1, ic2.getParameters())));
}
 
Example 18
Source Project: tomee   Source File: StatefulInterceptorTest.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {
    calls.add(Call.Method_Invoke_BEFORE);
    final Object o = context.proceed();
    calls.add(Call.Method_Invoke_AFTER);
    return o;
}
 
Example 19
Source Project: deltaspike   Source File: EnableInterceptorsInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object wrapBeanCandidate(InvocationContext invocationContext) throws Exception
{
    Object producerResult = invocationContext.proceed();
    
    return EnableInterceptorsProxyFactory.wrap(producerResult, beanManager);
}
 
Example 20
Source Project: logging-interceptor   Source File: ParameterLogArgument.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void set(RestorableMdc mdc, InvocationContext context) {
    if (logContextVariableName != null) {
        Object value = value(context);
        if (value != null) {
            mdc.put(logContextVariableName, value.toString());
        }
    }
}
 
Example 21
Source Project: tomee   Source File: EjbMethodInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object invoke(final Exchange exchange, final Object serviceObject,
                        final Method m, final List<Object> params) {
    final InvocationContext invContext = exchange.get(InvocationContext.class);
    if (invContext == null) {
        return preEjbInvoke(exchange, m, params);
    }
    return super.invoke(exchange, serviceObject, m, params);
}
 
Example 22
private Method resolveBlockHandlerInternal(InvocationContext ctx, /*@NonNull*/ String name, Class<?> clazz,
                                           boolean mustStatic) {
    Method originMethod = resolveMethod(ctx);
    Class<?>[] originList = originMethod.getParameterTypes();
    Class<?>[] parameterTypes = Arrays.copyOf(originList, originList.length + 1);
    parameterTypes[parameterTypes.length - 1] = BlockException.class;
    return findMethod(mustStatic, clazz, name, originMethod.getReturnType(), parameterTypes);
}
 
Example 23
protected Method resolveMethod(InvocationContext ctx) {
    Class<?> targetClass = ctx.getTarget().getClass();

    Method method = getDeclaredMethodFor(targetClass, ctx.getMethod().getName(),
        ctx.getMethod().getParameterTypes());
    if (method == null) {
        throw new IllegalStateException("Cannot resolve target method: " + ctx.getMethod().getName());
    }
    return method;
}
 
Example 24
Source Project: development   Source File: AuditLoggingEnabledTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void isLoggingEnabled_true() throws Exception {
    // given
    AuditLoggingEnabled auditLoggingEnabled = mockAuditLoggingIsEnabled(
            true);
    InvocationContext context = mock(InvocationContext.class);

    // when
    auditLoggingEnabled.isLoggingEnabled(context);

    // then
    verify(context, times(1)).proceed();
}
 
Example 25
Source Project: blog-tutorials   Source File: PaymentManipulationInterceptor.java    License: MIT License 5 votes vote down vote up
@AroundInvoke
public Object manipulatePayment(InvocationContext invocationContext) throws Exception {

    if (invocationContext.getParameters()[0] instanceof String) {
        if (((String) invocationContext.getParameters()[0]).equalsIgnoreCase("duke")) {
            paymentManipulator.manipulatePayment();
            invocationContext.setParameters(new Object[]{
                    "Duke", new BigDecimal(999.99).setScale(2, RoundingMode.HALF_UP)
            });
        }
    }

    return invocationContext.proceed();
}
 
Example 26
Source Project: tomee   Source File: SimpleCdiTest.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object aroundInvoke(final InvocationContext context) throws Exception {
    RUN = true;
    if (injection != null) {
        INJECTED = true;
    }

    return context.proceed();
}
 
Example 27
Source Project: development   Source File: LdapInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ensures that LDAP support is disabled if OSCM acts as a SAML SP.
 */
@AroundInvoke
public Object ensureLdapDisabledForServiceProvider(InvocationContext context)
        throws Exception {
    Object result = null;
    Object organizationProperties = null;

    Object[] parameters = context.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        if (parameters[i] instanceof LdapProperties
                || parameters[i] instanceof Properties) {
            organizationProperties = parameters[i];
        }
    }

    if (configService.isServiceProvider() && organizationProperties != null) {
        UnsupportedOperationException e = new UnsupportedOperationException(
                "It is forbidden to perform this operation if a OSCM acts as a SAML service provider.");

        Log4jLogger logger = LoggerFactory.getLogger(context.getTarget()
                .getClass());
        logger.logError(Log4jLogger.SYSTEM_LOG, e,
                LogMessageIdentifier.ERROR_OPERATION_FORBIDDEN_FOR_SAML_SP);
        throw e;
    }

    result = context.proceed();
    return result;
}
 
Example 28
Source Project: quarkus   Source File: CacheInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected <T> List<T> getInterceptorBindings(InvocationContext context, Class<T> bindingClass) {
    List<T> bindings = new ArrayList<>();
    for (Annotation binding : InterceptorBindings.getInterceptorBindings(context)) {
        if (bindingClass.isInstance(binding)) {
            bindings.add((T) binding);
        }
    }
    return bindings;
}
 
Example 29
Source Project: tomee   Source File: LoginToContinueInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@AroundInvoke
public Object intercept(final InvocationContext invocationContext) throws Exception {
    if (invocationContext.getMethod().getName().equals("validateRequest") &&
        Arrays.equals(invocationContext.getMethod().getParameterTypes(), new Class<?>[]{
                HttpServletRequest.class,
                HttpServletResponse.class,
                HttpMessageContext.class
        })) {
        return validateRequest(invocationContext);
    }

    return invocationContext.proceed();
}
 
Example 30
@AroundInvoke
public Object logInvocation(InvocationContext ctx) throws Exception {
    Method m = ctx.getMethod();
    invocationMessage = m.getDeclaringClass().getName() + "." + m.getName();

    Object returnVal = ctx.proceed();
    invocationMessage += " " + returnVal;
    return returnVal;
}