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 File: CDIContextTest.java    From microprofile-context-propagation with 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 File: DeploymentContextImpl.java    From thorntail with 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 #3
Source File: ContextImpl.java    From weld-junit with 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 #4
Source File: JoynrJeeMessageContextTest.java    From joynr with 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 #5
Source File: TransactionContext.java    From deltaspike with 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 #6
Source File: TransactionContext.java    From deltaspike with 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 #7
Source File: RenderingContext.java    From trimou with 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 #8
Source File: TransactionContext.java    From quarkus with 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 #9
Source File: DefaultTransactionScopedEntityManagerInjectionTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: DefaultTransactionScopedEntityManagerInjectionTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: HttpSessionContext.java    From quarkus with 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 #12
Source File: RedirectScopedContext.java    From portals-pluto with 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 #13
Source File: ContextUtils.java    From deltaspike with 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 #14
Source File: RequestContext.java    From quarkus with 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 #15
Source File: PortletSessionScopedContext.java    From portals-pluto with 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 #16
Source File: InvocationMonitorInterceptor.java    From deltaspike with 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 #17
Source File: InstanceHandleImpl.java    From quarkus with 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 #18
Source File: ImplicitlyGroupedConversationsTest.java    From deltaspike with 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 #19
Source File: TransactionScopedTest.java    From quarkus with 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 #20
Source File: ExplicitlyGroupedConversationsTest.java    From deltaspike with 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 #21
Source File: CDIContextTest.java    From microprofile-context-propagation with 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 #22
Source File: CDIContextTest.java    From microprofile-context-propagation with 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 #23
Source File: CDIContextTest.java    From microprofile-context-propagation with 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 #24
Source File: CDIContextTest.java    From microprofile-context-propagation with 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 #25
Source File: CDIContextTest.java    From microprofile-context-propagation with 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 #26
Source File: RedirectScopedContext.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean) {
   RedirectScopedBeanHolder holder = RedirectScopedBeanHolder.getBeanHolder();
   if (holder == null) {
      throw new ContextNotActiveException("The redirect context is not active.");
   }
   return holder.getBean(bean);
}
 
Example #27
Source File: BeanClassRefreshAgent.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
private static void doReinjectBean(BeanManagerImpl beanManager, InjectionTargetBean<?> bean) {
    try {
        if (!bean.getScope().equals(ApplicationScoped.class) &&
                (HaCdiCommons.isRegisteredScope(bean.getScope()) || HaCdiCommons.isInExtraScope(bean))) {
            doReinjectRegisteredBeanInstances(beanManager, bean);
        } else {
            doReinjectBeanInstance(beanManager, bean, beanManager.getContext(bean.getScope()));
        }
    } catch (ContextNotActiveException e) {
        LOGGER.info("No active contexts for bean '{}'", bean.getBeanClass().getName());
    }
}
 
Example #28
Source File: DefaultContextAssociationManager.java    From camunda-bpm-platform with Apache License 2.0 5 votes vote down vote up
protected Class< ? extends ScopedAssociation> getBroadestActiveContext() {
  for (Class< ? extends ScopedAssociation> scopeType : getAvailableScopedAssociationClasses()) {
    Annotation scopeAnnotation = scopeType.getAnnotations().length > 0 ? scopeType.getAnnotations()[0] : null;
    if (scopeAnnotation == null || !beanManager.isScope(scopeAnnotation.annotationType())) {
      throw new ProcessEngineException("ScopedAssociation must carry exactly one annotation and it must be a @Scope annotation");
    }
    try {
      beanManager.getContext(scopeAnnotation.annotationType());
      return scopeType;
    } catch (ContextNotActiveException e) {
      log.finest("Context " + scopeAnnotation.annotationType() + " not active.");
    }
  }
  throw new ProcessEngineException("Could not determine an active context to associate the current process instance / task instance with.");
}
 
Example #29
Source File: PortletSessionScopedContext.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T get(Contextual<T> bean) {
   PortletSessionBeanHolder holder = PortletSessionBeanHolder.getBeanHolder();
   if (holder == null) {
      throw new ContextNotActiveException("The portlet session context is not active.");
   }
   return holder.getBean(bean);
}
 
Example #30
Source File: AbstractContext.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Make sure that the Context is really active.
 * @throws ContextNotActiveException if there is no active
 *         Context for the current Thread.
 */
protected void checkActive()
{
    if (!isActive())
    {
        throw new ContextNotActiveException("CDI context with scope annotation @"
            + getScope().getName() + " is not active with respect to the current thread");
    }
}