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

项目:testee.fi    文件:DependencyInjectionRealm.java   
private <T> T newInstance(final Bean<T> bean, final ReleaseCallbackHandler handler) {
    final CreationalContextImpl<T> ctx = contextFor(bean, handler);
    final T instance = bean.create(ctx);
    ctx.addDependentInstance(new ContextualInstance<T>() {
        @Override
        public T getInstance() {
            return instance;
        }

        @Override
        public CreationalContext<T> getCreationalContext() {
            return ctx;
        }

        @Override
        public Contextual<T> getContextual() {
            return bean;
        }
    });
    return instance;
}
项目:testee.fi    文件:MockingExtension.java   
private <T> ProducerFactory<T> factory(final Object mock) {
    return new ProducerFactory<T>() {
        @Override
        public <T1> Producer<T1> createProducer(final Bean<T1> bean) {
            return new Producer<T1>() {

                @Override
                public T1 produce(final CreationalContext<T1> ctx) {
                    return (T1) mock;
                }

                @Override
                public void dispose(final T1 instance) {
                }

                @Override
                public Set<InjectionPoint> getInjectionPoints() {
                    return Collections.emptySet();
                }
            };
        }
    };
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:ContextSPITestCase.java   
private <T> CreationalContext<T> getCreationalContext() {

        CreationalContext<T> creationalContext = new CreationalContext<T>() {

            private List<T> applicationBeans = new ArrayList<T>();
            private T currentInstance;

            @Override
            public void push(T incompleteInstance) {
                applicationBeans.add(incompleteInstance);
                currentInstance = incompleteInstance;

            }

            @Override
            public void release() {
                applicationBeans.remove(currentInstance);

            }

        };
        return creationalContext;
    }
项目:Mastering-Java-EE-Development-with-WildFly    文件:EventTestCase.java   
/**
 * Tests if exists observer injection in a jar archive
 */
@Test
public void testIfExists() {
    logger.info("starting if exists event test");
    // To test the IF_EXISTS Reception I need to inject the observer bean so
    // it will be instantiated and ready to use
    Set<Bean<?>> beans = beanManager.getBeans(IfExistsObserver.class);
    assertEquals(beans.size(), 1);
    @SuppressWarnings("unchecked")
    Bean<IfExistsObserver> bean = (Bean<IfExistsObserver>) beans.iterator().next();
    CreationalContext<IfExistsObserver> ctx = beanManager.createCreationalContext(bean);
    beanManager.getReference(bean, IfExistsObserver.class, ctx);
    Bill bill = fire();
    assertEquals("The id generation passes through the always and if_exists observers and it is incremented", 10,
            bill.getId());
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:InjectSPITestCase.java   
@Test
public void testInjectionTarget() {
    BeanManager beanManager = current().getBeanManager();
    // CDI uses an AnnotatedType object to read the annotations of a class
    AnnotatedType<String> type = beanManager.createAnnotatedType(String.class);
    // The extension uses an InjectionTarget to delegate instantiation,
    // dependency injection
    // and lifecycle callbacks to the CDI container
    InjectionTarget<String> it = beanManager.createInjectionTarget(type);
    // each instance needs its own CDI CreationalContext
    CreationalContext<String> ctx = beanManager.createCreationalContext(null);
    // instantiate the framework component and inject its dependencies
    String instance = it.produce(ctx); // call the constructor
    it.inject(instance, ctx); // call initializer methods and perform field
                                // injection
    it.postConstruct(instance); // call the @PostConstruct method
    // destroy the framework component instance and clean up dependent
    // objects
    assertNotNull("the String instance is injected now", instance);
    assertTrue("the String instance is injected now but it's empty", instance.isEmpty());
    it.preDestroy(instance); // call the @PreDestroy method
    it.dispose(instance); // it is now safe to discard the instance
    ctx.release(); // clean up dependent objects
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
private <X> AnnotatedField<X> decorateContext(AnnotatedField<X> field) {
    final PersistenceContext persistenceContext = field.getAnnotation(PersistenceContext.class);
    final UniqueIdentifier identifier = UniqueIdentifierLitteral.random();

    Set<Annotation> templateQualifiers = new HashSet<>();
    templateQualifiers.add(ServiceLiteral.SERVICE);
    if (hasUnitName(persistenceContext)) {
        templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceContext.unitName() + ")"));
    }
    Bean<JpaTemplate> bean = manager.getExtension(OsgiExtension.class)
            .globalDependency(JpaTemplate.class, templateQualifiers);

    Set<Annotation> qualifiers = new HashSet<>();
    qualifiers.add(identifier);
    Bean<EntityManager> b = new SimpleBean<>(EntityManager.class, Dependent.class, Collections.singleton(EntityManager.class), qualifiers, () -> {
        CreationalContext<JpaTemplate> context = manager.createCreationalContext(bean);
        JpaTemplate template = (JpaTemplate) manager.getReference(bean, JpaTemplate.class, context);
        return EntityManagerProducer.create(template);
    });
    beans.add(b);

    Set<Annotation> fieldAnnotations = new HashSet<>();
    fieldAnnotations.add(InjectLiteral.INJECT);
    fieldAnnotations.add(identifier);
    return new SyntheticAnnotatedField<>(field, fieldAnnotations);
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
private <X> AnnotatedField<X> decorateUnit(AnnotatedField<X> field) {
    final PersistenceUnit persistenceUnit = field.getAnnotation(PersistenceUnit.class);
    final UniqueIdentifier identifier = UniqueIdentifierLitteral.random();

    Set<Annotation> templateQualifiers = new HashSet<>();
    templateQualifiers.add(ServiceLiteral.SERVICE);
    if (hasUnitName(persistenceUnit)) {
        templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceUnit.unitName() + ")"));
    }
    Bean<EntityManagerFactory> bean = manager.getExtension(OsgiExtension.class)
            .globalDependency(EntityManagerFactory.class, templateQualifiers);

    Set<Annotation> qualifiers = new HashSet<>();
    qualifiers.add(identifier);
    Bean<EntityManagerFactory> b = new SimpleBean<>(EntityManagerFactory.class, Dependent.class, Collections.singleton(EntityManagerFactory.class), qualifiers, () -> {
        CreationalContext<EntityManagerFactory> context = manager.createCreationalContext(bean);
        return (EntityManagerFactory) manager.getReference(bean, EntityManagerFactory.class, context);
    });
    beans.add(b);

    Set<Annotation> fieldAnnotations = new HashSet<>();
    fieldAnnotations.add(InjectLiteral.INJECT);
    fieldAnnotations.add(identifier);
    return new SyntheticAnnotatedField<>(field, fieldAnnotations);
}
项目:crnk-framework    文件:CdiServiceDiscovery.java   
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
    BeanManager beanManager = getBeanManager();

    Type type = clazz;
    if (clazz == JsonApiExceptionMapper.class) {
        TypeLiteral<JsonApiExceptionMapper<?>> typeLiteral = new TypeLiteral<JsonApiExceptionMapper<?>>() {
        };
        type = typeLiteral.getType();
    }

    Set<Bean<?>> beans = beanManager.getBeans(type);
    List<T> list = new ArrayList<>();
    for (Bean<?> bean : beans) {
        CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
        T object = (T) beanManager.getReference(bean, type, creationalContext);
        list.add(object);
    }
    return list;
}
项目:crnk-framework    文件:CdiServiceDiscovery.java   
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
    BeanManager beanManager = getBeanManager();
    Set<Bean<?>> beans = beanManager.getBeans(Object.class);
    List<Object> list = new ArrayList<>();
    for (Bean<?> bean : beans) {
        Class<?> beanClass = bean.getBeanClass();
        Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
        if (annotation.isPresent()) {
            CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
            Object object = beanManager.getReference(bean, beanClass, creationalContext);
            list.add(object);
        }
    }
    return list;
}
项目:weld-junit    文件:ContextImpl.java   
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }
    return instance != null ? instance.get() : null;
}
项目:cito    文件:ExtensionTest.java   
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void initialiseContexts() {
    final WebSocketContext webSocketContext = mock(WebSocketContext.class);
    ReflectionUtil.set(this.extension, "webSocketContext", webSocketContext);
    final AfterDeploymentValidation afterDeploymentValidation = mock(AfterDeploymentValidation.class);
    final Bean<?> bean = mock(Bean.class);
    when(this.beanManager.getBeans(WebSocketSessionHolder.class)).thenReturn(Collections.singleton(bean));
    when(this.beanManager.resolve(any(Set.class))).thenReturn(bean);
    final CreationalContext creationalContext = mock(CreationalContext.class);
    when(this.beanManager.createCreationalContext(bean)).thenReturn(creationalContext);
    final WebSocketSessionHolder webSocketSessionHolder = mock(WebSocketSessionHolder.class);
    when(this.beanManager.getReference(bean, WebSocketSessionHolder.class, creationalContext)).thenReturn(webSocketSessionHolder);

    this.extension.initialiseContexts(afterDeploymentValidation, this.beanManager);

    verify(this.beanManager).getBeans(WebSocketSessionHolder.class);
    verify(this.beanManager).resolve(any(Set.class));
    verify(this.beanManager).createCreationalContext(bean);
    verify(this.beanManager).getReference(bean, WebSocketSessionHolder.class, creationalContext);
    verify(webSocketContext).init(webSocketSessionHolder);
    verifyNoMoreInteractions(webSocketContext, afterDeploymentValidation, bean, creationalContext, webSocketSessionHolder);
}
项目:webpedidos    文件:CDIServiceLocator.java   
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
    BeanManager bm = getBeanManager();
    Set<Bean<?>> beans = bm.getBeans(clazz);

    if (beans == null || beans.isEmpty()) {
        return null;
    }

    Bean<T> bean = (Bean<T>) beans.iterator().next();

    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    T o = (T) bm.getReference(bean, clazz, ctx);

    return o;
}
项目:command-context-example    文件:CommandContextImpl.java   
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }

    return instance != null ? instance.get() : null;
}
项目:ozark    文件:RedirectScopeManager.java   
/**
 * Destroy the instance.
 *
 * @param contextual the contextual.
 */
