javax.enterprise.context.SessionScoped Java Examples

The following examples show how to use javax.enterprise.context.SessionScoped. 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: WeldContextControl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void stopContext(Class<? extends Annotation> scopeClass)
{
    if (scopeClass.isAssignableFrom(ApplicationScoped.class))
    {
        stopApplicationScope();
    }
    else if (scopeClass.isAssignableFrom(SessionScoped.class))
    {
        stopSessionScope();
    }
    else if (scopeClass.isAssignableFrom(RequestScoped.class))
    {
        stopRequestScope();
    }
    else if (scopeClass.isAssignableFrom(ConversationScoped.class))
    {
        stopConversationScope();
    }
}
 
Example #2
Source File: UndertowBuildStep.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@BuildStep
void integrateCdi(BuildProducer<AdditionalBeanBuildItem> additionalBeans,
        BuildProducer<ContextRegistrarBuildItem> contextRegistrars,
        BuildProducer<ListenerBuildItem> listeners,
        Capabilities capabilities) {
    additionalBeans.produce(new AdditionalBeanBuildItem(ServletProducer.class));
    if (capabilities.isPresent(Capability.SECURITY)) {
        additionalBeans.produce(AdditionalBeanBuildItem.unremovableOf(ServletHttpSecurityPolicy.class));
    }
    contextRegistrars.produce(new ContextRegistrarBuildItem(new ContextRegistrar() {
        @Override
        public void register(RegistrationContext registrationContext) {
            registrationContext.configure(SessionScoped.class).normal().contextClass(HttpSessionContext.class).done();
        }
    }, SessionScoped.class));
    listeners.produce(new ListenerBuildItem(HttpSessionContext.class.getName()));
}
 
Example #3
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 #4
Source File: CdiCucumberTestRunner.java    From database-rider with Apache License 2.0 6 votes vote down vote up
void applyBeforeFeatureConfig(Class testClass) {
    CdiContainer container = CdiContainerLoader.getCdiContainer();

    if (!isContainerStarted()) {
        container.boot(CdiTestSuiteRunner.getTestContainerConfig());
        containerStarted = true;
        bootExternalContainers(testClass);
    }

    List<Class<? extends Annotation>> restrictedScopes = new ArrayList<Class<? extends Annotation>>();

    //controlled by the container and not supported by weld:
    restrictedScopes.add(ApplicationScoped.class);
    restrictedScopes.add(Singleton.class);

    if (this.parent == null && this.testControl.getClass().equals(TestControlLiteral.class)) {
        //skip scope-handling if @TestControl isn't used explicitly on the test-class -> TODO re-visit it
        restrictedScopes.add(RequestScoped.class);
        restrictedScopes.add(SessionScoped.class);
    }

    this.previousProjectStage = ProjectStageProducer.getInstance().getProjectStage();
    ProjectStageProducer.setProjectStage(this.projectStage);

    startScopes(container, testClass, null, restrictedScopes.toArray(new Class[restrictedScopes.size()]));
}
 
Example #5
Source File: DestroyableBase.java    From actframework with Apache License 2.0 6 votes vote down vote up
public Class<? extends Annotation> scope() {
    if (null == scope) {
        synchronized (this) {
            if (null == scope) {
                Class<?> c = getClass();
                if (c.isAnnotationPresent(RequestScoped.class)) {
                    scope = RequestScoped.class;
                } else if (c.isAnnotationPresent(SessionScoped.class)) {
                    scope = SessionScoped.class;
                } else if (c.isAnnotationPresent(ApplicationScoped.class)) {
                    scope = ApplicationScoped.class;
                } else {
                    scope = NormalScope.class;
                }
            }
        }
    }
    return scope;
}
 
Example #6
Source File: HAOpenWebBeansTestLifeCycle.java    From HotswapAgent with GNU General Public License v2.0 6 votes vote down vote up
public void beforeStopApplication(Object endObject)
{
    WebBeansContext webBeansContext = getWebBeansContext();
    ContextsService contextsService = webBeansContext.getContextsService();
    contextsService.endContext(Singleton.class, null);
    contextsService.endContext(ApplicationScoped.class, null);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.endContext(SessionScoped.class, mockHttpSession);

    ELContextStore elStore = ELContextStore.getInstance(false);
    if (elStore == null)
    {
        return;
    }
    elStore.destroyELContextStore();
}
 
