Search in sources :

Example 41 with AroundInvoke

use of javax.interceptor.AroundInvoke in project Payara by payara.

the class CacheRemoveAllInterceptor method cacheRemoveAll.

@AroundInvoke
public Object cacheRemoveAll(InvocationContext ctx) throws Throwable {
    if (!isEnabled()) {
        return ctx.proceed();
    }
    CacheRemoveAll annotation = ctx.getMethod().getAnnotation(CacheRemoveAll.class);
    PayaraCacheKeyInvocationContext<CacheRemoveAll> pctx = new PayaraCacheKeyInvocationContext<>(ctx, annotation);
    if (!annotation.afterInvocation()) {
        doRemoveAll(pctx);
    }
    Object result = null;
    try {
        result = ctx.proceed();
    } catch (Throwable e) {
        if (annotation.afterInvocation()) {
            if (shouldIEvict(annotation.evictFor(), annotation.noEvictFor(), e)) {
                doRemoveAll(pctx);
            }
        }
        throw e;
    }
    if (annotation.afterInvocation()) {
        doRemoveAll(pctx);
    }
    return result;
}
Also used : CacheRemoveAll(javax.cache.annotation.CacheRemoveAll) PayaraCacheKeyInvocationContext(fish.payara.cdi.jsr107.implementation.PayaraCacheKeyInvocationContext) AroundInvoke(javax.interceptor.AroundInvoke)

Example 42 with AroundInvoke

use of javax.interceptor.AroundInvoke in project tomee by apache.

the class BValInterceptor method invoke.

@AroundInvoke
public Object invoke(final InvocationContext context) throws Exception {
    Method method = context.getMethod();
    Class<?> targetClass = getTargetClass(context);
    final ClassValidationData validationData = new ClassValidationData(targetClass);
    if (validationData.getJwtConstraints().size() > 0) {
        final Class<?> constraintsClazz = new ClassValidationGenerator(validationData).generate().stream().filter(aClass -> aClass.getName().endsWith("ReturnConstraints")).findFirst().orElseThrow(MissingConstraintsException::new);
        try {
            final Method constraintsClazzMethod = constraintsClazz.getMethod(method.getName(), method.getParameterTypes());
            targetClass = constraintsClazz;
            method = constraintsClazzMethod;
        } catch (NoSuchMethodException | SecurityException e) {
            // this is ok.  it means there are no return value constraints
            return context.proceed();
        }
    }
    if (!isExecutableValidated(targetClass, method, this::computeIsMethodValidated)) {
        return context.proceed();
    }
    final MethodDescriptor constraintsForMethod = validator.getConstraintsForClass(targetClass).getConstraintsForMethod(method.getName(), method.getParameterTypes());
    if (!DescriptorManager.isConstrained(constraintsForMethod)) {
        return context.proceed();
    }
    initExecutableValidator();
    if (constraintsForMethod.hasConstrainedParameters()) {
        final Set<ConstraintViolation<Object>> violations = executableValidator.validateParameters(context.getTarget(), method, context.getParameters());
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    final Object result = context.proceed();
    if (constraintsForMethod.hasConstrainedReturnValue()) {
        final Set<ConstraintViolation<Object>> violations = executableValidator.validateReturnValue(context.getTarget(), method, result);
        if (!violations.isEmpty()) {
            throw new ConstraintViolationException(violations);
        }
    }
    return result;
}
Also used : Method(java.lang.reflect.Method) AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) MethodDescriptor(javax.validation.metadata.MethodDescriptor) ConstraintViolation(javax.validation.ConstraintViolation) ConstraintViolationException(javax.validation.ConstraintViolationException) AroundInvoke(javax.interceptor.AroundInvoke)

Example 43 with AroundInvoke

use of javax.interceptor.AroundInvoke in project tomee by apache.

the class EjbInterceptor method intercept.