public void destroy(Contextual contextual) {
    String scopeId = (String) request.getAttribute(SCOPE_ID);
    if (null != scopeId) {
        HttpSession session = request.getSession();
        if (contextual instanceof PassivationCapable == false) {
            throw new RuntimeException("Unexpected type for contextual");
        }
        PassivationCapable pc = (PassivationCapable) contextual;
        final String sessionKey = SCOPE_ID + "-" + scopeId;
        Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
        if (null != scopeMap) {
            Object instance = scopeMap.get(INSTANCE + pc.getId());
            CreationalContext<?> creational = (CreationalContext<?>) scopeMap.get(CREATIONAL + pc.getId());
            if (null != instance && null != creational) {
                contextual.destroy(instance, creational);
                creational.release();
            }
        }
    }
}
项目:ozark    文件:RedirectScopeManager.java   
/**
 * Get the instance (create it if it does not exist).
 *
 * @param <T> the type.
 * @param contextual the contextual.
 * @param creational the creational.
 * @return the instance.
 */
public <T> T get(Contextual<T> contextual, CreationalContext<T> creational) {
    T result = get(contextual);

    if (result == null) {
        String scopeId = (String) request.getAttribute(SCOPE_ID);
        if (null == scopeId) {
            scopeId = generateScopeId();
        }
        HttpSession session = request.getSession();
        result = contextual.create(creational);
        if (contextual instanceof PassivationCapable == false) {
            throw new RuntimeException("Unexpected type for contextual");
        }
        PassivationCapable pc = (PassivationCapable) contextual;
        final String sessionKey = SCOPE_ID + "-" + scopeId;
        Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
        if (null != scopeMap) {
            session.setAttribute(sessionKey, scopeMap);
            scopeMap.put(INSTANCE + pc.getId(), result);
            scopeMap.put(CREATIONAL + pc.getId(), creational);
        }
    }

    return result;
}
项目:katharsis-framework    文件:CdiServiceDiscovery.java   
@Override
public <A extends Annotation> List<Object> getInstancesByAnnotation(Class<A> annotationClass) {
    BeanManager beanManager = CDI.current().getBeanManager();
    Set<Bean<?>> beans = beanManager.getBeans(Object.class);
    List<Object> list = new ArrayList<>();
    for (Bean<?> bean : beans) {
        Class<?> beanClass = bean.getBeanClass();
        Optional<A> annotation = ClassUtils.getAnnotation(beanClass, annotationClass);
        if (annotation.isPresent()) {
            CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
            Object object = beanManager.getReference(bean, beanClass, creationalContext);
            list.add(object);
        }
    }
    return list;
}
项目:wildfly-swarm    文件:DeploymentContextImpl.java   
@SuppressWarnings("unchecked")
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
    Map<Contextual<?>, ContextualInstance<?>> ctx = currentContext.get();

    if (ctx == null) {
        // Thread local not set - context is not active!
        throw new ContextNotActiveException();
    }

    ContextualInstance<T> instance = (ContextualInstance<T>) ctx.get(contextual);

    if (instance == null && creationalContext != null) {
        // Bean instance does not exist - create one if we have CreationalContext
        instance = new ContextualInstance<T>(contextual.create(creationalContext), creationalContext, contextual);
        ctx.put(contextual, instance);
    }

    return instance != null ? instance.get() : null;
}
项目:thymeleaf-mvc    文件:TemplateEngineProducer.java   
/**
 * Producer method building and configuring the {@link TemplateEngine} instance to be used in the application. The
 * engine's template resolver is set up to follow MVC requirements. JAX-RS parameter conversion bridges are
 * detected, and if one is present, the engine is set up to use it.
 *
 * Subclasses can override and {@link javax.enterprise.inject.Specializes specialize} this method to add additional
 * configuration (e.g. call {@link TemplateEngine#addDialect(org.thymeleaf.dialect.IDialect)} to add a dialect).
 *
 * @return the newly created and configured {@link TemplateEngine} instance
 */
