Search in sources :

Example 1 with Context

use of jakarta.enterprise.context.spi.Context in project core by weld.

the class BeanManagerImpl method internalGetContext.

private Context internalGetContext(Class<? extends Annotation> scopeType) {
    Context activeContext = null;
    final List<Context> ctx = contexts.get(scopeType);
    if (ctx == null) {
        return null;
    }
    for (Context context : ctx) {
        if (context.isActive()) {
            if (activeContext == null) {
                activeContext = context;
            } else {
                throw BeanManagerLogger.LOG.duplicateActiveContexts(scopeType.getName());
            }
        }
    }
    return activeContext;
}
Also used : Context(jakarta.enterprise.context.spi.Context) WeldCreationalContext(org.jboss.weld.contexts.WeldCreationalContext) CreationalContext(jakarta.enterprise.context.spi.CreationalContext)

Example 2 with Context

use of jakarta.enterprise.context.spi.Context in project core by weld.

the class WeldStartup method createContexts.

protected Collection<ContextHolder<? extends Context>> createContexts(ServiceRegistry services) {
    List<ContextHolder<? extends Context>> contexts = new ArrayList<ContextHolder<? extends Context>>();
    BeanIdentifierIndex beanIdentifierIndex = services.get(BeanIdentifierIndex.class);
    /*
        * Register a full set of bound and unbound contexts. Although we may not use all of
        * these (e.g. if we are running in a servlet environment) they may be
        * useful for an application.
        */
    Set<Annotation> boundQualifires = ImmutableSet.<Annotation>builder().addAll(Bindings.DEFAULT_QUALIFIERS).add(BoundLiteral.INSTANCE).build();
    Set<Annotation> unboundQualifiers = ImmutableSet.<Annotation>builder().addAll(Bindings.DEFAULT_QUALIFIERS).add(UnboundLiteral.INSTANCE).build();
    contexts.add(new ContextHolder<ApplicationContext>(new ApplicationContextImpl(contextId), ApplicationContext.class, unboundQualifiers));
    contexts.add(new ContextHolder<SingletonContext>(new SingletonContextImpl(contextId), SingletonContext.class, unboundQualifiers));
    contexts.add(new ContextHolder<BoundSessionContext>(new BoundSessionContextImpl(contextId, beanIdentifierIndex), BoundSessionContext.class, boundQualifires));
    contexts.add(new ContextHolder<BoundConversationContext>(new BoundConversationContextImpl(contextId, services), BoundConversationContext.class, boundQualifires));
    contexts.add(new ContextHolder<BoundRequestContext>(new BoundRequestContextImpl(contextId), BoundRequestContext.class, boundQualifires));
    contexts.add(new ContextHolder<RequestContext>(new RequestContextImpl(contextId), RequestContext.class, unboundQualifiers));
    contexts.add(new ContextHolder<DependentContext>(new DependentContextImpl(services.get(ContextualStore.class)), DependentContext.class, unboundQualifiers));
    services.get(WeldModules.class).postContextRegistration(contextId, services, contexts);
    /*
        * Register the contexts with the bean manager and add the beans to the
        * deployment manager so that they are easily accessible (contexts are app
        * scoped)
        */
    for (ContextHolder<? extends Context> context : contexts) {
        deploymentManager.addContext(context.getContext());
        deploymentManager.addBean(ContextBean.of(context, deploymentManager));
    }
    return contexts;
}
Also used : ArrayList(java.util.ArrayList) BoundRequestContextImpl(org.jboss.weld.contexts.bound.BoundRequestContextImpl) RequestContextImpl(org.jboss.weld.contexts.unbound.RequestContextImpl) BoundConversationContext(org.jboss.weld.context.bound.BoundConversationContext) BeanIdentifierIndex(org.jboss.weld.serialization.BeanIdentifierIndex) BoundRequestContextImpl(org.jboss.weld.contexts.bound.BoundRequestContextImpl) BoundRequestContext(org.jboss.weld.context.bound.BoundRequestContext) ApplicationContext(org.jboss.weld.context.ApplicationContext) SingletonContext(org.jboss.weld.context.SingletonContext) BoundRequestContext(org.jboss.weld.context.bound.BoundRequestContext) RequestContext(org.jboss.weld.context.RequestContext) DependentContext(org.jboss.weld.context.DependentContext) DependentContext(org.jboss.weld.context.DependentContext) BoundRequestContext(org.jboss.weld.context.bound.BoundRequestContext) Context(jakarta.enterprise.context.spi.Context) SingletonContext(org.jboss.weld.context.SingletonContext) ApplicationContext(org.jboss.weld.context.ApplicationContext) BoundSessionContext(org.jboss.weld.context.bound.BoundSessionContext) BoundConversationContext(org.jboss.weld.context.bound.BoundConversationContext) RequestContext(org.jboss.weld.context.RequestContext) SingletonContextImpl(org.jboss.weld.contexts.unbound.SingletonContextImpl) BoundSessionContext(org.jboss.weld.context.bound.BoundSessionContext) WeldModules(org.jboss.weld.module.WeldModules) Annotation(java.lang.annotation.Annotation) DependentContextImpl(org.jboss.weld.contexts.unbound.DependentContextImpl) ContextualStore(org.jboss.weld.serialization.spi.ContextualStore) ApplicationContextImpl(org.jboss.weld.contexts.unbound.ApplicationContextImpl) BoundSessionContextImpl(org.jboss.weld.contexts.bound.BoundSessionContextImpl) BoundConversationContextImpl(org.jboss.weld.contexts.bound.BoundConversationContextImpl)

