Java 类javax.enterprise.inject.spi.Bean 实例源码

项目: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    文件:DependencyInjectionRealm.java   
private <T> T unique(final Class clazz, final Collection<T> set) {
    if (set.isEmpty()) {
        final Set<Bean<?>> allBeans = container().beanDeploymentArchives().values().stream()
                .map(BeanManagerImpl::getBeans)
                .flatMap(Collection::stream)
                .collect(toSet());
        throw new TestEEfiException("No matching bean found for class "
                + clazz.getName()
                + ", available beans are: "
                + allBeans
        );
    } else if (set.size() > 1) {
        throw new TestEEfiException("Multiple ambiguous beans found for class " + clazz.getName());
    } else {
        return set.iterator().next();
    }
}
项目: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    文件: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 testProducer() {
    logger.info("starting producer spi test");
    CDI<Object> cdi = current();
    BeanManager beanManager = cdi.select(BeanManager.class).get();

    AnnotatedField<? super AnotherFactory> field = this
            .<AnotherFactory, AnnotatedField<AnotherFactory>>getAnnotatedMember(AnotherFactory.class, "jessie",
                    beanManager);
    Bean<AnotherFactory> declaringBean = cast(beanManager.resolve(beanManager.getBeans(AnotherFactory.class)));
    ProducerFactory<AnotherFactory> producerFactory = beanManager.getProducerFactory(field, declaringBean);
    Producer<Toy> producer = cast(producerFactory.createProducer(null));
    assertNotNull(producer);
    assertTrue(producer.getInjectionPoints().isEmpty());
    Toy jessie = producer.produce(beanManager.<Toy>createCreationalContext(null));
    assertEquals("Jessie", jessie.getName());
}
项目: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);
}
项目:acmeair-modular    文件:ServiceLocator.java   
/**
 * Retrieves the services that are available for use with the description for each service. 
 * The Services are determined by looking up all of the implementations of the 
 * Customer Service interface that are using the  DataService qualifier annotation. 
 * The DataService annotation contains the service name and description information. 
 * @return Map containing a list of services available and a description of each one.
 */
public Map<String,String> getServices (){
    TreeMap<String,String> services = new TreeMap<String,String>();
    logger.fine("Getting CustomerService Impls");
    Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() {
        private static final long serialVersionUID = 1L;});
    for (Bean<?> bean : beans) {            
        for (Annotation qualifer: bean.getQualifiers()){
            if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
                DataService service = (DataService) qualifer;
                logger.fine("   name="+service.name()+" description="+service.description());
                services.put(service.name(), service.description());
            }
        }
    }       
    return services;
}
项目: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;
}
项目:cito    文件:BodyProducerExtension.java   
/**
 * 
 * @param ip
 * @param beanManager
 * @return
 */
private <T> Bean<T> createBeanAdapter(InjectionPoint ip, BeanManager beanManager) {
    final Type type = ip.getType();
    final Class<T> rawType = ReflectionUtils.getRawType(type);
    final ContextualLifecycle<T> lifecycleAdapter = new BodyLifecycle<T>(ip, beanManager);
    final BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager)
            .readFromType(new AnnotatedTypeBuilder<T>().readFromType(rawType).create())
            .beanClass(Body.class) // see https://issues.jboss.org/browse/WELD-2165
            .name(ip.getMember().getName())
            .qualifiers(ip.getQualifiers())
            .beanLifecycle(lifecycleAdapter)
            .scope(Dependent.class)
            .passivationCapable(false)
            .alternative(false)
            .nullable(true)
            .id("BodyBean#" + type.toString())
            .addType(type); //java.lang.Object needs to be present (as type) in any case
    return beanBuilder.create();
}
项目: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;
}
项目:ozark    文件:RedirectScopeManager.java   
/**
 * Perform the work we need to do at AfterProcessViewEvent time.
 *
 * @param event the event.
 */