@Produces public TemplateEngine getTemplateEngine() {
    final TemplateEngine engine = new TemplateEngine();
    final ITemplateResolver tr = new MVCTemplateResolver(servletContext, mvcContext);
    engine.setTemplateResolver(tr);
    try {
        final Class<?> pcbClass = Class.forName("hu.inbuss.thymeleaf.jaxrs.ParamConverterBridge");
        final Bean<?> pcbBean = beanManager.resolve(beanManager.getBeans(pcbClass));
        final CreationalContext pcbContext = beanManager.createCreationalContext(pcbBean);
        final ParamConverterBridge pcb = (ParamConverterBridge) beanManager.getReference(pcbBean, pcbClass, pcbContext);
        pcb.installInto(engine);
    } catch (final ClassNotFoundException cnfe) {
        // the Jersey integration module is not present, do nothing
    }
    return engine;
}
项目:Purifinity    文件:BeanUtilities.java   
/**
    * Looks a bean to a given type up in JNDI and returns a reference to an
    * instance.
    * 
    * @param type
    *            is the type of the bean to look up.
    * @param <T>
    *            is the generic type of the bean.
    * @return A managed bean of the specified type is returned.
    */
   @SuppressWarnings("unchecked")
   public static <T> T getBean(Class<T> type, Annotation... qualifiers) {
if (beanManager == null) {
    getBeanManager();
}

Set<Bean<?>> beans = beanManager.getBeans(type, qualifiers);

if (beans.size() > 1) {
    throw new RuntimeException(
        "Ambiguous bean references found for type " + type);
}
Bean<T> bean = (Bean<T>) beans.iterator().next();
CreationalContext<T> creationalContext = beanManager
    .createCreationalContext(bean);
return (T) beanManager.getReference(bean, type, creationalContext);
   }