Example 3 with Context

use of jakarta.enterprise.context.spi.Context in project core by weld.

the class InstanceImpl method destroy.

@Override
public void destroy(T instance) {
    checkNotNull(instance);
    // Attempt to destroy instance which is either a client proxy or a dependent session bean proxy
    if (instance instanceof ProxyObject) {
        ProxyObject proxy = (ProxyObject) instance;
        if (proxy.weld_getHandler() instanceof ProxyMethodHandler) {
            ProxyMethodHandler handler = (ProxyMethodHandler) proxy.weld_getHandler();
            Bean<?> bean = handler.getBean();
            if (isSessionBeanProxy(instance) && Dependent.class.equals(bean.getScope())) {
                // Destroy internal reference to a dependent session bean
                destroyDependentInstance(instance);
                return;
            } else {
                // Destroy contextual instance of a normal-scoped bean
                Context context = getBeanManager().getContext(bean.getScope());
                if (context instanceof AlterableContext) {
                    AlterableContext alterableContext = (AlterableContext) context;
                    alterableContext.destroy(bean);
                    return;
                } else {
                    throw BeanLogger.LOG.destroyUnsupported(context);
                }
            }
        }
    }
    // Attempt to destroy dependent instance which is neither a client proxy nor a dependent session bean proxy
    destroyDependentInstance(instance);
}
Also used : WeldCreationalContext(org.jboss.weld.contexts.WeldCreationalContext) AlterableContext(jakarta.enterprise.context.spi.AlterableContext) Context(jakarta.enterprise.context.spi.Context) CreationalContext(jakarta.enterprise.context.spi.CreationalContext) ProxyObject(org.jboss.weld.bean.proxy.ProxyObject) Dependent(jakarta.enterprise.context.Dependent) AlterableContext(jakarta.enterprise.context.spi.AlterableContext) ProxyMethodHandler(org.jboss.weld.bean.proxy.ProxyMethodHandler)

Example 4 with Context

use of jakarta.enterprise.context.spi.Context in project helidon by oracle.

the class ExtendedEntityManager method acquireDelegate.

/*
     * Instance methods.
     */
/**
 * Acquires and returns the delegate {@link EntityManager} that
 * this {@link ExtendedEntityManager} must use according to the
 * rules for extended persistence contexts spelled out in the JPA
 * specification.
 *
 * <p>This method never returns {@code null}.</p>
 *
 * @return the delegate {@link EntityManager}; never {@code null}
 */
