javax.enterprise.context.ContextNotActiveException Java Examples

The following examples show how to use javax.enterprise.context.ContextNotActiveException. 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: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Request scoped bean and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesRequestScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(RequestScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-REQUEST", propagateCDI,
                selectedInstance.get());
    } 
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #2
Source Project: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Session scoped bean and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesSessionScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(SessionScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-SESSION", propagateCDI,
                selectedInstance.get());
    }
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #3
Source Project: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Conversation scoped beans and verify
 * the state is propagated to the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxPropagatesConversationScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(ConversationScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagateCDI = ManagedExecutor.builder().propagated(ThreadContext.CDI)
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<ConversationScopedBean> selectedInstance = instance.select(ConversationScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(true, "testCDI_ME_Ctx_Propagate-CONVERSATION", propagateCDI,
                selectedInstance.get());
    }
    finally {
        propagateCDI.shutdown();
    }
}
 
Example #4
Source Project: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Request scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsRequestScopedBean() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(RequestScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<RequestScopedBean> selectedInstance = instance.select(RequestScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-REQUEST", propagatedNone,
                selectedInstance.get());
    } 
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #5
Source Project: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Session scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsSessionScopedBeans() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(SessionScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<SessionScopedBean> selectedInstance = instance.select(SessionScopedBean.class);
    assertTrue(selectedInstance.isResolvable());

    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-SESSION", propagatedNone,
                selectedInstance.get());
    }
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #6
Source Project: microprofile-context-propagation   Author: eclipse   File: CDIContextTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Set some state on Conversation scoped bean and verify
 * the state is cleared on the thread where the other task runs.
 *
 * If the CDI context in question is not active, the test is deemed successful as there is no propagation to be done.
 *
 * @throws Exception indicates test failure
 */
@Test
public void testCDIMECtxClearsConversationScopedBeans() throws Exception {
    // check if given context is active, if it isn't test ends successfully
    try {
        bm.getContext(ConversationScoped.class);
    } catch (ContextNotActiveException e) {
        return;
    }

    ManagedExecutor propagatedNone = ManagedExecutor.builder()
            .propagated() // none
            .cleared(ThreadContext.ALL_REMAINING)
            .build();

    Instance<ConversationScopedBean> selectedInstance = instance.select(ConversationScopedBean.class);
    assertTrue(selectedInstance.isResolvable());
    try {
        checkCDIPropagation(false, "testCDI_ME_Ctx_Clear-CONVERSATION", propagatedNone,
                selectedInstance.get());
    }
    finally {
        propagatedNone.shutdown();
    }
}
 
Example #7
Source Project: quarkus   Author: quarkusio   File: TransactionScopedTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void transactionScopedInTransaction() throws Exception {
    tx.begin();
    beanTransactional.setValue(42);
    assertEquals(42, beanTransactional.getValue(), "Transaction scope did not save the value");
    Transaction suspendedTransaction = tm.suspend();

    assertThrows(ContextNotActiveException.class, () -> {
        beanTransactional.getValue();
    }, "Not expecting to have available TransactionScoped bean outside of the transaction");

    tx.begin();
    beanTransactional.setValue(1);
    assertEquals(1, beanTransactional.getValue(), "Transaction scope did not save the value");
    tx.commit();

    assertThrows(ContextNotActiveException.class, () -> {
        beanTransactional.getValue();
    }, "Not expecting to have available TransactionScoped bean outside of the transaction");

    tm.resume(suspendedTransaction);
    assertEquals(42, beanTransactional.getValue(), "Transaction scope did not resumed correctly");
    tx.rollback();
}
 
Example #8
Source Project: quarkus   Author: quarkusio   File: InstanceHandleImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void destroy() {
    if (instance != null && destroyed.compareAndSet(false, true)) {
        if (destroyLogic != null) {
            destroyLogic.accept(instance);
        } else {
            if (bean.getScope().equals(Dependent.class)) {
                destroyInternal();
            } else {
                InjectableContext context = Arc.container().getActiveContext(bean.getScope());
                if (context == null) {
                    throw new ContextNotActiveException(
                            "Cannot destroy instance of " + bean + " - no active context found for: " + bean.getScope());
                }
                context.destroy(bean);
            }
        }
    }
}
 
