Search in sources :

Example 1 with Interceptor

use of org.jboss.invocation.Interceptor in project wildfly by wildfly.

the class StatefulSessionSynchronizationInterceptorTestCase method testDifferentTx.

/**
 * After the bean is accessed within a tx and the tx has committed, the
 * association should be gone (and thus it is ready for another tx).
 */
@Test
public void testDifferentTx() throws Exception {
    final Interceptor interceptor = new StatefulSessionSynchronizationInterceptor(true);
    final InterceptorContext context = new InterceptorContext();
    context.setInterceptors(Arrays.asList(noop()));
    final StatefulSessionComponent component = mock(StatefulSessionComponent.class);
    context.putPrivateData(Component.class, component);
    when(component.getAccessTimeout(null)).thenReturn(defaultAccessTimeout());
    Cache<SessionID, StatefulSessionComponentInstance> cache = mock(Cache.class);
    when(component.getCache()).thenReturn(cache);
    Supplier<SessionID> identifierFactory = mock(Supplier.class);
    when(cache.getIdentifierFactory()).thenReturn(identifierFactory);
    final TransactionSynchronizationRegistry transactionSynchronizationRegistry = mock(TransactionSynchronizationRegistry.class);
    when(component.getTransactionSynchronizationRegistry()).thenReturn(transactionSynchronizationRegistry);
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX1");
    final List<Synchronization> synchronizations = new LinkedList<Synchronization>();
    doAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocation) throws Throwable {
            Synchronization synchronization = (Synchronization) invocation.getArguments()[0];
            synchronizations.add(synchronization);
            return null;
        }
    }).when(transactionSynchronizationRegistry).registerInterposedSynchronization((Synchronization) any());
    final StatefulSessionComponentInstance instance = new StatefulSessionComponentInstance(component, org.jboss.invocation.Interceptors.getTerminalInterceptor(), Collections.EMPTY_MAP, Collections.emptyMap());
    context.putPrivateData(ComponentInstance.class, instance);
    interceptor.processInvocation(context);
    // commit
    for (Synchronization synchronization : synchronizations) {
        synchronization.beforeCompletion();
    }
    for (Synchronization synchronization : synchronizations) {
        synchronization.afterCompletion(Status.STATUS_COMMITTED);
    }
    synchronizations.clear();
    when(transactionSynchronizationRegistry.getTransactionKey()).thenReturn("TX2");
    interceptor.processInvocation(context);
}
Also used : Synchronization(javax.transaction.Synchronization) LinkedList(java.util.LinkedList) TransactionSynchronizationRegistry(javax.transaction.TransactionSynchronizationRegistry) InvocationOnMock(org.mockito.invocation.InvocationOnMock) InterceptorContext(org.jboss.invocation.InterceptorContext) Interceptor(org.jboss.invocation.Interceptor) SessionID(org.jboss.ejb.client.SessionID) Test(org.junit.Test)

Example 2 with Interceptor

use of org.jboss.invocation.Interceptor in project wildfly by wildfly.

the class EJBSecurityViewConfigurator method handlePermissions.