@Override
@SuppressWarnings("checkstyle:MethodLength")
protected EntityManager acquireDelegate() {
    // This is very tricky.  Pay attention.
    // 
    // An extended EntityManager's persistence context (its "bag"
    // of "managed", not "detached", entities) spans transactions.
    // 
    // In this CDI-centric implementation, we make use of
    // jakarta.transaction.TransactionScoped to serve up
    // EntityManager instances in true JTA transaction scope.
    // That means those objects are destroyed when the transaction
    // is destroyed.  Obviously therefore they cannot be used as
    // the sole basis for the transaction-respecting bits of an
    // extended EntityManager.
    // 
    // However, an extended EntityManager must "become" the sole
    // EntityManager associated with a JTA transaction, and then
    // must dissociate from it after it has committed or rolled
    // back.
    // 
    // So we make use of the fact that the @TransactionScoped bean
    // that has been installed is going to produce instances of
    // CdiTransactionScopedEntityManager.  This
    // DelegatingEntityManager subclass allows you to set _its_
    // delegate, provided it has not yet been set, and allows you
    // to control whether or not its delegate is actually closed
    // when _it_ is closed.  This lets us "tunnel" another
    // EntityManager "into" transaction scope.
    final EntityManager returnValue;
    final Context context = transactionSupport.getContext();
    if (context == null || !context.isActive()) {
        if (this.delegate == null) {
            assert this.subdelegate == null;
            // For the first time during the lifespan of this
            // object, create its delegate.  It will be a "normal"
            // EntityManager.  We don't set our subdelegate
            // because that is only set in transactional cases
            // (see below).
            this.delegate = EntityManagers.createContainerManagedEntityManager(this.instance, this.suppliedQualifiers);
        } else if (this.delegate instanceof CdiTransactionScopedEntityManager) {
            // (see later in this method for proof).
            assert this.subdelegate != null;
            assert !(this.subdelegate instanceof CdiTransactionScopedEntityManager);
            assert this.subdelegate.isOpen();
            // We are an extended EntityManager, so take that old
            // "normal" EntityManager subdelegate that we know was
            // "tunneled" into our "stale"
            // CdiTransactionScopedEntityManager delegate, and
            // "pull it out" to be our delegate.  We can discard
            // the stale CdiTransactionScopedEntityManager at this
            // point, which we do by just overwriting its
            // reference.
            this.delegate = this.subdelegate;
            // Now set our subdelegate to null to help indicate that
            // we're no longer in a transactional situation.
            this.subdelegate = null;
        }
        // situation.
        assert this.delegate != null;
        assert !(this.delegate instanceof CdiTransactionScopedEntityManager);
        assert this.delegate.isOpen();
        assert this.subdelegate == null;
        returnValue = this.delegate;
    } else {
        if (this.delegate != null && !this.delegate.isOpen()) {
            // subdelegate field.
            assert this.delegate instanceof CdiTransactionScopedEntityManager;
            assert this.subdelegate != null;
            assert !(this.subdelegate instanceof CdiTransactionScopedEntityManager);
            assert this.subdelegate.isOpen();
            this.delegate = this.subdelegate;
            this.subdelegate = null;
        }
        if (!(this.delegate instanceof CdiTransactionScopedEntityManager)) {
            // not a CdiTransactionScopedEntityManager.
            assert this.subdelegate == null;
            assert this.delegate == null ? true : this.delegate.isOpen();
            // Since we're in a transaction, we have to look for
            // the @TransactionScoped EntityManager that is
            // associated with the JTA transaction.  So look for
            // an EntityManager bean annotated with, among other
            // possible things, @CdiTransactionScoped
            // and @ContainerManaged.
            final Set<Annotation> selectionQualifiers = new HashSet<>(this.suppliedQualifiers);
            selectionQualifiers.remove(Extended.Literal.INSTANCE);
            selectionQualifiers.remove(JpaTransactionScoped.Literal.INSTANCE);
            selectionQualifiers.remove(NonTransactional.Literal.INSTANCE);
            selectionQualifiers.add(CdiTransactionScoped.Literal.INSTANCE);
            selectionQualifiers.add(ContainerManaged.Literal.INSTANCE);
            final Set<Bean<?>> cdiTransactionScopedEntityManagerBeans = this.beanManager.getBeans(CdiTransactionScopedEntityManager.class, selectionQualifiers.toArray(new Annotation[selectionQualifiers.size()]));
            assert cdiTransactionScopedEntityManagerBeans != null;
            assert !cdiTransactionScopedEntityManagerBeans.isEmpty();
            @SuppressWarnings("unchecked") final Bean<?> cdiTransactionScopedEntityManagerBean = (Bean<CdiTransactionScopedEntityManager>) this.beanManager.resolve(cdiTransactionScopedEntityManagerBeans);
            assert cdiTransactionScopedEntityManagerBean != null;
            assert context.getScope().equals(cdiTransactionScopedEntityManagerBean.getScope());
            // Using that bean, check the Context to see if there's
            // already a container-managed EntityManager enrolled in
            // the transaction (without accidentally creating a new
            // one, hence the single-argument Context#get(Contextual)
            // invocation, not the dual-argument
            // Context#get(Contextual, CreationalContext) one).  We
            // have to do this to honor section 7.6.3.1 of the JPA
            // specification.
            final Object existingContainerManagedCdiTransactionScopedEntityManager = context.get(cdiTransactionScopedEntityManagerBean);
            if (existingContainerManagedCdiTransactionScopedEntityManager != null) {
                // transactional or not.
                throw new CreationException(Messages.format("preexistingExtendedEntityManager", cdiTransactionScopedEntityManagerBean, existingContainerManagedCdiTransactionScopedEntityManager));
            }
            // OK, there's no existing CDI-transaction-scoped
            // EntityManager.  Let's cause one to be created.
            @SuppressWarnings("unchecked") final CdiTransactionScopedEntityManager cdiTransactionScopedEntityManager = (CdiTransactionScopedEntityManager) this.beanManager.getReference(cdiTransactionScopedEntityManagerBean, CdiTransactionScopedEntityManager.class, this.beanManager.createCreationalContext(cdiTransactionScopedEntityManagerBean));
            assert cdiTransactionScopedEntityManager != null;
            // "through" to be *its* delegate.
            if (this.delegate == null) {
                this.subdelegate = EntityManagers.createContainerManagedEntityManager(this.instance, this.suppliedQualifiers);
            } else {
                assert !(this.delegate instanceof CdiTransactionScopedEntityManager);
                assert this.subdelegate == null;
                this.subdelegate = this.delegate;
            }
            assert this.subdelegate != null;
            cdiTransactionScopedEntityManager.setDelegate(this.subdelegate);
            this.delegate = cdiTransactionScopedEntityManager;
            // extended EntityManager.
            if (this.isSynchronized) {
                this.delegate.joinTransaction();
            }
        }
        assert this.delegate != null;
        assert this.delegate.isOpen();
        returnValue = this.delegate;
    }
    return returnValue;
}
Also used : Context(jakarta.enterprise.context.spi.Context) EntityManager(jakarta.persistence.EntityManager) CreationException(jakarta.enterprise.inject.CreationException) Annotation(java.lang.annotation.Annotation) HashSet(java.util.HashSet) Bean(jakarta.enterprise.inject.spi.Bean)