Example #7
Source File: BeginWebBeansListener.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void sessionCreated(final HttpSessionEvent event) {
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Starting a session with session id : [{0}]", event.getSession().getId());
        }
        if (webBeansContext instanceof WebappWebBeansContext) { // start before child
            ((WebappWebBeansContext) webBeansContext).getParent().getContextsService().startContext(SessionScoped.class, event.getSession());
        }
        contextsService.startContext(SessionScoped.class, event.getSession());
    } catch (final Exception e) {
        logger.error(OWBLogConst.ERROR_0020, event.getSession());
        WebBeansUtil.throwRuntimeExceptions(e);
    }
}
 
Example #8
Source File: EnsureRequestScopeThreadLocalIsCleanUpTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void ensureRequestContextCanBeRestarted() throws Exception {
    final ApplicationComposers composers = new ApplicationComposers(EnsureRequestScopeThreadLocalIsCleanUpTest.class);
    composers.before(this);
    final CdiAppContextsService contextsService = CdiAppContextsService.class.cast(WebBeansContext.currentInstance().getService(ContextsService.class));
    final Context req1 = contextsService.getCurrentContext(RequestScoped.class);
    assertNotNull(req1);
    final Context session1 = contextsService.getCurrentContext(SessionScoped.class);
    assertNotNull(session1);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.startContext(RequestScoped.class, null);
    final Context req2 = contextsService.getCurrentContext(RequestScoped.class);
    assertNotSame(req1, req2);
    final Context session2 = contextsService.getCurrentContext(SessionScoped.class);
    assertSame(session1, session2);
    composers.after();
    assertNull(contextsService.getCurrentContext(RequestScoped.class));
    assertNull(contextsService.getCurrentContext(SessionScoped.class));
}
 
Example #9
Source File: CdiTestRunner.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private void addScopesForDefaultBehavior(List<Class<? extends Annotation>> scopeClasses)
{
    if (this.parent != null && !this.parent.isScopeStarted(RequestScoped.class))
    {
        if (!scopeClasses.contains(RequestScoped.class))
        {
            scopeClasses.add(RequestScoped.class);
        }
    }
    if (this.parent != null && !this.parent.isScopeStarted(SessionScoped.class))
    {
        if (!scopeClasses.contains(SessionScoped.class))
        {
            scopeClasses.add(SessionScoped.class);
        }
    }
}
 
Example #10
Source File: ContextControlDecorator.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void stopContexts()
{
    if (isManualScopeHandling())
    {
        for (ExternalContainer externalContainer : CdiTestRunner.getActiveExternalContainers())
        {
            externalContainer.stopScope(ConversationScoped.class);
            externalContainer.stopScope(SessionScoped.class);
            externalContainer.stopScope(RequestScoped.class);
            externalContainer.stopScope(ApplicationScoped.class);
            externalContainer.stopScope(Singleton.class);
        }
    }

    wrapped.stopContexts();
}
 
Example #11
Source File: MockedJsf2TestContainer.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void startScope(Class<? extends Annotation> scopeClass)
{
    if (RequestScoped.class.equals(scopeClass))
    {
        initRequest();
        initResponse();

        initFacesContext();

        initDefaultView();
    }
    else if (SessionScoped.class.equals(scopeClass))
    {
        initSession();
    }
}
 
Example #12
Source File: MockedJsf2TestContainer.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void stopScope(Class<? extends Annotation> scopeClass)
{
    if (RequestScoped.class.equals(scopeClass))
    {
        if (this.facesContext != null)
        {
            this.facesContext.release();
        }
        this.facesContext = null;
        this.request = null;
        this.response = null;
    }
    else if (SessionScoped.class.equals(scopeClass))
    {
        this.session = null;
    }
}
 
Example #13
Source File: OpenWebBeansContextControl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void startContext(Class<? extends Annotation> scopeClass)
{
    if (scopeClass.isAssignableFrom(ApplicationScoped.class))
    {
        startApplicationScope();
    }
    else if (scopeClass.isAssignableFrom(SessionScoped.class))
    {
        startSessionScope();
    }
    else if (scopeClass.isAssignableFrom(RequestScoped.class))
    {
        startRequestScope();
    }
    else if (scopeClass.isAssignableFrom(ConversationScoped.class))
    {
        startConversationScope();
    }
}
 