private boolean handlePermissions(String contextID, ComponentConfiguration componentConfiguration, ViewConfiguration viewConfiguration, DeploymentReflectionIndex deploymentReflectionIndex, String viewClassName, EJBViewDescription ejbViewDescription, Method viewMethod, ApplicableMethodInformation<EJBMethodSecurityAttribute> permissions, boolean annotations, final EJBViewMethodSecurityAttributesService.Builder viewMethodSecurityAttributesServiceBuilder, EJBComponentDescription componentDescription, boolean elytronSecurityDomain, final String resolvedSecurityDomain) {
    EJBMethodSecurityAttribute ejbMethodSecurityMetaData = permissions.getViewAttribute(ejbViewDescription.getMethodIntf(), viewMethod);
    final List<EJBMethodSecurityAttribute> allAttributes = new ArrayList<EJBMethodSecurityAttribute>();
    allAttributes.addAll(permissions.getAllAttributes(ejbViewDescription.getMethodIntf(), viewMethod));
    if (ejbMethodSecurityMetaData == null) {
        ejbMethodSecurityMetaData = permissions.getViewAttribute(MethodIntf.BEAN, viewMethod);
    }
    allAttributes.addAll(permissions.getAllAttributes(MethodIntf.BEAN, viewMethod));
    final Method classMethod = ClassReflectionIndexUtil.findMethod(deploymentReflectionIndex, componentConfiguration.getComponentClass(), viewMethod);
    if (ejbMethodSecurityMetaData == null && classMethod != null) {
        // if this is null we try with the corresponding bean method
        ejbMethodSecurityMetaData = permissions.getAttribute(ejbViewDescription.getMethodIntf(), classMethod);
        if (ejbMethodSecurityMetaData == null) {
            ejbMethodSecurityMetaData = permissions.getAttribute(MethodIntf.BEAN, classMethod);
        }
    }
    if (classMethod != null) {
        allAttributes.addAll(permissions.getAllAttributes(ejbViewDescription.getMethodIntf(), classMethod));
        allAttributes.addAll(permissions.getAllAttributes(MethodIntf.BEAN, classMethod));
    }
    // we do not add the security interceptor if there is no security information
    if (ejbMethodSecurityMetaData != null) {
        if (!annotations && !ejbMethodSecurityMetaData.isDenyAll() && !ejbMethodSecurityMetaData.isPermitAll()) {
            // roles are additive when defined in the deployment descriptor
            final Set<String> rolesAllowed = new HashSet<String>();
            for (EJBMethodSecurityAttribute attr : allAttributes) {
                rolesAllowed.addAll(attr.getRolesAllowed());
            }
            ejbMethodSecurityMetaData = EJBMethodSecurityAttribute.rolesAllowed(rolesAllowed);
        }
        // build the EJBViewMethodSecurityAttributesService to expose these security attributes to other components like WS (@see https://issues.jboss.org/browse/WFLY-308)
        if (viewMethodSecurityAttributesServiceBuilder != null) {
            viewMethodSecurityAttributesServiceBuilder.addMethodSecurityMetadata(viewMethod, ejbMethodSecurityMetaData);
        }
        if (ejbMethodSecurityMetaData.isPermitAll()) {
            // no need to add authorizing interceptor
            return true;
        }
        // add the interceptor
        final Interceptor authorizationInterceptor;
        if (elytronSecurityDomain) {
            if (ejbMethodSecurityMetaData.isDenyAll()) {
                authorizationInterceptor = RolesAllowedInterceptor.DENY_ALL;
            } else {
                if (componentDescription.requiresJacc()) {
                    authorizationInterceptor = new JaccInterceptor(viewClassName, viewMethod);
                } else {
                    authorizationInterceptor = new RolesAllowedInterceptor(ejbMethodSecurityMetaData.getRolesAllowed());
                }
            }
        } else {
            throw ROOT_LOGGER.legacySecurityUnsupported(resolvedSecurityDomain);
        }
        viewConfiguration.addViewInterceptor(viewMethod, new ImmediateInterceptorFactory(authorizationInterceptor), InterceptorOrder.View.EJB_SECURITY_AUTHORIZATION_INTERCEPTOR);
        return true;
    }
    return false;
}
Also used : ImmediateInterceptorFactory(org.jboss.invocation.ImmediateInterceptorFactory) ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) Interceptor(org.jboss.invocation.Interceptor) HashSet(java.util.HashSet)

Example 3 with Interceptor

use of org.jboss.invocation.Interceptor in project wildfly by wildfly.

the class BasicComponent method createInterceptors.

protected void createInterceptors(InterceptorFactoryContext context) {
    // Create the post-construct interceptors for the ComponentInstance
    postConstructInterceptor = this.postConstruct.create(context);
    // create the pre-destroy interceptors
    preDestroyInterceptor = this.getPreDestroy().create(context);
    final Map<Method, InterceptorFactory> interceptorFactoryMap = this.getInterceptorFactoryMap();
    // This is an identity map.  This means that only <b>certain</b> {@code Method} objects will
    // match - specifically, they must equal the objects provided to the proxy.
    final IdentityHashMap<Method, Interceptor> interceptorMap = new IdentityHashMap<Method, Interceptor>();
    for (Method method : interceptorFactoryMap.keySet()) {
        interceptorMap.put(method, interceptorFactoryMap.get(method).create(context));
    }
    this.interceptorInstanceMap = interceptorMap;
}
Also used : InterceptorFactory(org.jboss.invocation.InterceptorFactory) IdentityHashMap(java.util.IdentityHashMap) Method(java.lang.reflect.Method) Interceptor(org.jboss.invocation.Interceptor)