Example 5 with Context

use of jakarta.enterprise.context.spi.Context in project helidon by oracle.

the class JpaTransactionScopedEntityManager method acquireDelegate.

/**
 * Acquires and returns a delegate {@link EntityManager}, adhering
 * to the rules spelled out by the JPA specification around
 * transaction-scoped {@link EntityManager}s.
 *
 * <p>This method never returns {@code null}.</p>
 *
 * <p>If a {@linkplain TransactionSupport#inTransaction() JTA
 * transaction is active}, then an {@link EntityManager} that is
 * joined to it is returned.  Otherwise a non-transactional {@link
 * EntityManager} is returned.</p>
 *
 * <p>Recall that this method is invoked by all {@link
 * DelegatingEntityManager} methods.</p>
 *
 * @return a non-{@code null} {@link EntityManager} that will be
 * used as this {@link JpaTransactionScopedEntityManager}'s
 * delegate
 */
@Override
protected EntityManager acquireDelegate() {
    final EntityManager returnValue;
    final int status = this.transactionSupport.getStatus();
    switch(status) {
        case TransactionSupport.STATUS_ACTIVE:
            // If we are or were just in a transaction, then we're
            // obligated to see if there's a transaction-scoped
            // EntityManager already affiliated with the current
            // transaction.  If there is, and its synchronization type
            // doesn't match ours, we're supposed to throw an
            // exception.  Remember that the transaction-scoped
            // context can go inactive at any point due to a rollback
            // on another thread, and may already be inactive at
            // *this* point.  This also means the status that dropped
            // us into this case statement may be stale.
            final Context transactionScopedContext = this.transactionSupport.getContext();
            if (transactionScopedContext == null || !transactionScopedContext.isActive()) {
                returnValue = this.nonTransactionalEntityManager;
            } else {
                EntityManager candidateReturnValue = this.cdiTransactionScopedEntityManager;
                try {
                    final Object existingContextualInstance = transactionScopedContext.get(this.oppositeSynchronizationBean);
                    if (existingContextualInstance != null) {
                        // exception.
                        throw new PersistenceException(Messages.format("mixedSynchronizationTypes", this.oppositeSynchronizationBean, existingContextualInstance));
                    }
                } catch (final ContextNotActiveException contextNotActiveException) {
                    candidateReturnValue = this.nonTransactionalEntityManager;
                } finally {
                    returnValue = candidateReturnValue;
                }
            }
            break;
        default:
            returnValue = this.nonTransactionalEntityManager;
            break;
    }
    assert returnValue != null;
    return returnValue;
}
Also used : Context(jakarta.enterprise.context.spi.Context) ReferenceCountedContext(io.helidon.integrations.cdi.referencecountedcontext.ReferenceCountedContext) EntityManager(jakarta.persistence.EntityManager) ContextNotActiveException(jakarta.enterprise.context.ContextNotActiveException) PersistenceException(jakarta.persistence.PersistenceException)