项目: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);
    }
}
项目:Camel    文件:CamelContextOsgiProducer.java   
@Override
public T produce(CreationalContext<T> ctx) {
    T context = super.produce(ctx);

    // Register the context in the OSGi registry
    BundleContext bundle = BundleContextUtils.getBundleContext(getClass());
    context.getManagementStrategy().addEventNotifier(new OsgiCamelContextPublisher(bundle));

    if (!(context instanceof DefaultCamelContext)) {
        // Fail fast for the time being to avoid side effects by some methods get declared on the CamelContext interface
        throw new InjectionException("Camel CDI requires Camel context [" + context.getName() + "] to be a subtype of DefaultCamelContext");
    }

    DefaultCamelContext adapted = context.adapt(DefaultCamelContext.class);
    adapted.setRegistry(OsgiCamelContextHelper.wrapRegistry(context, context.getRegistry(), bundle));
    CamelContextNameStrategy strategy = context.getNameStrategy();
    OsgiCamelContextHelper.osgiUpdate(adapted, bundle);
    // FIXME: the above call should not override explicit strategies provided by the end user or should decorate them instead of overriding them completely
    if (!(strategy instanceof DefaultCamelContextNameStrategy)) {
        context.setNameStrategy(strategy);
    }

    return context;
}
项目:Camel    文件:CdiEventEndpoint.java   
@Override
public Producer createProducer() throws IllegalAccessException {
    // FIXME: to be replaced once event firing with dynamic parameterized type
    // is properly supported (see https://issues.jboss.org/browse/CDI-516)
    TypeLiteral<T> literal = new TypeLiteral<T>() {
    };
    for (Field field : TypeLiteral.class.getDeclaredFields()) {
        if (field.getType().equals(Type.class)) {
            field.setAccessible(true);
            field.set(literal, type);
            break;
        }
    }

    InjectionTarget<AnyEvent> target = manager.createInjectionTarget(manager.createAnnotatedType(AnyEvent.class));
    CreationalContext<AnyEvent> ctx = manager.createCreationalContext(null);
    AnyEvent instance = target.produce(ctx);
    target.inject(instance, ctx);
    return new CdiEventProducer<>(this, instance.event
        .select(literal, qualifiers.stream().toArray(Annotation[]::new)));
}
项目:PedidoVenda    文件:CDIServiceLocator.java   
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
    BeanManager bm = getBeanManager();
    Set<Bean<?>> beans = bm.getBeans(clazz);

    if (beans == null || beans.isEmpty()) {
        return null;
    }

    Bean<T> bean = (Bean<T>) beans.iterator().next();

    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    T o = (T) bm.getReference(bean, clazz, ctx);

    return o;
}
项目:PedidoVenda    文件:ViewScopedContext.java   
@SuppressWarnings("unchecked")
@Override
public <T> T get(final Contextual<T> component, final CreationalContext<T> creationalContext) {
    assertActive();

    T instance = get(component);
    if (instance == null) {
        if (creationalContext != null) {
            Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
            Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap();

            synchronized (componentInstanceMap) {
                instance = (T) componentInstanceMap.get(component);
                if (instance == null) {
                    instance = component.create(creationalContext);
                    if (instance != null) {
                        componentInstanceMap.put(component, instance);
                        creationalContextMap.put(component, creationalContext);
                    }
                }
            }
        }
    }

    return instance;
}
项目:PedidoVenda    文件:ViewScopedContext.java   
/**
 * We get PreDestroyViewMapEvent events from the JSF servlet and destroy our
 * contextual instances. This should (theoretically!) also get fired if the
 * webapp closes, so there should be no need to manually track all view
 * scopes and destroy them at a shutdown.
 * 
 * @see javax.faces.event.SystemEventListener#processEvent(javax.faces.event.SystemEvent)
 */
