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()])); }
void processClaimValueInjections(@Observes ProcessInjectionPoint pip) { log.debugf("pipRaw: %s", pip.getInjectionPoint()); InjectionPoint ip = pip.getInjectionPoint(); if (ip.getAnnotated().isAnnotationPresent(Claim.class) && ip.getType() instanceof Class) { Class rawClass = (Class) ip.getType(); if (Modifier.isFinal(rawClass.getModifiers())) { Claim claim = ip.getAnnotated().getAnnotation(Claim.class); rawTypes.add(ip.getType()); rawTypeQualifiers.add(claim); log.debugf("+++ Added Claim raw type: %s", ip.getType()); Class declaringClass = ip.getMember().getDeclaringClass(); Annotation[] appScoped = declaringClass.getAnnotationsByType(ApplicationScoped.class); Annotation[] sessionScoped = declaringClass.getAnnotationsByType(SessionScoped.class); if ((appScoped != null && appScoped.length > 0) || (sessionScoped != null && sessionScoped.length > 0)) { String err = String.format("A raw type cannot be injected into application/session scope: IP=%s", ip); pip.addDefinitionError(new DeploymentException(err)); } } } }
/** * Does actually not work */ @Override @Asynchronous public void startAsynchronous(final IWorkflowListener listener) { try { CdiContextAwareRunnable runnable = new CdiContextAwareRunnable(this.newWorkflowRunnable(listener)); // runnable.addContext(RequestScoped.class); runnable.addContext(SessionScoped.class); // runnable.addContext(ApplicationScoped.class); runnable.addContext(ConversationScoped.class); runnable.run(); } catch (WorkflowException e) { LOG.error(e.getMessage(), e); } }
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; }
/** * Checks if a custom resolver method injected parameter scope is {@link Dependent} * * @param type * The parameter type being checked * @return Returns true if the paraeter scope is {@link Dependent} */ private boolean checkDependentScope(Class<?> type) { for (Annotation annotation : type.getAnnotations()) { if (annotation.annotationType().equals(SessionScoped.class) || annotation.annotationType().equals(RequestScoped.class) || annotation.annotationType().equals(ApplicationScoped.class)) { return false; } Class<?> viewScopedClass = null; try { // Account for JEE 7 @ViewScoped scope viewScopedClass = Class.forName("javax.faces.view.ViewScoped"); } catch (Exception e) { // JEE 6 environment if (logger.isDebugEnabled()) { logger.debug("Class javax.faces.view.ViewScoped was not found: Running in a Java EE 6 environment."); } } if (viewScopedClass != null) { if (annotation.annotationType().equals(viewScopedClass)) { return false; } } } return true; }
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(); }
private static void doReinjectSessionBasedBean(BeanManagerImpl beanManager, Class<?> beanClass, AbstractClassBean<?> bean) { Map<Class<? extends Annotation>, List<Context>> contexts = getContexts(beanManager); List<Context> contextList = contexts.get(SessionScoped.class); if (contextList != null && !contextList.isEmpty()) { for (Context ctx: contextList) { Context sessionCtx = PassivatingContextWrapper.unwrap(ctx); if (sessionCtx instanceof HttpSessionContextImpl) { doReinjectHttpSessionBasedBean(beanManager, beanClass, bean, (HttpSessionContextImpl) sessionCtx); } else if (sessionCtx instanceof BoundSessionContextImpl) { doReinjectBoundSessionBasedBean(beanManager, beanClass, bean, (BoundSessionContextImpl) sessionCtx); } else if (sessionCtx instanceof HttpSessionDestructionContext) { // HttpSessionDestructionContext is temporary used for HttpSession context destruction, we don't handle it } else { LOGGER.warning("Unexpected session context class '{}'.", sessionCtx.getClass().getName()); } } } else { LOGGER.warning("No session context found in BeanManager."); } }
/** * {@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); } }
@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)); }
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); } } }
@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); } } }
@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(); }
@Override public void startScope(Class<? extends Annotation> scopeClass) { if (RequestScoped.class.equals(scopeClass)) { initRequest(); initResponse(); initFacesContext(); initDefaultView(); } else if (SessionScoped.class.equals(scopeClass)) { initSession(); } }
@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; } }
@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(); } }
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(); } }
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); }
@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); } }
@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(); } }
/** * Tests the specializes a jar archive */ @Test public void testSpecializes() { logger.info("starting specializes test"); assertTrue("the revisionService with Specializes", revisionService instanceof RevisionService); Bean<?> bean = beanManager.getBeans(Service.class, new AnnotationLiteral<Revision>() { private static final long serialVersionUID = -4491584612013368113L; }).iterator().next(); assertEquals("RevisionService should inherit the SessionScope without the Specializes annotation", SessionScoped.class, bean.getScope()); }
@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(); }
@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(); }
@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(); JavaArchive jar = ShrinkWrap.create(JavaArchive.class) .addClasses(SimpleGetApi.class, MySessionScopedApi.class) .addAsManifestResource(new StringAsset(url+"\n"+scope), "microprofile-config.properties") .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); return ShrinkWrap.create(WebArchive.class) .addAsLibrary(jar) .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"); }
@Bean @ConditionalOnProperty(value = "jsf.scope-configurer.cdi.enabled", havingValue = "true", matchIfMissing = true) public static BeanFactoryPostProcessor cdiScopeAnnotationsConfigurer(Environment environment) { CustomScopeAnnotationConfigurer scopeAnnotationConfigurer = new CustomScopeAnnotationConfigurer(); scopeAnnotationConfigurer.setOrder(environment.getProperty("jsf.scope-configurer.cdi.order", Integer.class, Ordered.LOWEST_PRECEDENCE)); scopeAnnotationConfigurer.addMapping(RequestScoped.class, WebApplicationContext.SCOPE_REQUEST); scopeAnnotationConfigurer.addMapping(SessionScoped.class, WebApplicationContext.SCOPE_SESSION); scopeAnnotationConfigurer.addMapping(ConversationScoped.class, WebApplicationContext.SCOPE_SESSION); scopeAnnotationConfigurer.addMapping(ApplicationScoped.class, WebApplicationContext.SCOPE_APPLICATION); return scopeAnnotationConfigurer; }
/** * Creates the current user * @return User */ @Produces @SessionScoped @AuthenticatedUser @Named("currentUser") public User getCurrentUser() { if(user == null || user.isAnonymous()) { user = userService.getAuthenticatedUser(); } return user; }
protected void submit(Runnable runnable) { CdiContextAwareRunnable contextRunnable = new CdiContextAwareRunnable(runnable); contextRunnable.addContext(RequestScoped.class); contextRunnable.addContext(SessionScoped.class); contextRunnable.addContext(ConversationScoped.class); this.service.submit(contextRunnable); }
@Test public void cannotBeAManagedBeanBecauseOfWas() { assertNull(getAnnotation(ApplicationScoped.class)); assertNull(getAnnotation(Dependent.class)); assertNull(getAnnotation(SessionScoped.class)); assertNull(getAnnotation(RequestScoped.class)); assertNull(getAnnotation(ConversationScoped.class)); }
/** * Handling of the after bean discovery event as fired by the bean manager. The handling creates * contexts for the session and request scopes. * * @param event The event that can be used for the actions */ public void afterBeanDiscovery(@Observes AfterBeanDiscovery event) { // Register the session scope context. event.addContext(registerContext(addContext(new MultiInstanceContext(SessionScoped.class, null)))); // And the request scope context. event.addContext(registerContext(addContext(new MultiInstanceContext(RequestScoped.class, null)))); // And the bundle scope. event.addContext(addContext(new BasicContext(ComponentScoped.class, null))); // And the view scope. event.addContext(registerContext(addContext(new MultiInstanceContext(ViewScoped.class, null)))); }
@Override public void sessionDestroyed(HttpSessionEvent event) { HttpSession session = event.getSession(); ServletContext context = session.getServletContext(); doWithContext(context, SessionScoped.class, (c) -> {c.remove(session.getId()); c.setCurrent(null);}); doWithContext(context, ViewScoped.class, (c) -> { identifiersThisSession(c, session).forEach((i) -> { c.remove(i); }); }); }
@Override public void requestInitialized(ServletRequestEvent event) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); request.setAttribute(SCOPELISTENER, this); ServletContext context = request.getServletContext(); HttpSession session = request.getSession(true); doWithContext(context, RequestScoped.class, (c) -> {c.add(request); c.setCurrent(request);}); doWithContext(context, SessionScoped.class, (c) -> c.setCurrent(session.getId())); setFallbackViewScope(request); }
@Override public void requestDestroyed(ServletRequestEvent event) { HttpServletRequest request = (HttpServletRequest) event.getServletRequest(); ServletContext context = request.getServletContext(); doWithContext(context, SessionScoped.class, (c) -> c.setCurrent(null)); doWithContext(context, ViewScoped.class, (c) -> c.setCurrent(null)); doWithContext(context, RequestScoped.class, (c) -> c.remove(request)); }
private static boolean inScope(Object o, Class<? extends Annotation> scope) { if (null == o) { return false; } if (null == scope || scope == ApplicationScoped.class) { return true; } Class<?> c = o.getClass(); // performance tune - most frequent types in ActionContext if (String.class == c || Method.class == c || Boolean.class == c) { return false; } if (RequestHandlerProxy.class == c || ReflectedHandlerInvoker.class == c) { return ApplicationScoped.class == scope; } if (Integer.class == c || Locale.class == c || Long.class == c || Double.class == c || Enum.class.isAssignableFrom(c)) { return false; } if (c.isAnnotationPresent(scope)) { return true; } if (scope == SessionScoped.class) { // RequestScoped is always inside Session scope return c.isAnnotationPresent(RequestScoped.class); } return false; }
/** * Construct the wrapper. */ public PortletSessionScopedAnnotatedType(AnnotatedType<SessionScoped> type) { aType = type; annos.addAll(type.getAnnotations()); annos.remove(Dummy.class.getAnnotation(SessionScoped.class)); annos.add(Dummy.class.getAnnotation(PortletSessionScoped.class)); }
@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); }
@Override public void postStart() { final ContextControl contextControl = this.container.getContextControl(); contextControl.startContext(ApplicationScoped.class); contextControl.startContext(SessionScoped.class); contextControl.startContext(RequestScoped.class); }
@Override public void preStop() { final ContextControl contextControl = this.container.getContextControl(); contextControl.stopContext(RequestScoped.class); contextControl.stopContext(SessionScoped.class); contextControl.stopContext(ApplicationScoped.class); }
@Test public void simpleReplacementWithComment() { createHolder("test-annotations.properties"); Map<Class<? extends Annotation>, Annotation> replacementMap = holder.getReplacementMap(); assertEquals(1, replacementMap.size()); Map.Entry<Class<? extends Annotation>, Annotation> annotationEntry = replacementMap.entrySet().iterator().next(); assertEquals(SessionScoped.class, annotationEntry.getKey()); assertTrue(annotationEntry.getValue() instanceof ApplicationScoped); }