Example #9
Source Project: quarkus   Author: quarkusio   File: RequestContext.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    if (contextual == null) {
        throw new IllegalArgumentException("Contextual parameter must not be null");
    }
    Map<Contextual<?>, ContextInstanceHandle<?>> ctx = currentContext.get();
    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }
    ContextInstanceHandle<T> instance = (ContextInstanceHandle<T>) ctx.get(contextual);
    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextInstanceHandleImpl<T>((InjectableBean<T>) contextual,
                contextual.create(creationalContext), creationalContext);
        ctx.put(contextual, instance);
    }
    return instance != null ? instance.get() : null;
}
 
Example #10
Source Project: quarkus   Author: quarkusio   File: HttpSessionContext.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    HttpServletRequest request = servletRequest();
    if (request == null) {
        throw new ContextNotActiveException();
    }
    InjectableBean<T> bean = (InjectableBean<T>) contextual;
    ComputingCache<Key, ContextInstanceHandle<?>> contextualInstances = getContextualInstances(request);
    if (creationalContext != null) {
        return (T) contextualInstances.getValue(new Key(creationalContext, bean.getIdentifier())).get();
    } else {
        InstanceHandle<T> handle = (InstanceHandle<T>) contextualInstances
                .getValueIfPresent(new Key(null, bean.getIdentifier()));
        return handle != null ? handle.get() : null;
    }
}
 
Example #11
Source Project: quarkus   Author: quarkusio   File: TransactionContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ContextState getState() {
    if (!isActive()) {
        throw new ContextNotActiveException("No active transaction on the current thread");
    }

    ContextState result;
    TransactionContextState contextState = (TransactionContextState) transactionSynchronizationRegistry
            .getResource(TRANSACTION_CONTEXT_MARKER);
    if (contextState == null) {
        result = new TransactionContextState();
    } else {
        result = contextState;
    }
    return result;
}
 
Example #12
Source Project: weld-junit   Author: weld   File: ContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }
    return instance != null ? instance.get() : null;
}
 
Example #13
Source Project: thorntail   Author: thorntail   File: DeploymentContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }

    return instance != null ? instance.get() : null;
}
 
Example #14
Source Project: portals-pluto   Author: apache   File: PortletSessionScopedContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> crco) {
   PortletSessionBeanHolder holder = PortletSessionBeanHolder.getBeanHolder();
   
   if (holder == null) {
      throw new ContextNotActiveException("The portlet session context is not active.");
   }
   
   T inst = holder.getBean(bean);
   if (inst == null) {
      inst = bean.create(crco);
      holder.putBeanInstance(bean, crco, inst);
   }
   
   return inst;
}
 
Example #15
Source Project: portals-pluto   Author: apache   File: RedirectScopedContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> crco) {
   RedirectScopedBeanHolder holder = RedirectScopedBeanHolder.getBeanHolder();
   
   if (holder == null) {
      throw new ContextNotActiveException("The redirect context is not active.");
   }
   
   T inst = holder.getBean(bean);
   if (inst == null) {
      inst = bean.create(crco);
      holder.putBeanInstance(bean, crco, inst);
   }

   return inst;
}
 
Example #16
Source Project: trimou   Author: trimou   File: RenderingContext.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {

    checkArgumentNotNull(contextual);
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        throw new ContextNotActiveException();
    }

    @SuppressWarnings("unchecked")
    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }

    return instance != null ? instance.get() : null;
}
 