@SuppressWarnings("unchecked")
@Override
public void processEvent(final SystemEvent event) {
    if (event instanceof PreDestroyViewMapEvent) {
        Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
        Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap();

        if (componentInstanceMap != null) {
            for (Map.Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) {
                /*
                 * No way to inform the compiler of type <T> information, so
                 * it has to be abandoned here :(
                 */
                Contextual contextual = componentEntry.getKey();
                Object instance = componentEntry.getValue();
                CreationalContext creational = creationalContextMap.get(contextual);

                contextual.destroy(instance, creational);
            }
        }
    }
}
项目:dolphin-platform    文件:DolphinPlatformContextualLifecycle.java   
@Override
public T create(Bean<T> bean, CreationalContext<T> creationalContext) {
    Assert.requireNonNull(bean, "bean");
    Assert.requireNonNull(creationalContext, "creationalContext");
    if(interceptor == null) {
        throw new ModelInjectionException("No interceptor defined!");
    }
    try {
        T instance = injectionTarget.produce(creationalContext);
        interceptor.intercept(instance);
        injectionTarget.inject(instance, creationalContext);
        injectionTarget.postConstruct(instance);
        return instance;
    } finally {
        interceptor = null;
    }
}
项目:appformer    文件:SystemConfigProducerTest.java   
@Test
public void createAndDestroyFSShouldRegisterUnregisterOnPriorityDisposableRegistry() throws Exception {

    when(bm.getBeans("configIO")).thenReturn(configIOBeans);
    when(bm.getReference(eq(ioServiceBean),
                         eq(IOService.class),
                         any(CreationalContext.class)))
            .thenReturn(ioServiceMock);
    when(ioServiceMock.newFileSystem(any(URI.class),
                                     any(Map.class)))
            .thenReturn(fs);

    final Bean fileSystemBean = producer.createFileSystemBean(bm,
                                                              mock(InjectionTarget.class));

    assertNull(PriorityDisposableRegistry.get("systemFS"));

    fileSystemBean.create(mock(CreationalContext.class));

    assertNotNull(PriorityDisposableRegistry.get("systemFS"));

    fileSystemBean.destroy(fs,
                           mock(CreationalContext.class));

    assertNull(PriorityDisposableRegistry.get("systemFS"));
}
项目:ocelot    文件:CdiBootstrapTest.java   
/**
 * Test of getBean method, of class CdiBootstrap.
 * @throws javax.naming.NamingException
 */