Aggregations

Context (jakarta.enterprise.context.spi.Context)11 CreationalContext (jakarta.enterprise.context.spi.CreationalContext)4 EntityManager (jakarta.persistence.EntityManager)3 Annotation (java.lang.annotation.Annotation)3 ContextNotActiveException (jakarta.enterprise.context.ContextNotActiveException)2 Dependent (jakarta.enterprise.context.Dependent)2 AlterableContext (jakarta.enterprise.context.spi.AlterableContext)2 Bean (jakarta.enterprise.inject.spi.Bean)2 BeanManager (jakarta.enterprise.inject.spi.BeanManager)2 ProxyObject (org.jboss.weld.bean.proxy.ProxyObject)2 WeldCreationalContext (org.jboss.weld.contexts.WeldCreationalContext)2 ReferenceCountedContext (io.helidon.integrations.cdi.referencecountedcontext.ReferenceCountedContext)1 ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)1 RequestScoped (jakarta.enterprise.context.RequestScoped)1 RequestContextController (jakarta.enterprise.context.control.RequestContextController)1 CreationException (jakarta.enterprise.inject.CreationException)1 AnnotatedType (jakarta.enterprise.inject.spi.AnnotatedType)1 InjectionPoint (jakarta.enterprise.inject.spi.InjectionPoint)1 InterceptionType (jakarta.enterprise.inject.spi.InterceptionType)1 ProcessInjectionPoint (jakarta.enterprise.inject.spi.ProcessInjectionPoint)1