Example #17
Source Project: joynr   Author: bmwcarit   File: JoynrJeeMessageContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(timeout = 10000)
public void testContextRegistered() {
    JoynrJeeMessageContext.getInstance().activate();

    Context result = beanManager.getContext(JoynrJeeMessageScoped.class);

    assertNotNull(result);
    assertTrue(result instanceof JoynrJeeMessageContext);

    JoynrJeeMessageContext.getInstance().deactivate();
    try {
        result = beanManager.getContext(JoynrJeeMessageScoped.class);
        fail("Shouldn't get it after deactivation.");
    } catch (ContextNotActiveException e) {
        logger.trace("Context not available after deactivation as expected.");
    }
}
 
Example #18
Source Project: deltaspike   Author: apache   File: TransactionContext.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T get(Contextual<T> component)
{
    Map<Contextual, TransactionBeanEntry> transactionBeanEntryMap =
            TransactionBeanStorage.getInstance().getActiveTransactionContext();

    if (transactionBeanEntryMap == null)
    {
        TransactionBeanStorage.close();

        throw new ContextNotActiveException("Not accessed within a transactional method - use @" +
                Transactional.class.getName());
    }

    TransactionBeanEntry transactionBeanEntry = transactionBeanEntryMap.get(component);
    if (transactionBeanEntry != null)
    {
        return (T) transactionBeanEntry.getContextualInstance();
    }

    return null;
}
 
Example #19
Source Project: deltaspike   Author: apache   File: TransactionContext.java    License: Apache License 2.0 6 votes vote down vote up
public <T> T get(Contextual<T> component, CreationalContext<T> creationalContext)
{
    Map<Contextual, TransactionBeanEntry> transactionBeanEntryMap =
        TransactionBeanStorage.getInstance().getActiveTransactionContext();

    if (transactionBeanEntryMap == null)
    {
        TransactionBeanStorage.close();

        throw new ContextNotActiveException("Not accessed within a transactional method - use @" +
                Transactional.class.getName());
    }

    TransactionBeanEntry transactionBeanEntry = transactionBeanEntryMap.get(component);
    if (transactionBeanEntry != null)
    {
        return (T) transactionBeanEntry.getContextualInstance();
    }

    // if it doesn't yet exist, we need to create it now!
    T instance = component.create(creationalContext);
    transactionBeanEntry = new TransactionBeanEntry(component, instance, creationalContext);
    transactionBeanEntryMap.put(component, transactionBeanEntry);

    return instance;
}
 
Example #20
@Test
public void entityManagerUsageWithoutTransaction()
{
    try
    {
        //not available because there is no transactional method
        entityManager.getTransaction();
        Assert.fail(ContextNotActiveException.class.getName() + " expected!");
    }
    catch (ContextNotActiveException e)
    {
        //expected
    }

    Assert.assertEquals(false, TransactionBeanStorage.isOpen());
}
 
Example #21
@Test
public void invalidEntityManagerUsageAfterTransaction()
{
    transactionalBean.executeInTransaction();

    try
    {
        //not available because there is no transactional method
        entityManager.getTransaction();
        Assert.fail(ContextNotActiveException.class.getName() + " expected!");
    }
    catch (ContextNotActiveException e)
    {
        //expected
    }

    Assert.assertEquals(false, TransactionBeanStorage.isOpen());
}
 
Example #22
Source Project: deltaspike   Author: apache   File: ContextUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the context for the given scope annotation is active.
 *
 * @param scopeAnnotationClass The scope annotation (e.g. @RequestScoped.class)
 * @param beanManager The {@link BeanManager}
 * @return If the context is active.
 */
public static boolean isContextActive(Class<? extends Annotation> scopeAnnotationClass, BeanManager beanManager)
{
    try
    {
        if (beanManager.getContext(scopeAnnotationClass) == null
                || !beanManager.getContext(scopeAnnotationClass).isActive())
        {
            return false;
        }
    }
    catch (ContextNotActiveException e)
    {
        return false;
    }

    return true;
}
 