public void afterProcessViewEvent(@Observes AfterProcessViewEvent event) {
    if (request.getAttribute(SCOPE_ID) != null) {
        String scopeId = (String) request.getAttribute(SCOPE_ID);
        HttpSession session = request.getSession();
        final String sessionKey = SCOPE_ID + "-" + scopeId;
        Map<String, Object> scopeMap = (Map<String, Object>) session.getAttribute(sessionKey);
        if (null != scopeMap) {
            scopeMap.entrySet().stream().forEach((entrySet) -> {
                String key = entrySet.getKey();
                Object value = entrySet.getValue();
                if (key.startsWith(INSTANCE)) {
                    BeanManager beanManager = CdiUtils.getApplicationBeanManager();
                    Bean<?> bean = beanManager.resolve(beanManager.getBeans(value.getClass()));
                    destroy(bean);
                }
            });
            scopeMap.clear();
            session.removeAttribute(sessionKey);
        }
    }
}
项目: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;
}
项目:property-inject    文件:PropertyProducerBeanTest.java   
@SuppressWarnings("unchecked")
private InjectionPoint mockInjectionPoint(Property property,
                                          Type type,
                                          Class<? extends Member> memberType,
                                          String memberName,
                                          int memberPosition) {
    InjectionPoint injectionPoint = mock(InjectionPoint.class);

    Member member = mock(memberType);
    when(injectionPoint.getType()).thenReturn(type);
    when(injectionPoint.getMember()).thenReturn(member);
    when(member.getName()).thenReturn(memberName);

    @SuppressWarnings("rawtypes")
    Bean mockBean = mock(Bean.class);
    when(injectionPoint.getBean()).thenReturn(mockBean);
    when(mockBean.getBeanClass()).thenReturn(getClass());

    AnnotatedParameter<?> annotated = mock(AnnotatedParameter.class);
    when(annotated.getPosition()).thenReturn(memberPosition);
    when(injectionPoint.getAnnotated()).thenReturn(annotated);

    when(annotated.getAnnotation(Property.class)).thenReturn(property);

    return injectionPoint;
}
项目:property-inject    文件:PropertyFactoryTest.java   
@SuppressWarnings("unchecked")
private InjectionPoint mockInjectionPoint(Property property,
                                          Class<? extends Member> memberType,
                                          String memberName,
                                          int memberPosition) {
    InjectionPoint injectionPoint = mock(InjectionPoint.class);

    Member member = mock(memberType);
    when(injectionPoint.getMember()).thenReturn(member);
    when(member.getName()).thenReturn(memberName);

    @SuppressWarnings("rawtypes")
    Bean mockBean = mock(Bean.class);
    when(injectionPoint.getBean()).thenReturn(mockBean);
    when(mockBean.getBeanClass()).thenReturn(getClass());

    AnnotatedParameter<?> annotated = mock(AnnotatedParameter.class);
    when(annotated.getPosition()).thenReturn(memberPosition);
    when(injectionPoint.getAnnotated()).thenReturn(annotated);

    when(annotated.getAnnotation(Property.class)).thenReturn(property);

    return injectionPoint;
}
项目:opendata-common    文件:MethodAdapter.java   
@Override
public void execute( JobExecutionContext context )
        throws JobExecutionException
{
    JobDetail d = context.getJobDetail();
    JobDataMap m = d.getJobDataMap();
    String name = m.getString( "bean" );
    Method meth = (Method) m.get( "method" );

    try {
        Bean<Object> bean = CDIUtils.getBean( name );
        Object job = CDIUtils.getInstance( (Bean<Object>) bean, Object.class );

        LOG.log( Level.INFO, () -> "job " + job );

        meth.invoke( job );
    }
    catch( IllegalAccessException |
           IllegalArgumentException |
           InvocationTargetException ex ) {
        LOG.log( Level.SEVERE, ex, () -> "Failed running " + name + " " + meth );
        throw new JobExecutionException( ex, false );
    }
}
项目:opendata-common    文件:JobAdapter.java   
@Override
public void execute( JobExecutionContext context )
        throws JobExecutionException
{
    JobDetail d = context.getJobDetail();
    JobDataMap m = d.getJobDataMap();
    String name = m.getString( "bean" );
    LOG.log( Level.INFO, () -> "name " + name );

    Bean<?> bean = CDIUtils.getBean( name );
    LOG.log( Level.INFO, () -> "bean " + bean );

    @SuppressWarnings( "unchecked" )
    Job job = CDIUtils.getInstance( (Bean<Job>) bean, Job.class );
    LOG.log( Level.INFO, () -> "job " + job );

    job.execute( context );
}
项目:wildfly-swarm    文件:MetricCdiInjectionExtension.java   
void registerMetrics(@Observes AfterDeploymentValidation adv, BeanManager manager) {

        // Produce and register custom metrics
        MetricRegistry registry = getReference(manager, MetricRegistry.class);
        MetricName name = getReference(manager, MetricName.class);
        for (Map.Entry<Bean<?>, AnnotatedMember<?>> bean : metrics.entrySet()) {
            if (// skip non @Default beans
            !bean.getKey().getQualifiers().contains(DEFAULT)
                    // skip producer methods with injection point metadata
                    || hasInjectionPointMetadata(bean.getValue())) {
                continue;
            }

            String metricName = name.of(bean.getValue());
            registry.register(metricName, getReference(manager, bean.getValue().getBaseType(), bean.getKey()));
        }

        // Let's clear the collected metric producers
        metrics.clear();
    }