Example 4 with Interceptor

use of org.jboss.invocation.Interceptor in project wildfly by wildfly.

the class StatefulComponentDescription method createConfiguration.

@Override
public ComponentConfiguration createConfiguration(final ClassReflectionIndex classIndex, final ClassLoader moduleClassLoader, final ModuleLoader moduleLoader) {
    final ComponentConfiguration statefulComponentConfiguration = new ComponentConfiguration(this, classIndex, moduleClassLoader, moduleLoader);
    // setup the component create service
    statefulComponentConfiguration.setComponentCreateServiceFactory(new StatefulComponentCreateServiceFactory());
    if (getTransactionManagementType() == TransactionManagementType.BEAN) {
        getConfigurators().add(new ComponentConfigurator() {

            @Override
            public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
                final ComponentInstanceInterceptorFactory bmtComponentInterceptorFactory = new ComponentInstanceInterceptorFactory() {

                    @Override
                    protected Interceptor create(Component component, InterceptorFactoryContext context) {
                        if (!(component instanceof StatefulSessionComponent)) {
                            throw EjbLogger.ROOT_LOGGER.componentNotInstanceOfSessionComponent(component, component.getComponentClass(), "stateful");
                        }
                        return new StatefulBMTInterceptor((StatefulSessionComponent) component);
                    }
                };
                configuration.addComponentInterceptor(bmtComponentInterceptorFactory, InterceptorOrder.Component.BMT_TRANSACTION_INTERCEPTOR, false);
            }
        });
    } else {
        getConfigurators().add(new ComponentConfigurator() {

            @Override
            public void configure(final DeploymentPhaseContext context, final ComponentDescription description, final ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
                final EEApplicationClasses applicationClasses = context.getDeploymentUnit().getAttachment(Attachments.EE_APPLICATION_CLASSES_DESCRIPTION);
                InterceptorClassDescription interceptorConfig = ComponentDescription.mergeInterceptorConfig(configuration.getComponentClass(), applicationClasses.getClassByName(description.getComponentClassName()), description, MetadataCompleteMarker.isMetadataComplete(context.getDeploymentUnit()));
                configuration.addPostConstructInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostConstruct(), false), InterceptorOrder.ComponentPostConstruct.TRANSACTION_INTERCEPTOR);
                configuration.addPreDestroyInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPreDestroy(), false), InterceptorOrder.ComponentPreDestroy.TRANSACTION_INTERCEPTOR);
                if (description.isPassivationApplicable()) {
                    configuration.addPrePassivateInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPrePassivate(), false), InterceptorOrder.ComponentPassivation.TRANSACTION_INTERCEPTOR);
                    configuration.addPostActivateInterceptor(new LifecycleCMTTxInterceptor.Factory(interceptorConfig.getPostActivate(), false), InterceptorOrder.ComponentPassivation.TRANSACTION_INTERCEPTOR);
                }
            }
        });
    }
    addStatefulSessionSynchronizationInterceptor();
    this.getConfigurators().add(new ComponentConfigurator() {

        @Override
        public void configure(DeploymentPhaseContext context, ComponentDescription description, ComponentConfiguration configuration) throws DeploymentUnitProcessingException {
            DeploymentUnit unit = context.getDeploymentUnit();
            CapabilityServiceSupport support = unit.getAttachment(org.jboss.as.server.deployment.Attachments.CAPABILITY_SERVICE_SUPPORT);
            StatefulComponentDescription statefulDescription = (StatefulComponentDescription) description;
            ServiceTarget target = context.getServiceTarget();
            ServiceBuilder<?> builder = target.addService(statefulDescription.getCacheFactoryServiceName().append("installer"));
            Supplier<CacheFactoryBuilder<SessionID, StatefulSessionComponentInstance>> cacheFactoryBuilder = builder.requires(this.getCacheFactoryBuilderRequirement(statefulDescription));
            Service service = new ChildTargetService(new Consumer<ServiceTarget>() {

                @Override
                public void accept(ServiceTarget target) {
                    cacheFactoryBuilder.get().getServiceConfigurator(unit, statefulDescription, configuration).configure(support).build(target).install();
                }
            });
            builder.setInstance(service).install();
        }

        private ServiceName getCacheFactoryBuilderRequirement(StatefulComponentDescription description) {
            if (!description.isPassivationApplicable()) {
                return CacheFactoryBuilderServiceNameProvider.DEFAULT_PASSIVATION_DISABLED_CACHE_SERVICE_NAME;
            }
            CacheInfo cache = description.getCache();
            return (cache != null) ? new CacheFactoryBuilderServiceNameProvider(cache.getName()).getServiceName() : CacheFactoryBuilderServiceNameProvider.DEFAULT_CACHE_SERVICE_NAME;
        }
    });
    return statefulComponentConfiguration;
}
Also used : DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) SessionBeanComponentDescription(org.jboss.as.ejb3.component.session.SessionBeanComponentDescription) ComponentDescription(org.jboss.as.ee.component.ComponentDescription) ComponentConfigurator(org.jboss.as.ee.component.ComponentConfigurator) ComponentTypeIdentityInterceptorFactory(org.jboss.as.ejb3.component.interceptors.ComponentTypeIdentityInterceptorFactory) InterceptorFactory(org.jboss.invocation.InterceptorFactory) ImmediateInterceptorFactory(org.jboss.invocation.ImmediateInterceptorFactory) ComponentInstanceInterceptorFactory(org.jboss.as.ee.component.ComponentInstanceInterceptorFactory) StatefulBMTInterceptor(org.jboss.as.ejb3.tx.StatefulBMTInterceptor) DeploymentPhaseContext(org.jboss.as.server.deployment.DeploymentPhaseContext) InterceptorFactoryContext(org.jboss.invocation.InterceptorFactoryContext) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) ServiceBuilder(org.jboss.msc.service.ServiceBuilder) InterceptorClassDescription(org.jboss.as.ee.component.interceptors.InterceptorClassDescription) Consumer(java.util.function.Consumer) Supplier(java.util.function.Supplier) Component(org.jboss.as.ee.component.Component) LifecycleCMTTxInterceptor(org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor) Interceptor(org.jboss.invocation.Interceptor) StatefulBMTInterceptor(org.jboss.as.ejb3.tx.StatefulBMTInterceptor) CacheInfo(org.jboss.as.ejb3.cache.CacheInfo) ComponentInstanceInterceptorFactory(org.jboss.as.ee.component.ComponentInstanceInterceptorFactory) ChildTargetService(org.wildfly.clustering.service.ChildTargetService) ServiceTarget(org.jboss.msc.service.ServiceTarget) Service(org.jboss.msc.Service) ChildTargetService(org.wildfly.clustering.service.ChildTargetService) CacheFactoryBuilderServiceNameProvider(org.jboss.as.ejb3.cache.CacheFactoryBuilderServiceNameProvider) ComponentConfiguration(org.jboss.as.ee.component.ComponentConfiguration) EEApplicationClasses(org.jboss.as.ee.component.EEApplicationClasses) ServiceName(org.jboss.msc.service.ServiceName) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) SessionID(org.jboss.ejb.client.SessionID)