Example #14
Source File: OpenWebBeansContextControl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public void stopContext(Class<? extends Annotation> scopeClass)
{
    if (scopeClass.isAssignableFrom(ApplicationScoped.class))
    {
        stopApplicationScope();
    }
    else if (scopeClass.isAssignableFrom(SessionScoped.class))
    {
        stopSessionScope();
    }
    else if (scopeClass.isAssignableFrom(RequestScoped.class))
    {
        stopRequestScope();
    }
    else if (scopeClass.isAssignableFrom(ConversationScoped.class))
    {
        stopConversationScope();
    }
}
 
Example #15
Source File: OpenWebBeansContextControl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private void startSessionScope()
{
    ContextsService contextsService = getContextsService();

    Object mockSession = null;
    if (isServletApiAvailable())
    {
        mockSession = mockSessions.get();
        if (mockSession == null)
        {
            // we simply use the ThreadName as 'sessionId'
            mockSession = OwbHelper.getMockSession(Thread.currentThread().getName());
            mockSessions.set(mockSession);
        }
    }
    contextsService.startContext(SessionScoped.class, mockSession);
}
 
Example #16
Source File: ContextControlDecorator.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void startContexts()
{
    wrapped.startContexts();

    if (isManualScopeHandling())
    {
        for (ExternalContainer externalContainer : CdiTestRunner.getActiveExternalContainers())
        {
            externalContainer.startScope(Singleton.class);
            externalContainer.startScope(ApplicationScoped.class);
            externalContainer.startScope(RequestScoped.class);
            externalContainer.startScope(SessionScoped.class);
            externalContainer.startScope(ConversationScoped.class);
        }
    }
}
 
Example #17
Source File: WeldContextControl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void startContext(Class<? extends Annotation> scopeClass)
{
    if (scopeClass.isAssignableFrom(ApplicationScoped.class))
    {
        startApplicationScope();
    }
    else if (scopeClass.isAssignableFrom(SessionScoped.class))
    {
        startSessionScope();
    }
    else if (scopeClass.isAssignableFrom(RequestScoped.class))
    {
        startRequestScope();
    }
    else if (scopeClass.isAssignableFrom(ConversationScoped.class))
    {
        startConversationScope(null);
    }
}
 
Example #18
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 #19
Source File: EnsureRequestScopeThreadLocalIsCleanUpTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
public void runAndCheckThreadLocal() throws Exception {
    final ApplicationComposers composers = new ApplicationComposers(EnsureRequestScopeThreadLocalIsCleanUpTest.class);
    composers.before(this);
    final CdiAppContextsService contextsService = CdiAppContextsService.class.cast(WebBeansContext.currentInstance().getService(ContextsService.class));
    assertNotNull(contextsService.getCurrentContext(RequestScoped.class));
    assertNotNull(contextsService.getCurrentContext(SessionScoped.class));
    composers.after();
    assertNull(contextsService.getCurrentContext(RequestScoped.class));
    assertNull(contextsService.getCurrentContext(SessionScoped.class));
}
 
Example #20
Source File: MockedJsfTestContainerAdapter.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public void startScope(Class<? extends Annotation> scopeClass)
{
    if (RequestScoped.class.equals(scopeClass))
    {
        this.mockedMyFacesTestContainer.startRequest();
    }
    else if (SessionScoped.class.equals(scopeClass))
    {
        this.mockedMyFacesTestContainer.startSession();
    }
}
 
Example #21
Source File: MockedJsfTestContainerAdapter.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Override
public void stopScope(Class<? extends Annotation> scopeClass)
{
    if (RequestScoped.class.equals(scopeClass))
    {
        this.mockedMyFacesTestContainer.endRequest();
    }
    else if (SessionScoped.class.equals(scopeClass))
    {
        this.mockedMyFacesTestContainer.endSession();
    }
}
 
Example #22
Source File: OpenWebBeansContextControl.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private void stopSessionScope()
{
    ContextsService contextsService = getContextsService();

    Object mockSession = null;
    if (isServletApiAvailable())
    {
        mockSession = mockSessions.get();
        mockSessions.set(null);
        mockSessions.remove();
    }
    contextsService.endContext(SessionScoped.class, mockSession);
}
 