@Test
public void testGetBean() throws NamingException {
    System.out.println("getBean");
    Bean b = mock(Bean.class);
    when(b.getBeanClass()).thenReturn(Result.class);

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(b);

    CreationalContext context = mock(CreationalContext.class);

    BeanManager bm = mock(BeanManager.class);
    when(bm.getBeans(eq(Result.class), any(Annotation.class))).thenReturn(beans);
    when(bm.createCreationalContext(eq(b))).thenReturn(context);
    when(bm.getReference(eq(b), eq(Result.class), eq(context))).thenReturn(new Result());

    when(cdiBootstrap.getBeanManager()).thenReturn(bm);

    Object result = cdiBootstrap.getBean(Result.class);
    assertThat(result).isInstanceOf(Result.class);

}
项目:ocelot    文件:CdiBeanResolverTest.java   
@Test
public void testGetBean() throws NamingException {
    System.out.println("getBean");
    CdiBeanResolver instance = spy(CdiBeanResolver.class);
    CdiBeanResolver.raz();
    InitialContext ic = mock(InitialContext.class);
    BeanManager bm = mock(BeanManager.class);
    Set<Bean<?>> beans = new HashSet<>();
    Bean<?> b = mock(Bean.class);
    beans.add(b);
    CreationalContext context = mock(CreationalContext.class);

    doReturn(ic).when(instance).getInitialContext();
    when(ic.lookup(eq(Constants.BeanManager.BEANMANAGER_JEE))).thenReturn(bm);
    when(bm.getBeans(any(Class.class), any(Annotation.class))).thenReturn(beans);
    when(bm.createCreationalContext(eq(b))).thenReturn(context);
    when(bm.getReference(eq(b), any(Class.class), eq(context))).thenReturn(this);
    Object result = instance.getBean(this.getClass());
    assertThat(result).isInstanceOf(this.getClass());
}
项目:osgi.ee    文件:ContextBeansHolder.java   
/**
 * Create the holder/cache of the beans.
 * 
 * @param listener A listener for changes to the cache
 */
