@Override public void run() { if (firstInit) { Context theContext = beanManager.getContext(bean.getScope()); instance = theContext.get(bean); if (instance == null) { CreationalContext theCreational = beanManager.createCreationalContext(bean); instance = beanManager.getReference(bean, bean.getBeanClass(), theCreational); } firstInit = false; } try { method.invoke(instance, new Object[0]); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Tries to add the bean in the context so it is reloaded in the next activation of the context. * * @param ctx * @param managedBean * @return */ @SuppressWarnings("unchecked") public static boolean addToReloadSet(Context ctx, Contextual<?> managedBean) { try { LOGGER.debug("Adding bean '{}' to context '{}'", managedBean, ctx.getClass()); Field toRedefine = ctx.getClass().getField("$$ha$toReloadOwb"); Set toReload = Set.class.cast(toRedefine.get(ctx)); if (toReload == null) { toReload = new HashSet(); toRedefine.set(ctx, toReload); } toReload.add(managedBean); return true; } catch(Exception e) { LOGGER.warning("Context '{}' is not patched. Can not add bean '{}' to reload set", e, ctx, managedBean); } return false; }
/** * Will re-inject any managed beans in the target. Will not call any other life-cycle methods * * @param ctx * @param managedBean */ @SuppressWarnings("unchecked") static void reinitialize(Context ctx, Contextual<Object> contextual) { try { ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual); LOGGER.debug("Re-Initializing bean '{}' in context '{}'", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean); CreationalContextImpl<Object> creationalContext = managedBean.getWebBeansContext().getCreationalContextFactory().getCreationalContext(managedBean); managedBean.getProducer().inject(get, creationalContext); } } catch (Exception e) { LOGGER.error("Error reinitializing bean '{}' in context '{}'", e, contextual, ctx); } }
/** * Tries to add the bean in the context so it is reloaded in the next activation of the context. * * @param ctx * @param managedBean * @return */ public static boolean addToReloadSet(Context ctx, Contextual<Object> managedBean) { try { LOGGER.debug("Adding bean in '{}' : {}", ctx.getClass(), managedBean); Field toRedefine = ctx.getClass().getDeclaredField("$$ha$toReloadWeld"); Set toReload = Set.class.cast(toRedefine.get(ctx)); if (toReload == null) { toReload = new HashSet(); toRedefine.set(ctx, toReload); } toReload.add(managedBean); return true; } catch(Exception e) { LOGGER.warning("Context {} is not patched. Can not add {} to reload set", e, ctx, managedBean); } return false; }
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."); } }
@Override public Iterator<Object> iterator() { BeanManager beanManager = CDI.current().getBeanManager(); Bean<WindowBeanHolder> bean = resolveBean(beanManager, WindowBeanHolder.class); if (bean != null) { Context sessionContext = beanManager.getContext(bean.getScope()); if (sessionContext != null) { WindowBeanHolder beanHolder = sessionContext.get(bean); Map<String, ContextualStorage> storageMap = (Map<String, ContextualStorage>) ReflectionHelper.get(beanHolder, "storageMap"); if (storageMap != null) { return new WindowContextsIterator(new ArrayList<String>(storageMap.keySet())); } } else { LOGGER.debug("No WindowBeanHolder found, no active session context."); } } return 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)); }
@Test 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."); } }
public Object lookup(String beanName, String sessionID) { NGSessionScopeContext.setCurrentContext(sessionID); Set<Bean<?>> beans = beanManager.getBeans(beanName); Class beanClass = CommonUtils.beanNamesHolder.get(beanName); if (beans.isEmpty()) { beans = beanManager.getBeans(beanClass, new AnnotationLiteral<Any>() { // }); } Bean bean = beanManager.resolve(beans); Class scopeAnnotationClass = bean.getScope(); Context context; if (scopeAnnotationClass.equals(RequestScoped.class)) { context = beanManager.getContext(scopeAnnotationClass); if (context == null) return bean.create(beanManager.createCreationalContext(bean)); } else { if (scopeAnnotationClass.equals(NGSessionScopeContext.class)) { context = NGSessionScopeContext.getINSTANCE(); } else { context = beanManager.getContext(scopeAnnotationClass); } } CreationalContext creationalContext = beanManager.createCreationalContext(bean); Object reference = context.get(bean, creationalContext); // if(reference==null && scopeAnnotationClass.equals(RequestScoped.class)){ // reference= bean.create(beanManager.createCreationalContext(bean)); // } return reference; }
private static void doReinjectSessionBasedBean(BeanManagerImpl beanManager, Class<?> beanClass, InjectionTargetBean<?> bean) { ContextsService contextsService = beanManager.getWebBeansContext().getContextsService(); // SessionContextsTracker can't be directly used here, since it may not be in the visible class loader (Tomee) // therefore inner Iterator is used as workaround Object sessionContextsTracker = ReflectionHelper.get(contextsService, WebBeansContextsServiceTransformer.SESSION_CONTEXTS_TRACKER_FIELD); if (sessionContextsTracker != null) { try { Iterator<?> sessionContextIterator = ((Iterable<?> ) sessionContextsTracker).iterator(); while (sessionContextIterator.hasNext()) { sessionContextIterator.next(); // Set next active session context Context sessionContext = beanManager.getContext(SessionScoped.class); if (bean.getScope() == SessionScoped.class) { doReinjectBeanInstance(beanManager, beanClass, bean, sessionContext); } else { doReinjectCustomScopedBean(beanManager, beanClass, bean, sessionContext); } SessionScopedBeanInterceptorHandler.removeThreadLocals(); } } finally { contextsService.removeThreadLocals(); } } else { LOGGER.error("Field '{}' not found in class '{}'", WebBeansContextsServiceTransformer.SESSION_CONTEXTS_TRACKER_FIELD, contextsService.getClass().getName()); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static void doReinjectBeanInstance(BeanManagerImpl beanManager, Class<?> beanClass, InjectionTargetBean bean, Context context) { Object instance = context.get(bean); if (instance != null) { bean.getProducer().inject(instance, beanManager.createCreationalContext(bean)); LOGGER.info("Bean '{}' injection points was reinjected.", beanClass.getName()); } }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Map<Class<? extends Annotation>, List<Context>> getContextMap(BeanManagerImpl beanManagerImpl){ try { Field contextsField = BeanManagerImpl.class.getField("contextMap"); contextsField.setAccessible(true); return (Map) contextsField.get(beanManagerImpl); } catch (IllegalAccessException |IllegalArgumentException | NoSuchFieldException | SecurityException e) { LOGGER.warning("Field BeanManagerImpl.contextMap is not accessible", e); } return Collections.emptyMap(); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static Map<Class<? extends Annotation>, Context> getSingleContextMap(BeanManagerImpl beanManagerImpl){ try { Field contextsField = BeanManagerImpl.class.getField("singleContextMap"); contextsField.setAccessible(true); return (Map) contextsField.get(beanManagerImpl); } catch (IllegalAccessException |IllegalArgumentException | NoSuchFieldException | SecurityException e) { LOGGER.warning("Field BeanManagerImpl.singleContextMap is not accessible", e); } return Collections.emptyMap(); }
private static void doReloadBeanInContext(BeanManagerImpl beanManager, Class<?> beanClass, InjectionTargetBean bean, Context context) { if (ContextualReloadHelper.addToReloadSet(context, bean)) { LOGGER.debug("Bean {}, added to reload set in context '{}'", bean, context.getClass()); } else { // fallback: try to reinitialize injection points instead... doReinjectBeanInstance(beanManager, beanClass, bean, context); } }
/** * Will re-inject any managed beans in the target. Will not call any other life-cycle methods * * @param ctx * @param managedBean */ public static void reinitialize(Context ctx, Contextual<Object> contextual) { try { ManagedBean<Object> managedBean = ManagedBean.class.cast(contextual); LOGGER.debug("Re-Initializing........ {},: {}", managedBean, ctx); Object get = ctx.get(managedBean); if (get != null) { LOGGER.debug("Bean injection points are reinitialized '{}'", managedBean); managedBean.getProducer().inject(get, managedBean.getBeanManager().createCreationalContext(managedBean)); } } catch (Exception e) { LOGGER.error("Error reinitializing bean {},: {}", e, contextual, ctx); } }
@SuppressWarnings("unchecked") private static Map<Class<? extends Annotation>, List<Context>> getContexts(BeanManagerImpl beanManager){ try { return Map.class.cast(ReflectionHelper.get(beanManager, "contexts")); } catch (Exception e) { LOGGER.warning("BeanManagerImpl.contexts not accessible", e); } return Collections.emptyMap(); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static void doReinjectBeanInstance(BeanManagerImpl beanManager, Class<?> beanClass, AbstractClassBean bean, Context context) { Object get = context.get(bean); if (get != null) { bean.getProducer().inject(get, beanManager.createCreationalContext(bean)); LOGGER.info("Bean '{}' injection points was reinjected.", beanClass.getName()); } }
@SuppressWarnings("unchecked") private static Map<Class<? extends Annotation>, List<Context>> getContextMap(BeanManagerImpl beanManager) { try { return Map.class.cast(ReflectionHelper.get(beanManager, "contexts")); } catch (Exception e) { LOGGER.warning("BeanManagerImpl.contexts not accessible", e); } return Collections.emptyMap(); }
@SuppressWarnings({ "unchecked", "rawtypes" }) private static void doReloadBeanInContext(BeanManagerImpl beanManager, Class<?> beanClass, ManagedBean managedBean, Context context) { if(ContextualReloadHelper.addToReloadSet(context, managedBean)) { LOGGER.debug("Bean {}, added to reload set in context '{}'", managedBean, context.getClass()); } else { // fallback for not patched contexts doReinjectBean(beanManager, beanClass, managedBean); } }
public static void ensureRequestScope(final ContextsService cs, final ServletRequestListener listener) { final Context reqCtx = cs.getCurrentContext(RequestScoped.class); if (reqCtx == null || !cs.getCurrentContext(RequestScoped.class).isActive()) { listener.requestInitialized(null); FAKE_REQUEST.set(true); } }
@Override public Context getContext(final Class<? extends Annotation> scope) { try { return super.getContext(scope); } catch (final RuntimeException e) { try { return getParentBm().getContext(scope); } catch (final RuntimeException ignored) { throw e; } } }
public static Context getINSTANCE() { if (INSTANCE == null) INSTANCE = new NGSessionScopeContext(); return INSTANCE; }
@Override public Context getContext(Class<? extends Annotation> scopeType) { // TODO Auto-generated method stub return null; }
@Override public Context getContext(final Class<? extends Annotation> arg0) { return this.beanManager.getContext(arg0); }
@Override public Object getSessionBeanProxy(final Bean<?> inBean, final Class<?> interfce, final CreationalContext<?> creationalContext) { Object instance = cacheProxies.get(inBean); if (instance != null) { return instance; } synchronized (inBean) { // singleton for the app so safe to sync on it instance = cacheProxies.get(inBean); if (instance != null) { return instance; } final Class<? extends Annotation> scopeClass = inBean.getScope(); final CdiEjbBean<Object> cdiEjbBean = (CdiEjbBean<Object>) inBean; final CreationalContext<Object> cc = (CreationalContext<Object>) creationalContext; if (scopeClass == null || Dependent.class == scopeClass) { // no need to add any layer, null = @New return cdiEjbBean.createEjb(cc); } // only stateful normally final InstanceBean<Object> bean = new InstanceBean<Object>(cdiEjbBean); if (webBeansContext.getBeanManagerImpl().isNormalScope(scopeClass)) { final BeanContext beanContext = cdiEjbBean.getBeanContext(); final Provider provider = webBeansContext.getNormalScopeProxyFactory().getInstanceProvider(beanContext.getClassLoader(), cdiEjbBean); if (!beanContext.isLocalbean()) { final List<Class> interfaces = new ArrayList<Class>(); final InterfaceType type = beanContext.getInterfaceType(interfce); if (type != null) { interfaces.addAll(beanContext.getInterfaces(type)); } else { // can happen when looked up from impl instead of API in OWB -> default to business local interfaces.addAll(beanContext.getInterfaces(InterfaceType.BUSINESS_LOCAL)); } interfaces.add(Serializable.class); interfaces.add(IntraVmProxy.class); if (BeanType.STATEFUL.equals(beanContext.getComponentType()) || BeanType.MANAGED.equals(beanContext.getComponentType())) { interfaces.add(BeanContext.Removable.class); } try { instance = ProxyManager.newProxyInstance(interfaces.toArray(new Class<?>[interfaces.size()]), new InvocationHandler() { @Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { try { return method.invoke(provider.get(), args); } catch (final InvocationTargetException ite) { throw ite.getCause(); } } }); } catch (final IllegalAccessException e) { throw new OpenEJBRuntimeException(e); } } else { final NormalScopeProxyFactory normalScopeProxyFactory = webBeansContext.getNormalScopeProxyFactory(); final Class<?> proxyClass = normalScopeProxyFactory.createProxyClass(beanContext.getClassLoader(), beanContext.getBeanClass()); instance = normalScopeProxyFactory.createProxyInstance(proxyClass, provider); } cacheProxies.put(inBean, instance); } else { final Context context = webBeansContext.getBeanManagerImpl().getContext(scopeClass); instance = context.get(bean, cc); } bean.setOwbProxy(instance); return instance; } }
@Test public void test() throws Exception { final Context appContext = beanManager.getContext(ApplicationScoped.class); final Green green = createAndMutate(appContext, Green.class); final Blue blue = createAndMutate(appContext, Blue.class); assertEquals(green.getMessage(), blue.getGreen().getMessage()); final BrownLocal brownLocal = createAndMutate(appContext, BrownLocal.class); final Green green2 = brownLocal.getGreen(); green2.getMessage(); final Orange orange = createAndMutate(appContext, Orange.class); assertNotNull(orange); assertNotNull(orange.getBlue()); assertNotNull(orange.getBlue().getGreen()); assertNotNull(orange.getGreen()); final Green greenA = orange.getBlue().getGreen(); final Green greenB = orange.getGreen(); assertSame(greenA, greenB); }
/** * <p> * Invoked by the container once all the annotated types has bean discovered, then registers * the NGSessionScopeContext (and the NGSessionScoped custom CDI scope) * </p> * * @see javax.enterprise.inject.spi.AfterBeanDiscovery * @see javax.enterprise.inject.spi.BeanManager * @see angularBeans.context.NGSessionScoped * @see angularBeans.context.NGSessionScopeContext */ public void registerContext(@Observes final AfterBeanDiscovery event, BeanManager manager) { Context context = NGSessionScopeContext.getINSTANCE(); event.addContext(context); }
private <T extends Message> T createAndMutate(final Context context, final Class<T> beanType) { final Bean<T> bean = (Bean<T>) beanManager.getBeans(beanType).iterator().next(); // We haven't created anything yet, so the instance should not exist in the context assertNull(context.get(bean)); final CreationalContext<T> cc1 = beanManager.createCreationalContext(bean); // This should create the instance and put it in the context final T instance = context.get(bean, cc1); // Assert the instance is now in the context and can be generically retrieved assertNotNull(context.get(bean)); final String prefix = beanType.getSimpleName(); // Mutate the instance... instance.setMessage(prefix + ": hello application"); // Now check the reference in the context assertEquals(prefix + ": hello application", context.get(bean, cc1).getMessage()); // Attempt to create a second instance (should not work) final CreationalContext<T> cc2 = beanManager.createCreationalContext(bean); // We should still have the same mutated instance as before assertEquals(prefix + ": hello application", context.get(bean, cc2).getMessage()); // Mutate the instance one more time instance.setMessage(prefix + ": hello again application"); // And double check that we still just have the single instance in the context assertEquals(prefix + ": hello again application", context.get(bean).getMessage()); assertEquals(prefix + ": hello again application", context.get(bean, null).getMessage()); assertEquals(prefix + ": hello again application", context.get(bean, cc1).getMessage()); assertEquals(prefix + ": hello again application", context.get(bean, cc2).getMessage()); return instance; }