Example #23
Source File: AddPassivatingBeanTest.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("serial")
static Bean<?> createListBean() {
    return MockBean.builder()
        .types(new TypeLiteral<List<String>>() {
        }.getType())
        .scope(SessionScoped.class)
        .creating(
            // Mock object provided by Mockito
            when(mock(List.class).get(0)).thenReturn("42").getMock())
        .build();
}
 
Example #24
Source File: ScopeHelper.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static void stopContexts(final ContextsService contextsService, final ServletContext servletContext, final HttpSession session) throws Exception {
    contextsService.endContext(SessionScoped.class, session);
    contextsService.endContext(RequestScoped.class, null);
    contextsService.endContext(ConversationScoped.class, null);
    if (CdiAppContextsService.class.isInstance(contextsService)) {
        CdiAppContextsService.class.cast(contextsService).removeThreadLocals();
    }
}
 
Example #25
Source File: HasSessionScopeTest.java    From microprofile-rest-client with Apache License 2.0 5 votes vote down vote up
@Deployment
public static WebArchive createDeployment() {
    String url = SimpleGetApi.class.getName()+"/mp-rest/url=http://localhost:8080";
    String scope = SimpleGetApi.class.getName()+"/mp-rest/scope="+ SessionScoped.class.getName();
    String configKeyScope = "myConfigKey/mp-rest/scope=" + SessionScoped.class.getName();
    String simpleName = HasSessionScopeTest.class.getSimpleName();
    JavaArchive jar = ShrinkWrap.create(JavaArchive.class, simpleName + ".jar")
        .addClasses(SimpleGetApi.class, MySessionScopedApi.class, ConfigKeyClient.class)
        .addAsManifestResource(new StringAsset(url + "\n" + scope + "\n" + configKeyScope),
                                               "microprofile-config.properties")
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
    return ShrinkWrap.create(WebArchive.class, simpleName + ".war")
        .addAsLibrary(jar)
        .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
 
Example #26
Source File: EmbeddedTomEEContainer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void startCdiContexts(final String name) {
    final WebBeansContext wbc = this.container.getAppContexts(name).getWebBeansContext();
    if (wbc != null && wbc.getBeanManagerImpl().isInUse()) {
        final MockHttpSession session = new MockHttpSession();
        wbc.getContextsService().startContext(RequestScoped.class, null);
        wbc.getContextsService().startContext(SessionScoped.class, session);
        wbc.getContextsService().startContext(ConversationScoped.class, null);

        SESSIONS.put(name, session);
    }
}
 
Example #27
Source File: BeginWebBeansListener.java    From tomee with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void sessionDestroyed(final HttpSessionEvent event) {
    if (webBeansContext == null) {
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Destroying a session with session id : [{0}]", event.getSession().getId());
    }

    contextsService.endContext(SessionScoped.class, event.getSession());

    WebBeansListenerHelper.destroyFakedRequest(this);
}
 
Example #28
Source File: HAAbstractUnitTest.java    From HotswapAgent with GNU General Public License v2.0 5 votes vote down vote up
protected void startContainer()
{
    CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();
    ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext(ApplicationScoped.class);
    contextControl.startContext(SessionScoped.class);
    contextControl.startContext(RequestScoped.class);
}
 
Example #29
Source File: EmbeddedTomEEContainer.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void stopCdiContexts(final String name) {
    try {
        final HttpSession session = SESSIONS.remove(name);
        if (session != null) {
            final WebBeansContext wbc = container.getAppContexts(container.getInfo(name).appId).getWebBeansContext();
            if (wbc != null && wbc.getBeanManagerImpl().isInUse()) {
                wbc.getContextsService().startContext(RequestScoped.class, null);
                wbc.getContextsService().startContext(SessionScoped.class, session);
                wbc.getContextsService().startContext(ConversationScoped.class, null);
            }
        }
    } catch (final Exception e) {
        // no-op
    }
}
 
Example #30
Source File: PortletSessionAppScopeTest.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
@Test
public void checkNoSessionScoped() throws Exception {
   Set<Annotation> annos = appScoped.getAnnotations();
   assertNotEquals(0, annos.size());
   boolean ok = true;
   for (Annotation a : annos) {
      if (a.annotationType().equals(SessionScoped.class)) {
         ok = false;
         break;
      }
   }
   assertTrue(ok);
}