ContextBeansHolder(ContextBeansListener listener) {
    this.listener = listener;
    if (this.listener == null) {
        this.listener = new ContextBeansListener() {
            @Override
            public void instanceRemoved(Contextual<?> bean,
                    CreationalContext<?> context, Object instance) {
            }
            @Override
            public void instanceAdded(Contextual<?> bean, CreationalContext<?> context,
                    Object instance) {
            }
        };
    }
}
项目:assetmanager    文件:DefaultAssetTaskHandler.java   
@SuppressWarnings("unchecked")
public <R> R execute(DefaultAssetTask task, Class<R> resultType) {
    String taskId = UUID.randomUUID().toString();
    TaskContext context = new DefaultTaskContext(taskId, task);
    Bean<Task> bean = getBean(task.getTaskName());
    CreationalContext<Task> creationalContext = (CreationalContext<Task>) beanManager.createCreationalContext(bean);
    try {
        CurrentTaskContext.set(context);
        Task instance = (Task) beanManager.getReference(bean, Task.class, creationalContext);
        R result = (R) instance.execute();
        beanManager.fireEvent(new TaskExecuted(context));
        return result;
    } finally {
        CurrentTaskContext.clear();
        creationalContext.release();
    }
}
项目:johnzon    文件:CdiJohnzonAdapterFactory.java   
@Override
public <T> Instance<T> create(final Class<T> type) {
    try {
        final Set<Bean<?>> beans = bm.getBeans(type);
        final Bean<?> bean = bm.resolve(beans);
        if (bean != null) {
            final CreationalContext<Object> creationalContext = bm.createCreationalContext(null);
            final T instance = (T) bm.getReference(bean, type, creationalContext);
            if (bm.isNormalScope(bean.getScope())) {
                return new ConstantInstance<>((T) bm.getReference(bean, type, creationalContext));
            }
            return new CdiInstance<T>(instance, creationalContext);
        }
    } catch (final Exception e) {
        // fallback
    }
    return super.create(type);
}
项目:rabbitmq-support    文件:RabbitMQSupportProducer.java   
@Produces
@Consumers
public List<Object> consumerList(BeanManager beanManager, InjectionPoint injectionPoint) throws IllegalAccessException, InstantiationException {
    Reflections reflections = new Reflections(injectionPoint.getAnnotated().getAnnotation(Consumers.class).packagePrefixScan());
    Set<Class<? extends Object>> subTypesOf = (Set) reflections.getTypesAnnotatedWith(RabbitMQConsumer.class);
    List<Object> consumers = new LinkedList<Object>();

    for (Class<? extends Object> clazz : subTypesOf) {
        Set<Bean<?>> beans = beanManager.getBeans(clazz);
        Bean<?> bean = beans.iterator().next();
        CreationalContext<? extends Object> ctx = (CreationalContext<? extends Object>) beanManager.createCreationalContext(bean);
        Object consumer = (Object) beanManager.getReference(bean, clazz, ctx);
        consumers.add(consumer);
    }

    return consumers;
}
项目:goFitOne    文件:CDIServiceLocator.java   
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
    BeanManager bm = getBeanManager();
    Set<Bean<?>> beans = (Set<Bean<?>>) bm.getBeans(clazz);

    if (beans == null || beans.isEmpty()) {
        return null;
    }

    Bean<T> bean = (Bean<T>) beans.iterator().next();

    CreationalContext<T> ctx = bm.createCreationalContext(bean);
    T o = (T) bm.getReference(bean, clazz, ctx);

    return o;
}
项目:goFitOne    文件:ViewScopedContext.java   
@Override
public <T> T get(final Contextual<T> component, final CreationalContext<T> creationalContext) {
    assertActive();

    T instance = get(component);
    if (instance == null) {
        if (creationalContext != null) {
            Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
            Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap();

            synchronized (componentInstanceMap) {
                instance = (T) componentInstanceMap.get(component);
                if (instance == null) {
                    instance = component.create(creationalContext);
                    if (instance != null) {
                        componentInstanceMap.put(component, instance);
                        creationalContextMap.put(component, creationalContext);
                    }
                }
            }
        }
    }

    return instance;
}
项目:goFitOne    文件:ViewScopedContext.java   
/**
 * We get PreDestroyViewMapEvent events from the JSF servlet and destroy our
 * contextual instances. This should (theoretically!) also get fired if the
 * webapp closes, so there should be no need to manually track all view
 * scopes and destroy them at a shutdown.
 * 
 * @see javax.faces.event.SystemEventListener#processEvent(javax.faces.event.SystemEvent)
 */