项目:flowable-engine    文件:BusinessProcessContext.java   
@Override
public <T> T get(Contextual<T> contextual) {
    Bean<T> bean = (Bean<T>) contextual;
    String variableName = bean.getName();

    BusinessProcess businessProcess = getBusinessProcess();
    Object variable = businessProcess.getVariable(variableName);
    if (variable != null) {
        if (LOGGER.isDebugEnabled()) {
            if (businessProcess.isAssociated()) {
                LOGGER.debug("Getting instance of bean '{}' from Execution[{}]", variableName, businessProcess.getExecutionId());
            } else {
                LOGGER.debug("Getting instance of bean '{}' from transient bean store", variableName);
            }
        }

        return (T) variable;
    } else {
        return 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);
   }
项目:Camel    文件:XmlCdiBeanFactory.java   
private SyntheticBean<?> camelContextBean(Bean<?> context, AbstractCamelFactoryBean<?> factory, URL url) {
    if (factory instanceof BeanManagerAware) {
        ((BeanManagerAware) factory).setBeanManager(manager);
    }

    Set<Annotation> annotations = new HashSet<>();
    annotations.add(ANY);
    // FIXME: should add @ContextName if the Camel context bean has it
    annotations.add(hasId(factory) ? NamedLiteral.of(factory.getId()) : DEFAULT);

    // TODO: should that be @Singleton to enable injection points with bean instance type?
    if (factory.isSingleton()) {
        annotations.add(APPLICATION_SCOPED);
    }

    return new SyntheticBean<>(manager,
        new SyntheticAnnotated(factory.getObjectType(),
            manager.createAnnotatedType(factory.getObjectType()).getTypeClosure(),
            annotations),
        factory.getObjectType(),
        new XmlFactoryBeanInjectionTarget<>(manager, factory, context), bean ->
            "imported bean [" + factory.getId() + "] "
            + "from resource [" + url + "] "
            + "with qualifiers " + bean.getQualifiers());
}
项目:Camel    文件:XmlCdiBeanFactory.java   
private SyntheticBean<?> proxyFactoryBean(Bean<?> context, CamelProxyFactoryDefinition proxy, URL url) {
    if (isEmpty(proxy.getServiceRef()) && isEmpty(proxy.getServiceUrl())) {
        throw new CreationException(
            format("Missing [%s] or [%s] attribute for imported bean [%s] from resource [%s]",
                "serviceRef", "serviceUrl", proxy.getId(), url));
    }

    return new XmlProxyFactoryBean<>(manager,
        new SyntheticAnnotated(proxy.getServiceInterface(),
            manager.createAnnotatedType(proxy.getServiceInterface()).getTypeClosure(),
            APPLICATION_SCOPED, ANY, NamedLiteral.of(proxy.getId())),
        proxy.getServiceInterface(), bean ->
            "imported bean [" + proxy.getId() + "] "
            + "from resource [" + url + "] "
            + "with qualifiers " + bean.getQualifiers(),
        context, proxy);
}
项目:Camel    文件:ContextScanRouteBuilderFinder.java   
/**
 * Appends all the {@link org.apache.camel.builder.RouteBuilder} bean instances that can be found in the manager.
 */