Example 5 with Interceptor

use of org.jboss.invocation.Interceptor in project wildfly by wildfly.

the class AsyncFutureInterceptorFactory method create.

@Override
public Interceptor create(final InterceptorFactoryContext context) {
    final SessionBeanComponent component = (SessionBeanComponent) context.getContextData().get(Component.class);
    if (component.isSecurityDomainKnown()) {
        return new Interceptor() {

            @Override
            public Object processInvocation(final InterceptorContext context) throws Exception {
                if (!context.isBlockingCaller()) {
                    return context.proceed();
                }
                final InterceptorContext asyncInterceptorContext = context.clone();
                asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
                final CancellationFlag flag = new CancellationFlag();
                final SecurityDomain securityDomain = context.getPrivateData(SecurityDomain.class);
                final StartupCountdown.Frame frame = StartupCountdown.current();
                final SecurityIdentity currentIdentity = securityDomain == null ? null : securityDomain.getCurrentSecurityIdentity();
                Callable<Object> invocationTask = () -> {
                    StartupCountdown.restore(frame);
                    try {
                        return asyncInterceptorContext.proceed();
                    } finally {
                        StartupCountdown.restore(null);
                    }
                };
                final AsyncInvocationTask task = new AsyncInvocationTask(flag) {

                    @Override
                    protected Object runInvocation() throws Exception {
                        if (currentIdentity != null) {
                            return currentIdentity.runAs(invocationTask);
                        } else {
                            return invocationTask.call();
                        }
                    }
                };
                asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
                asyncInterceptorContext.setBlockingCaller(false);
                return execute(component, task);
            }
        };
    } else {
        return new Interceptor() {

            @Override
            public Object processInvocation(final InterceptorContext context) throws Exception {
                if (!context.isBlockingCaller()) {
                    return context.proceed();
                }
                final InterceptorContext asyncInterceptorContext = context.clone();
                asyncInterceptorContext.putPrivateData(InvocationType.class, InvocationType.ASYNC);
                final CancellationFlag flag = new CancellationFlag();
                final StartupCountdown.Frame frame = StartupCountdown.current();
                final AsyncInvocationTask task = new AsyncInvocationTask(flag) {

                    @Override
                    protected Object runInvocation() throws Exception {
                        StartupCountdown.restore(frame);
                        try {
                            return asyncInterceptorContext.proceed();
                        } finally {
                            StartupCountdown.restore(null);
                        }
                    }
                };
                asyncInterceptorContext.putPrivateData(CancellationFlag.class, flag);
                asyncInterceptorContext.setBlockingCaller(false);
                return execute(component, task);
            }
        };
    }
}
Also used : SecurityIdentity(org.wildfly.security.auth.server.SecurityIdentity) SessionBeanComponent(org.jboss.as.ejb3.component.session.SessionBeanComponent) InterceptorContext(org.jboss.invocation.InterceptorContext) Component(org.jboss.as.ee.component.Component) SessionBeanComponent(org.jboss.as.ejb3.component.session.SessionBeanComponent) Interceptor(org.jboss.invocation.Interceptor) StartupCountdown(org.jboss.as.ee.component.deployers.StartupCountdown) SecurityDomain(org.wildfly.security.auth.server.SecurityDomain)

Aggregations

Interceptor (org.jboss.invocation.Interceptor)15 InterceptorContext (org.jboss.invocation.InterceptorContext)8 Method (java.lang.reflect.Method)4 InterceptorFactory (org.jboss.invocation.InterceptorFactory)4 ImmediateInterceptorFactory (org.jboss.invocation.ImmediateInterceptorFactory)3 Component (org.jboss.as.ee.component.Component)2 ComponentConfiguration (org.jboss.as.ee.component.ComponentConfiguration)2 LifecycleCMTTxInterceptor (org.jboss.as.ejb3.tx.LifecycleCMTTxInterceptor)2 DeploymentPhaseContext (org.jboss.as.server.deployment.DeploymentPhaseContext)2 DeploymentUnitProcessingException (org.jboss.as.server.deployment.DeploymentUnitProcessingException)2 SessionID (org.jboss.ejb.client.SessionID)2 SimpleInterceptorFactoryContext (org.jboss.invocation.SimpleInterceptorFactoryContext)2 SecurityDomain (org.wildfly.security.auth.server.SecurityDomain)2 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 IdentityHashMap (java.util.IdentityHashMap)1 LinkedList (java.util.LinkedList)1 Map (java.util.Map)1 Consumer (java.util.function.Consumer)1