@Produces @RequestScoped @Named("userPrincipal") public UserPrincipal producePrincipal() { Object principal = SecurityUtils.getSubject().getPrincipal(); UserPrincipal result = null; if (principal instanceof UserPrincipal) { result = (UserPrincipal) principal; } /* FIXME if (principal instanceof SystemAccountPrincipal) { SystemAccountPrincipal systemAccountPrincipal = (SystemAccountPrincipal) principal; String identifier = systemAccountPrincipal.getIdentifier(); result = new UserPrincipal(identifier); } */ if (principal == null) { result = new UserPrincipal(); } return result; }
@Override public ScopeMetadata resolveScopeMetadata(final BeanDefinition definition) { if (definition instanceof AnnotatedBeanDefinition) { final AnnotatedBeanDefinition beanDefinition = (AnnotatedBeanDefinition) definition; final ScopeMetadata metadata = new ScopeMetadata(); final Set<String> annotationTypes = beanDefinition.getMetadata().getAnnotationTypes(); if (annotationTypes.contains(RequestScoped.class .getName())) { metadata.setScopeName("request"); metadata.setScopedProxyMode(ScopedProxyMode.TARGET_CLASS); } else if (annotationTypes .contains(ApplicationScoped.class.getName())) { metadata.setScopeName("singleton"); } else { return super.resolveScopeMetadata(definition); } return metadata; } else { return super.resolveScopeMetadata(definition); } }
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()])); }
@Produces @RequestScoped public BlazeStorage createClient() { URI uri = URI.create(httpServletRequest.getRequestURL().toString()); String contextPath = httpServletRequest.getContextPath(); String basePath = "/api"; if (contextPath != null) { basePath = contextPath + basePath; } try { uri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), basePath, null, null); } catch (URISyntaxException x) { throw new IllegalArgumentException(x.getMessage(), x); } return BlazeStorageClient.getInstance(uri.toString()); }
@Produces @Named("storageQuotaPlanItems") @RequestScoped public List<SelectItem> getStorageQuotaPlanItems() { List<StorageQuotaModelListElementRepresentation> quotaModels = storage.storageQuotaModels().get(); List<SelectItem> quotaModelPlanItems = new ArrayList<>(quotaModels.size()); for (StorageQuotaModelListElementRepresentation quotaModel : quotaModels) { SelectItemGroup group = new SelectItemGroup(quotaModel.getName()); List<SelectItem> groupItems = new ArrayList<>(quotaModel.getLimits().size()); for (Integer limit : quotaModel.getLimits()) { groupItems.add(new SelectItem(new StorageQuotaPlanChoiceRepresentation(quotaModel.getId(), limit), limit + " GB")); } group.setSelectItems(groupItems.toArray(new SelectItem[groupItems.size()])); quotaModelPlanItems.add(group); } return quotaModelPlanItems; }
@Override protected void releaseResources() { for (Listener l : listenerList) { try { l.onDestroy(this); } catch (Exception e) { warn(e, "error calling listener onDestroy method"); } } Destroyable.Util.destroyAll(destroyableList, RequestScoped.class); Destroyable.Util.tryDestroyAll(attributes.values(), RequestScoped.class); this.attributes.clear(); this.renderArgs.clear(); this.template = null; this.app = null; this.template = null; this.listenerList.clear(); this.destroyableList.clear(); this.violations.clear(); // note we can't destroy progress as it might still be used // by background thread //this.progress.destroy(); }
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; }
@AroundInvoke public Object startRequestScope(final InvocationContext ctx) throws Exception { Object result = null; ContextControl contextControl = null; if(!isRequestScopeActive()) { contextControl = CDI.current().select(ContextControl.class).get(); contextControl.startContext(RequestScoped.class); } try { result = ctx.proceed(); } finally { if(contextControl != null) { contextControl.stopContext(RequestScoped.class); } } return result; }
@Test(priority = 3) public void testRequestScopedBeanPerformance() throws InterruptedException { final SimpleRequestScopedBeanWithoutInterceptor underTest = getInstance(cdiContainer.getBeanManager(), SimpleRequestScopedBeanWithoutInterceptor.class); final ContextControl contextControl = cdiContainer.getContextControl(); contextControl.startContext(RequestScoped.class); Assert.assertEquals(underTest.theMeaningOfLife(), 42); contextControl.stopContext(RequestScoped.class); executeInParallel("invocation on @RequestScoped bean", new Runnable() { @Override public void run() { contextControl.startContext(RequestScoped.class); for (int i = 0; i < NUM_ITERATION; i++) { // this line does the actual bean invocation. underTest.theMeaningOfLife(); } contextControl.stopContext(RequestScoped.class); } }); }
/** * Provides an EntityManager for this Model. * * @return new EntityManager */ @Override @RequestScoped public EntityManager provide() { // hk2 final EntityManager instance = getEntityManager(); if (closeableService != null) { closeableService.add(new Closeable() { @Override public void close() throws IOException { dispose(instance); } }); } return instance; }
/** * 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(); }
/** * {@inheritDoc} */ @Override public void requestInitialized(final ServletRequestEvent event) { final Object oldContext = ThreadSingletonServiceImpl.enter(this.webBeansContext); if (event != null) { event.getServletRequest().setAttribute(contextKey, oldContext); } try { if (logger.isDebugEnabled()) { logger.debug("Starting a new request : [{0}]", event == null ? "null" : event.getServletRequest().getRemoteAddr()); } if (webBeansContext instanceof WebappWebBeansContext) { // start before child ((WebappWebBeansContext) webBeansContext).getParent().getContextsService().startContext(RequestScoped.class, event); } contextsService.startContext(RequestScoped.class, event); // we don't initialise the Session here but do it lazily if it gets requested // the first time. See OWB-457 } catch (final Exception e) { logger.error(OWBLogConst.ERROR_0019, event == null ? "null" : event.getServletRequest()); WebBeansUtil.throwRuntimeExceptions(e); } }
@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 contextEntered(final ThreadContext oldContext, final ThreadContext newContext) { final BeanContext beanContext = newContext.getBeanContext(); final WebBeansContext webBeansContext = beanContext.getModuleContext().getAppContext().getWebBeansContext(); if (webBeansContext == null) { return; } final ContextsService contextsService = webBeansContext.getContextsService(); final Context requestContext = CdiAppContextsService.class.cast(contextsService).getRequestContext(false); if (requestContext == null) { contextsService.startContext(RequestScoped.class, CdiAppContextsService.EJB_REQUEST_EVENT); newContext.set(DestroyContext.class, new DestroyContext(contextsService, newContext)); } }
@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)); }
@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(); } }
@Before public final void setUp() throws Exception { System.out.printf("AbstractCdiContainerTest#setUp() containerRefCount=%d, cdiContainer=%s\n", containerRefCount.get(), cdiContainer ); if ( cdiContainer != null ) { containerRefCount.incrementAndGet(); final ContextControl ctxCtrl = BeanProvider.getContextualReference(ContextControl.class); //stop the RequestContext to dispose of the @RequestScoped EntityManager ctxCtrl.stopContext(RequestScoped.class); //immediately restart the context again ctxCtrl.startContext(RequestScoped.class); // perform injection into the very own test class final BeanManager beanManager = cdiContainer.getBeanManager(); final CreationalContext creationalContext = beanManager.createCreationalContext(null); final AnnotatedType annotatedType = beanManager.createAnnotatedType(this.getClass()); final InjectionTarget injectionTarget = beanManager.createInjectionTarget(annotatedType); injectionTarget.inject(this, creationalContext); } }
@After public final void tearDown() throws Exception { System.out.printf("AbstractCdiContainerTest#tearDown() containerRefCount=%d, cdiContainer=%s\n", containerRefCount.get(), cdiContainer ); if (cdiContainer != null) { final ContextControl ctxCtrl = BeanProvider.getContextualReference(ContextControl.class); //stop the RequestContext to dispose of the @RequestScoped EntityManager ctxCtrl.stopContext(RequestScoped.class); //immediately restart the context again ctxCtrl.startContext(RequestScoped.class); // cdiContainer.getContextControl().stopContext(RequestScoped.class); // cdiContainer.getContextControl().startContext(RequestScoped.class); containerRefCount.decrementAndGet(); } }
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 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(); } }
@Produces @RequestScoped public Properties exposeKafkaProperties() throws IOException { final Properties properties = new Properties(); properties.putAll(kafkaProperties); return properties; }
@RequestScoped @Produces @FromJedisPool public Jedis get() { Jedis jedis = pool.getResource(); System.out.println("Got resource from Jedis pool"); return jedis; }
private <T> Provider<T> buildProvider(final Key<T> key, final Set<Key<?>> chain) { final Provider<T> p; switch (key.getStrategy()) { case CONTEXT: p = new ContextProvider<>(key); break; case COOKIE: p = new CookieParamProvider<>(key); break; case FORM: p = new FormParamProvider<>(key); break; case HEADER: p = new HeaderParamProvider<>(key); break; case PATH: p = new PathParamProvider<>(key); break; case QUERY: p = new QueryParamProvider<>(key); break; default: p = new ConstructorProviderBuilder<>(this, key, chain).buildConstructorProvider(); break; } if (key.getType().getAnnotation(Singleton.class) != null) { return new SingletonProvider<>(p); } else if (key.getType().getAnnotation(RequestScoped.class) != null) { return new RequestScopedProvider<>(key, p); } else { return p; } }
@Deployment public static WebArchive createDeployment() { String url = SimpleGetApi.class.getName() + "/mp-rest/url=http://localhost:8080"; String url2 = MyRequestScopedApi.class.getName() + "/mp-rest/url=http://localhost:8080"; String scope = SimpleGetApi.class.getName() + "/mp-rest/scope=" + RequestScoped.class.getName(); JavaArchive jar = ShrinkWrap.create(JavaArchive.class) .addClasses(SimpleGetApi.class, MyRequestScopedApi.class) .addAsManifestResource(new StringAsset(url + "\n" + scope + "\n" + url2), "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; }
@Named @Produces @RequestScoped public PhotoTableModel getPhotoList() { if (photoTableModel == null) { photoTableModel = new PhotoTableModel(); photoTableModel.setPhotoListFilter(photoListFilter); } return photoTableModel; }
/** * List of audit logs or user events. * * @return List of audit log items. */ @Named @Produces @RequestScoped public AuditLogTableModel getAuditLogList() { if (auditLogTableModel == null) { auditLogTableModel = new AuditLogTableModel(); auditLogTableModel.setAuditListFilter(auditListFilter); } return auditLogTableModel; }
/** * List of know bad remote addresses. * * @return List of known bad items. */ @Named @Produces @RequestScoped public KnownBadTableModel getKnownBadList() { if (knownBadTableModel == null) { knownBadTableModel = new KnownBadTableModel(); knownBadTableModel.setKnownBadListFilter(knownBadListFilter); } return knownBadTableModel; }
/** * List of known safe remote addresses. * * @return List of known safe items. */ @Named @Produces @RequestScoped public KnownSafeTableModel getKnownSafeList() { if (knownSafeTableModel == null) { knownSafeTableModel = new KnownSafeTableModel(); knownSafeTableModel.setKnownSafeListFilter(knownSafeListFilter); } return knownSafeTableModel; }
@Named @Produces @RequestScoped public UserTableModel getWebUserList() { if (userTableModel == null) { userTableModel = new UserTableModel(); userTableModel.setUserListFilter(userListFilter); } return userTableModel; }
@Produces @RequestScoped public User user() { Long id = idRef.get(); if (id == null) { return new UserImpl(false, null, Collections.emptyList(), csrfToken); } Key<Account> accountId = new Key<>(id); Account account = accountDao.selectById(accountId).orElse(null); List<AccountRole> accountRoles = grantDao.selectByAccount(accountId).stream() .map(a -> a.role).collect(Collectors.toList()); return new UserImpl(true, account, accountRoles, csrfToken); }
@Produces @Named @Managed @RequestScoped Permission getManagedPermission() { return getInstance(); }
@Produces @Named @Managed @RequestScoped Group getManagedGroup() { return getInstance(); }