Java 类javax.enterprise.context.spi.Context 实例源码

项目:cdicron    文件:BeanMethodInvocationRunnable.java   
@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);
    }
}
项目:HotswapAgent    文件:ContextualReloadHelper.java   
/**
 * 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;
}
项目:HotswapAgent    文件:ContextualReloadHelper.java   
/**
 * 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);
    }
}
项目:HotswapAgent    文件:ContextualReloadHelper.java   
/**
 * 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;
}
项目:HotswapAgent    文件:BeanReloadExecutor.java   
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.");
    }
}
项目:HotswapAgent    文件:WindowContextsTracker.java   
@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;
}
项目:tomee    文件:RequestScopedThreadContextListener.java   
@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));
    }
}
项目:tomee    文件:EnsureRequestScopeThreadLocalIsCleanUpTest.java   
@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));
}
项目:joynr    文件:JoynrJeeMessageContextTest.java   
@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.");
    }
}
项目:AngularBeans    文件:BeanLocator.java   
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;
    }
项目:HotswapAgent    文件:BeanClassRefreshAgent.java   
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());
        }
    }
项目:HotswapAgent    文件:BeanClassRefreshAgent.java   
@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());
    }
}
项目:HotswapAgent    文件:BeanClassRefreshAgent.java   
@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();
}
项目:HotswapAgent    文件:BeanClassRefreshAgent.java   
@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();
}
项目:HotswapAgent    文件:BeanClassRefreshAgent.java   
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);
    }
}
项目:HotswapAgent    文件:ContextualReloadHelper.java   
/**
 * 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);
    }
}
项目:HotswapAgent    文件:BeanReloadExecutor.java   
@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();
}
项目:HotswapAgent    文件:BeanReloadExecutor.java   
@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());
    }
}
项目:HotswapAgent    文件:BeanReloadExecutor.java   
@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();
}
项目:HotswapAgent    文件:BeanReloadExecutor.java   
@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);
    }
}
项目:tomee    文件:WebBeansListenerHelper.java   
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);
    }
}
项目:tomee    文件:WebappBeanManager.java   
@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;
        }
    }
}
项目:AngularBeans    文件:NGSessionScopeContext.java   
public static Context getINSTANCE() {
    if (INSTANCE == null)
        INSTANCE = new NGSessionScopeContext();
    return INSTANCE;
}
项目:tapestry-jpa-transactions    文件:NoopBeanManager.java   
@Override
public Context getContext(Class<? extends Annotation> scopeType)
{
    // TODO Auto-generated method stub
    return null;
}
项目:jbromo    文件:BeanManagerExt.java   
@Override
public Context getContext(final Class<? extends Annotation> arg0) {
    return this.beanManager.getContext(arg0);
}
项目:tomee    文件:CdiPlugin.java   
@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;
    }
}
项目:tomee    文件:ApplicationScopedTest.java   
@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);
}
项目:AngularBeans    文件:AngularBeansCDIExtension.java   
/**
 * <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);
}
项目:tomee    文件:ApplicationScopedTest.java   
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;
    }