@AroundInvoke
public Object intercept(InvocationContext context) throws Exception {
    Endpoint endpoint = this.exchange.get(Endpoint.class);
    Service service = endpoint.getService();
    Binding binding = ((JaxWsEndpointImpl) endpoint).getJaxwsBinding();
    this.exchange.put(InvocationContext.class, context);
    if (binding.getHandlerChain() == null || binding.getHandlerChain().isEmpty()) {
        // no handlers so let's just directly invoke the bean
        log.debug("No handlers found.");
        EjbMethodInvoker invoker = (EjbMethodInvoker) service.getInvoker();
        return invoker.directEjbInvoke(this.exchange, this.method, this.params);
    } else {
        // have handlers so have to run handlers now and redo data binding
        // as handlers can change the soap message
        log.debug("Handlers found.");
        Message inMessage = exchange.getInMessage();
        PhaseInterceptorChain chain = new PhaseInterceptorChain(bus.getExtension(PhaseManager.class).getInPhases());
        chain.setFaultObserver(endpoint.getOutFaultObserver());
        /*
             * Since we have to re-do data binding and the XMLStreamReader
             * contents are already consumed by prior data binding step
             * we have to reinitialize the XMLStreamReader from the SOAPMessage
             * created by SAAJInInterceptor.
             */
        if (inMessage instanceof SoapMessage) {
            try {
                reserialize((SoapMessage) inMessage);
            } catch (Exception e) {
                throw new ServerRuntimeException("Failed to reserialize soap message", e);
            }
        } else {
        // TODO: how to handle XML/HTTP binding?
        }
        this.exchange.setOutMessage(null);
        // install default interceptors
        chain.add(new ServiceInvokerInterceptor());
        // chain.add(new OutgoingChainInterceptor()); // it is already in the enclosing chain, if we add it there we are in the tx so we write the message in the tx!
        // See http://cwiki.apache.org/CXF20DOC/interceptors.html
        // install Holder and Wrapper interceptors
        chain.add(new WrapperClassInInterceptor());
        chain.add(new HolderInInterceptor());
        // install interceptors for handler processing
        chain.add(new MustUnderstandInterceptor());
        chain.add(new LogicalHandlerInInterceptor(binding));
        chain.add(new SOAPHandlerInterceptor(binding));
        // install data binding interceptors - todo: check we need it
        copyDataBindingInterceptors(chain, inMessage.getInterceptorChain());
        InterceptorChain oldChain = inMessage.getInterceptorChain();
        inMessage.setInterceptorChain(chain);
        try {
            chain.doIntercept(inMessage);
        } finally {
            inMessage.setInterceptorChain(oldChain);
        }
        // TODO: the result should be deserialized from SOAPMessage
        Object result = getResult();
        return result;
    }
}
Also used : Binding(javax.xml.ws.Binding) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) Message(org.apache.cxf.message.Message) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) SOAPMessage(javax.xml.soap.SOAPMessage) HolderInInterceptor(org.apache.cxf.jaxws.interceptors.HolderInInterceptor) SOAPHandlerInterceptor(org.apache.cxf.jaxws.handler.soap.SOAPHandlerInterceptor) MustUnderstandInterceptor(org.apache.cxf.binding.soap.interceptor.MustUnderstandInterceptor) Service(org.apache.cxf.service.Service) ServerRuntimeException(org.apache.openejb.server.ServerRuntimeException) SoapMessage(org.apache.cxf.binding.soap.SoapMessage) InterceptorChain(org.apache.cxf.interceptor.InterceptorChain) PhaseInterceptorChain(org.apache.cxf.phase.PhaseInterceptorChain) Endpoint(org.apache.cxf.endpoint.Endpoint) JaxWsEndpointImpl(org.apache.cxf.jaxws.support.JaxWsEndpointImpl) LogicalHandlerInInterceptor(org.apache.cxf.jaxws.handler.logical.LogicalHandlerInInterceptor) ServiceInvokerInterceptor(org.apache.cxf.interceptor.ServiceInvokerInterceptor) ServerRuntimeException(org.apache.openejb.server.ServerRuntimeException) WrapperClassInInterceptor(org.apache.cxf.jaxws.interceptors.WrapperClassInInterceptor) AroundInvoke(javax.interceptor.AroundInvoke)

Example 44 with AroundInvoke

use of javax.interceptor.AroundInvoke in project Payara by payara.

the class SystemInterceptorProxy method setDelegate.