Example #23
Source Project: deltaspike   Author: apache   File: InvocationMonitorInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@AroundInvoke
public Object track(InvocationContext ic) throws Exception
{
    long start = System.nanoTime();
    Object retVal = ic.proceed();
    long end = System.nanoTime();
    try
    {
        requestInvocationCounter.count(ic.getTarget().getClass().getName(), ic.getMethod().getName(), end - start);
    }
    catch (ContextNotActiveException cnae)
    {
        logger.log(Level.FINE, "could not monitor invocatino to {} due to RequestContext not being active",
            ic.getMethod().toString());
    }

    return retVal;
}
 
Example #24
Source Project: deltaspike   Author: apache   File: ImplicitlyGroupedConversationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = ContextNotActiveException.class)
public void noWindowTest()
{
    try
    {
        windowContext.activateWindow("w1");

        implicitlyGroupedBean.setValue("x");
        Assert.assertEquals("x", implicitlyGroupedBean.getValue());

        this.windowContext.closeWindow("w1");
    }
    catch (ContextNotActiveException e)
    {
        Assert.fail();
    }

    implicitlyGroupedBean.getValue();
}
 
Example #25
Source Project: deltaspike   Author: apache   File: ExplicitlyGroupedConversationsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(expected = ContextNotActiveException.class)
public void noWindowTest()
{
    try
    {
        windowContext.activateWindow("w1");

        explicitlyGroupedBeanX.setValue("x1");
        explicitlyGroupedBeanY.setValue("x2");
        Assert.assertEquals("x1", explicitlyGroupedBeanX.getValue());
        Assert.assertEquals("x2", explicitlyGroupedBeanY.getValue());

        this.windowContext.closeWindow("w1");
    }
    catch (ContextNotActiveException e)
    {
        Assert.fail();
    }

    explicitlyGroupedBeanX.getValue();
}
 
Example #26
Source Project: quarkus   Author: quarkusio   File: TransactionBeanWithEvents.java    License: Apache License 2.0 5 votes vote down vote up
void transactionScopeDestroyed(@Observes @Destroyed(TransactionScoped.class) final Object event,
        final BeanManager beanManager) throws SystemException {
    Transaction tx = tm.getTransaction();
    if (tx != null)
        throw new IllegalStateException("@Destroyed expects no transaction");
    try {
        Context ctx = beanManager.getContext(TransactionScoped.class);
        throw new IllegalStateException("No bean in context expected but it's " + ctx);
    } catch (final ContextNotActiveException expected) {
    }

    destroyedCount++;
}
 
Example #27
Source Project: quarkus   Author: quarkusio   File: InjectableRequestContextController.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deactivate() throws ContextNotActiveException {
    if (Arc.container().getActiveContext(RequestScoped.class) == null) {
        throw new ContextNotActiveException(RequestScoped.class.getName());
    }
    if (isActivator.compareAndSet(true, false)) {
        requestContext.terminate();
    }
}
 
Example #28
Source Project: quarkus   Author: quarkusio   File: BeanManagerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Context getContext(Class<? extends Annotation> scopeType) {
    Context context = Arc.container().getActiveContext(scopeType);
    if (context == null) {
        throw new ContextNotActiveException("No active context found for: " + scopeType);
    }
    return context;
}
 
Example #29
Source Project: quarkus   Author: quarkusio   File: InstanceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Object instance) {
    Objects.requireNonNull(instance);
    if (instance instanceof ClientProxy) {
        ClientProxy proxy = (ClientProxy) instance;
        InjectableContext context = Arc.container().getActiveContext(proxy.arc_bean().getScope());
        if (context == null) {
            throw new ContextNotActiveException("No active context found for: " + proxy.arc_bean().getScope());
        }
        context.destroy(proxy.arc_bean());
    } else {
        // Try to destroy a dependent instance
        creationalContext.destroyDependentInstance(instance);
    }
}
 
Example #30
Source Project: quarkus   Author: quarkusio   File: RequestContext.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void destroy(Contextual<?> contextual) {
    Map<Contextual<?>, ContextInstanceHandle<?>> ctx = currentContext.get();
    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }
    ContextInstanceHandle<?> instance = ctx.remove(contextual);
    if (instance != null) {
        instance.destroy();
    }
}