@Override
public void processEvent(final SystemEvent event) {
    if (event instanceof PreDestroyViewMapEvent) {
        Map<Contextual<?>, Object> componentInstanceMap = getComponentInstanceMap();
        Map<Contextual<?>, CreationalContext<?>> creationalContextMap = getCreationalInstanceMap();

        if (componentInstanceMap != null) {
            for (Map.Entry<Contextual<?>, Object> componentEntry : componentInstanceMap.entrySet()) {
                /*
                 * No way to inform the compiler of type <T> information, so
                 * it has to be abandoned here :(
                 */
                Contextual contextual = componentEntry.getKey();
                Object instance = componentEntry.getValue();
                CreationalContext creational = creationalContextMap.get(contextual);

                contextual.destroy(instance, creational);
            }
        }
    }
}
项目:portals-pluto    文件:PortletSessionScopedBeanMap.java   
/**
 * Removes & destroys the given bean from the given bean map
 * @param bean
 */
@SuppressWarnings("unchecked")
private <T> void remove(String id, Map<Contextual<?>, BeanInstance<?>> beanMap, Contextual<T> bean) {
   BeanInstance<?> bi = beanMap.get(bean);

   if (isDebug) {
      StringBuilder txt = new StringBuilder(80);
      txt.append("Removing bean: ");
      if (bean instanceof Bean<?>) {
         Bean<?> b = (Bean<?>) bean;
         txt.append(b.getBeanClass().getSimpleName());
      }
      txt.append(", window ID: ").append(id);
      if (bi == null) {
         txt.append(", instance is null.");
      }
      LOG.debug(txt.toString());
   }

   if (bi != null) {
      beans.remove(bean);
      bi.crco.release();
      bean.destroy((T)bi.instance, (CreationalContext<T>)bi.crco);
   }
}
项目:portals-pluto    文件:PortletStateScopedBeanHolder.java   
/**
 * Removes & destroys the given bean
 * @param bean
 */
@SuppressWarnings("unchecked")
protected <T> void remove(Contextual<T> bean) {
   BeanInstance<?> bi = beans.get(bean);

   if (isTrace) {
      StringBuilder txt = new StringBuilder(80);
      txt.append("Removing render state scoped bean: ");
      if (bean instanceof Bean<?>) {
         Bean<?> b = (Bean<?>) bean;
         txt.append(b.getBeanClass().getSimpleName());
      }
      if (bi == null) {
         txt.append(", instance is null.");
      }
      LOG.trace(txt.toString());
   }

   if (bi != null) {
      beans.remove(bean);
      bi.crco.release();
      bean.destroy((T)bi.instance, (CreationalContext<T>)bi.crco);
   }
}
项目:portals-pluto    文件:PortletSessionScopedContext.java   
@Override
public <T> T get(Contextual<T> bean, CreationalContext<T> crco) {
   PortletSessionBeanHolder holder = PortletSessionBeanHolder.getBeanHolder();

   if (holder == null) {
      throw new ContextNotActiveException("The portlet session context is not active.");
   }

   T inst = holder.getBean(bean);
   if (inst == null) {
      inst = bean.create(crco);
      holder.putBeanInstance(bean, crco, inst);
   }

   return inst;
}
项目:portals-pluto    文件:PortletRequestScopedBeanHolder.java   
/**
 * Returns an instance for the contextual type. If no existing bean is available,
 * a new instance is created.
 * 
 * @param bean       Contextual type (Bean) for which an instance is desired
 * @return           The instance, or null if none exists
 */
@SuppressWarnings("unchecked")
public <T> T getBean(Contextual<T> bean, CreationalContext<T> crco) {
   BeanInstance<?> bi = beans.get(bean);

   if (bi == null) {

      // No bean available, so create one.

      BeanInstance<T> newbi = new BeanInstance<T>();
      newbi.crco = crco;
      newbi.instance = bean.create(crco);
      bi = newbi;
      beans.put(bean, newbi);

      if (isTrace) {
         StringBuilder txt = new StringBuilder(80);
         txt.append("Created bean: ");
         txt.append(((Bean<?>) bean).getBeanClass().getSimpleName());
         LOG.trace(txt.toString());
      }

   }

   return (T) bi.instance;
}