void appendBuilders(List<RoutesBuilder> list) {
    for (Bean<?> bean : manager.getBeans(RoutesBuilder.class, ANY)) {
        logger.trace("Found RouteBuilder bean {}", bean);

        // certain beans should be ignored
        if (shouldIgnoreBean(bean)) {
            logger.debug("Ignoring RouteBuilder {}", bean);
            continue;
        }

        if (!isFilteredClass(bean)) {
            logger.debug("Ignoring filtered RouteBuilder {}", bean);
            continue;
        }

        logger.debug("Adding instantiated RouteBuilder {}", bean);
        Object instance = manager.getReference(bean, RoutesBuilder.class, manager.createCreationalContext(bean));
        list.add((RoutesBuilder) instance);
    }
}
项目:Camel    文件:CdiCamelExtension.java   
private boolean addRouteToContext(Bean<?> routeBean, Bean<?> contextBean, BeanManager manager, AfterDeploymentValidation adv) {
    try {
        CamelContext context = getReference(manager, CamelContext.class, contextBean);
        try {
            Object route = getReference(manager, Object.class, routeBean);
            if (route instanceof RoutesBuilder) {
                context.addRoutes((RoutesBuilder) route);
            } else if (route instanceof RouteContainer) {
                context.addRouteDefinitions(((RouteContainer) route).getRoutes());
            } else {
                throw new IllegalArgumentException(
                    "Invalid routes type [" + routeBean.getBeanClass().getName() + "], "
                        + "must be either of type RoutesBuilder or RouteContainer!");
            }
            return true;
        } catch (Exception cause) {
            adv.addDeploymentProblem(
                new InjectionException(
                    "Error adding routes of type [" + routeBean.getBeanClass().getName() + "] "
                        + "to Camel context [" + context.getName() + "]", cause));
        }
    } catch (Exception exception) {
        adv.addDeploymentProblem(exception);
    }
    return false;
}
项目: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;
}
项目:SecureBPMN    文件:BusinessProcessContext.java   
@Override
public <T> T get(Contextual<T> contextual) {
  Bean<T> bean = (Bean<T>) contextual;
  String variableName = bean.getName();

  BusinessProcess businessProcess = getBusinessProcess();
  Object variable = businessProcess.getVariable(variableName);
  if (variable != null) {

    if (logger.isLoggable(Level.FINE)) {
      if(businessProcess.isAssociated()) {        
        logger.fine("Getting instance of bean '" + variableName + "' from Execution[" + businessProcess.getExecutionId() + "].");
      } else {
        logger.fine("Getting instance of bean '" + variableName + "' from transient bean store");
      }
    }

    return (T) variable;
  } else {
    return null;
  }

}
项目:axon-cdi    文件:CdiParameterResolverFactory.java   
@Override
public ParameterResolver<Object> createInstance(final Executable executable, final Parameter[] parameters, final int parameterIndex) {
    Class<?> parameterType = parameters[parameterIndex].getType();
    Annotation[] annotations = parameters[parameterIndex].getAnnotations();
    Set<Annotation> qualifiers = CdiUtils.qualifiers(beanManager, annotations);
    Set<Bean<?>> beansFound = CdiUtils.getBeans(beanManager, parameterType, qualifiers);
    if (beansFound.isEmpty()) {
        return null;
    } else if (beansFound.size() > 1) {
        if (logger.isWarnEnabled()) {
            logger.warn("Ambiguous reference for parameter type {} with qualifiers {}",
                    parameterType.getName(), qualifiers);
        }
        return null;
    } else {
        return new CdiParameterResolver(beanManager, beansFound.iterator().next(), parameterType);
    }
}
项目: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;
    }
}
项目:switchyard    文件:BeanDeploymentMetaData.java   
/**
 * Lookup the BeanDeploymentMetaData for the current deployment.
 * @return The BeanDeploymentMetaData.
 */