public void setDelegate(Object d) {
    Class delegateClass = d.getClass();
    try {
        for (Method m : delegateClass.getDeclaredMethods()) {
            if (m.getAnnotation(PostConstruct.class) != null) {
                postConstruct = m;
                prepareMethod(m);
            } else if (m.getAnnotation(PreDestroy.class) != null) {
                preDestroy = m;
                prepareMethod(m);
            } else if (m.getAnnotation(AroundInvoke.class) != null) {
                aroundInvoke = m;
                prepareMethod(m);
            } else if (m.getAnnotation(AroundTimeout.class) != null) {
                aroundTimeout = m;
                prepareMethod(m);
            } else if (m.getAnnotation(AroundConstruct.class) != null) {
                aroundConstruct = m;
                prepareMethod(m);
            }
        }
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
    delegate = d;
}
Also used : AroundConstruct(javax.interceptor.AroundConstruct) Method(java.lang.reflect.Method) PostConstruct(javax.annotation.PostConstruct) AroundInvoke(javax.interceptor.AroundInvoke) InvocationTargetException(java.lang.reflect.InvocationTargetException)

Example 45 with AroundInvoke

use of javax.interceptor.AroundInvoke in project Payara by payara.

the class TracedInterceptor method traceCdiCall.

/**
 * If the tracing is enabled and possible for the invoked method, traces it's execution.
 * If not, only executes the invocation context.
 *
 * @param invocationContext the context to be executed
 * @return result of the invocation context execution.
 * @throws Exception any execution thrown from the invocation context execution.
 */
@AroundInvoke
public Object traceCdiCall(final InvocationContext invocationContext) throws Exception {
    LOG.fine(() -> "traceCdiCall(" + invocationContext + ")");
    // Get the required HK2 services
    final PayaraTracingServices payaraTracingServices = new PayaraTracingServices();
    final OpenTracingService openTracing = payaraTracingServices.getOpenTracingService();
    final InvocationManager invocationManager = payaraTracingServices.getInvocationManager();
    // If Request Tracing is enabled, and this isn't a JaxRs method
    if (// 
    openTracing == null || !openTracing.isEnabled() || isJaxRsMethod(invocationContext) || isWebServiceMethod(invocationContext, invocationManager)) {
        // If request tracing was turned off, or this is a JaxRs method, just carry on
        LOG.finest("The call is already monitored by some different component, proceeding the invocation.");
        return invocationContext.proceed();
    }
    // Get the Traced annotation present on the method or class
    final Traced traced = getAnnotation(beanManager, Traced.class, invocationContext);
    // Get the enabled (value) variable from a config override, or from the annotation if there is no override
    final boolean tracingEnabled = OpenTracingCdiUtils.getConfigOverrideValue(Traced.class, "value", invocationContext, boolean.class).orElse(traced.value());
    // If we've explicitly been told not to trace the method: don't!
    if (!tracingEnabled) {
        LOG.finest("Tracing is not enabled, nothing to do.");
        return invocationContext.proceed();
    }
    // If we *have* been told to, get the application's Tracer instance and start an active span.
    final String applicationName = openTracing.getApplicationName(invocationManager, invocationContext);
    final Tracer tracer = openTracing.getTracer(applicationName);
    final String operationName = getOperationName(invocationContext, traced);
    Span parentSpan = tracer.activeSpan();
    final Span span = tracer.buildSpan(operationName).start();
    try (Scope scope = tracer.scopeManager().activate(span)) {
        try {
            return invocationContext.proceed();
        } catch (final Exception ex) {
            LOG.log(Level.FINEST, "Setting the error to the active span ...", ex);
            span.setTag(Tags.ERROR.getKey(), true);
            final Map<String, Object> errorInfoMap = new HashMap<>();
            errorInfoMap.put(Fields.EVENT, "error");
            errorInfoMap.put(Fields.ERROR_OBJECT, ex.getClass().getName());
            span.log(errorInfoMap);
            throw ex;
        }
    } finally {
        span.finish();
    }
}
Also used : Traced(org.eclipse.microprofile.opentracing.Traced) Scope(io.opentracing.Scope) Tracer(io.opentracing.Tracer) InvocationManager(org.glassfish.api.invocation.InvocationManager) OpenTracingService(fish.payara.opentracing.OpenTracingService) Span(io.opentracing.Span) HashMap(java.util.HashMap) Map(java.util.Map) PayaraTracingServices(fish.payara.requesttracing.jaxrs.client.PayaraTracingServices) AroundInvoke(javax.interceptor.AroundInvoke)

Aggregations

AroundInvoke (javax.interceptor.AroundInvoke)52 Method (java.lang.reflect.Method)10 InvocationManager (org.glassfish.api.invocation.InvocationManager)6 FaultToleranceService (fish.payara.microprofile.faulttolerance.FaultToleranceService)5 FallbackPolicy (fish.payara.microprofile.faulttolerance.interceptors.fallback.FallbackPolicy)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)5 TransactionalException (javax.transaction.TransactionalException)5 Config (org.eclipse.microprofile.config.Config)5 Fallback (org.eclipse.microprofile.faulttolerance.Fallback)5 PayaraCacheKeyInvocationContext (fish.payara.cdi.jsr107.implementation.PayaraCacheKeyInvocationContext)4 Meter (com.codahale.metrics.Meter)2 Timer (com.codahale.metrics.Timer)2 TransactionManagerHelper (com.sun.enterprise.transaction.TransactionManagerHelper)2 CallerAccessException (fish.payara.cdi.auth.roles.CallerAccessException)2 RolesPermitted (fish.payara.cdi.auth.roles.RolesPermitted)2 Parameter (java.lang.reflect.Parameter)2 Principal (java.security.Principal)2 ArrayList (java.util.ArrayList)2 NoSuchElementException (java.util.NoSuchElementException)2 Message (javax.jms.Message)2