public static BeanDeploymentMetaData lookupBeanDeploymentMetaData() {
    BeanManager beanManager = CDIUtil.lookupBeanManager();
    if (beanManager == null) {
        throw BeanMessages.MESSAGES.failedToLookupBeanManagerMustBeBoundIntoJavaCompAsPerCDISpecification();
    }

    Set<Bean<?>> beans = beanManager.getBeans(BeanDeploymentMetaData.class);
    if (beans.isEmpty()) {
        throw BeanMessages.MESSAGES.failedToLookupBeanDeploymentMetaDataFromBeanManagerMustBeBoundIntoBeanManagerPerhapsSwitchYardCDIExtensionsNotProperlyInstalledInContainer();
    }
    if (beans.size() > 1) {
        throw BeanMessages.MESSAGES.failedToLookupBeanDeploymentMetaDataFromBeanManagerMultipleBeansResolvedForType(BeanDeploymentMetaData.class.getName());
    }

    BeanDeploymentMetaDataCDIBean bean = (BeanDeploymentMetaDataCDIBean) beans.iterator().next();
    return bean.getBeanMetaData();
}
项目: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());
}
项目:axon-cdi    文件:AutoConfiguringEventStoreProducer.java   
private void registerEventHandlers(final X eventStore, final TokenStore tokenStore, Set<Annotation> qualifiers) {
    for (HandlerInfo eventHandlerInfo : eventHandlersInfo) {
        Bean<?> eventHandlerBean = CdiUtils.getBean(getBeanManager(), eventHandlerInfo.getType(), qualifiers);
        if (eventHandlerBean != null) {
            /**
            SubscribingEventProcessor subscribingEventProcessor = new SubscribingEventProcessor(eventHandlerBean.getName() + "SubscribingEventProcessor",
                    new SimpleEventHandlerInvoker(CdiUtils.getReference(getBeanManager(), eventHandlerBean, eventHandlerInfo.getType())),
                    eventStore);
            subscribingEventProcessor.start();
            */
            TrackingEventProcessor processor = new TrackingEventProcessor(eventHandlerBean.getName() + "Tracking",
                    new SimpleEventHandlerInvoker(CdiUtils.getReference(getBeanManager(), eventHandlerBean, eventHandlerInfo.getType())),
                    eventStore,
                    tokenStore,
                    NoTransactionManager.instance());
            processor.start();
        }
    }
}
项目:osgi.ee    文件:ServiceExtension.java   
/**
 * Process a bean. Checks the bean for @Service annotation and if it is found, verifies
 * the bean scope and marks it for export as service at a later stage.
 *
 * @param event The process bean event. See CDI specification
 * @param <T> The type of the bean
 */
public <T> void processBean(@Observes ProcessBean<T> event) {
    Bean<T> bean = event.getBean();
    Service service = BeanExporter.getServiceDefinition(bean);
    if (service == null) {
        return;
    }
    // Check the scope. Must be global.
    Class<? extends Annotation> scope = bean.getScope();
    if (!scope.equals(ComponentScoped.class) && !scope.equals(ApplicationScoped.class)) {
        // Set an error.
        event.addDefinitionError(new Exception("beans annotated with @Service must have a global scope"));
        return;
    }
    // Mark the bean as exportable.
    exportedBeans.put(bean, null);
}
项目:testee.fi    文件:InjectionPointUtils.java   
@SuppressWarnings("unchecked")
public static <T> FieldInjectionPoint<Object, T> injectionPointOf(
        final Field field,
        final Bean<T> bean,
        final BeanManagerImpl beanManager
) {
    final EnhancedAnnotatedType<T> type = beanManager.createEnhancedAnnotatedType((Class<T>) bean.getBeanClass());
    final Collection<EnhancedAnnotatedField<?, ? super T>> enhancedFields = type.getEnhancedFields();
    final EnhancedAnnotatedField<Object, T> eaf = (EnhancedAnnotatedField<Object, T>) enhancedFields.stream()
            .filter(it -> field.equals(it.getJavaMember()))
            .findFirst()
            .orElseThrow(() -> new TestEEfiException("Failed to get enhanced annotated field for " + field));
    return InjectionPointFactory.instance()
            .createFieldInjectionPoint(eaf, bean, bean.getBeanClass(), beanManager);
}
项目:testee.fi    文件:DependencyInjectionRealm.java   
@SuppressWarnings("unchecked")
private <T> Set<Bean<T>> beansOf(
        final Class<T> clazz,
        final BeanManagerImpl beanManager
) {
    return beanManager.getBeans(clazz).stream()
            .map(bean -> (Bean<T>) bean)
            .collect(toSet());
}
项目:testee.fi    文件:DependencyInjectionRealm.java   
@SuppressWarnings("unchecked")
private void withProducer(final Object o, final BiConsumer<Bean, InjectionTarget> consumer) {
    final Bean<Object> bean = resolveUnique((Class<Object>) o.getClass());
    if (!(bean instanceof AbstractClassBean)) {
        throw new TestEEfiException("Injection of " + bean + " is not supported");
    }
    consumer.accept(bean, ((AbstractClassBean) bean).getProducer());
}