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

项目: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());
}
项目: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
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:InjectSPITestCase.java   
@SuppressWarnings("unchecked")
private <X, A extends AnnotatedMember<? super X>> A getAnnotatedMember(Class<X> javaClass, String memberName,
        BeanManager beanManager) {
    AnnotatedType<X> type = beanManager.createAnnotatedType(javaClass);
    for (AnnotatedField<? super X> field : type.getFields()) {
        if (field.getJavaMember().getName().equals(memberName)) {
            return (A) field;
        }
    }
    for (AnnotatedMethod<? super X> method : type.getMethods()) {
        if (method.getJavaMember().getName().equals(memberName)) {
            return (A) method;
        }
    }
    throw new IllegalArgumentException("Member " + memberName + " not found on " + javaClass);
}
项目: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;
}
项目:wildfly-microprofile-config    文件:ConfigExtension.java   
public void registerConfigProducer(@Observes AfterBeanDiscovery abd, BeanManager bm) {
    // excludes type that are already produced by ConfigProducer
    Set<Class> types = injectionPoints.stream()
            .filter(ip -> ip.getType() instanceof Class
                    && ip.getType() != String.class
                    && ip.getType() != Boolean.class
                    && ip.getType() != Boolean.TYPE
                    && ip.getType() != Integer.class
                    && ip.getType() != Integer.TYPE
                    && ip.getType() != Long.class
                    && ip.getType() != Long.TYPE
                    && ip.getType() != Float.class
                    && ip.getType() != Float.TYPE
                    && ip.getType() != Double.class
                    && ip.getType() != Double.TYPE
                    && ip.getType() != Duration.class
                    && ip.getType() != LocalDate.class
                    && ip.getType() != LocalTime.class
                    && ip.getType() != LocalDateTime.class)
            .map(ip -> (Class) ip.getType())
            .collect(Collectors.toSet());
    types.forEach(type -> abd.addBean(new ConfigInjectionBean(bm, type)));
}
项目:wildfly-microprofile-config    文件:ConfigExtension.java   
public void validate(@Observes AfterDeploymentValidation add, BeanManager bm) {
    List<String> deploymentProblems = new ArrayList<>();

    Config config = ConfigProvider.getConfig();
    for (InjectionPoint injectionPoint : injectionPoints) {
        Type type = injectionPoint.getType();
        ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class);
        if (type instanceof Class) {
            String key = getConfigKey(injectionPoint, configProperty);

            if (!config.getOptionalValue(key, (Class)type).isPresent()) {
                String defaultValue = configProperty.defaultValue();
                if (defaultValue == null ||
                        defaultValue.equals(ConfigProperty.UNCONFIGURED_VALUE)) {
                    deploymentProblems.add("No Config Value exists for " + key);
                }
            }
        }
    }

    if (!deploymentProblems.isEmpty()) {
        add.addDeploymentProblem(new DeploymentException("Error while validating Configuration\n"
                + String.join("\n", deploymentProblems)));
    }

}
项目: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();
}
项目:wildfly-nosql    文件:CassandraExtension.java   
/**
 */
void registerNoSQLSourceBeans(@Observes AfterBeanDiscovery abd, BeanManager bm) {

    if (bm.getBeans(clusterClass, DefaultLiteral.INSTANCE).isEmpty()) {
        // Iterate profiles and create Cluster/Session bean for each profile, that application code can @Inject
        for(String profile: getService().profileNames()) {
            log.log(Level.INFO, "Registering bean for profile {0}", profile);
            abd.addBean(bm.createBean(
                    new ClusterBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(clusterClass)), profile),
                    clusterClass, new ClusterProducerFactory(profile, clusterClass)));
            abd.addBean(bm.createBean(
                    new SessionBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(sessionClass)), profile),
                    sessionClass, new SessionProducerFactory(profile, sessionClass)));
        }
     } else {
        log.log(Level.INFO, "Application contains a default Cluster Bean, automatic registration will be disabled");
    }
}
项目:wildfly-nosql    文件:MongoExtension.java   
void registerNoSQLSourceBeans(@Observes AfterBeanDiscovery abd, BeanManager bm) {
    if (bm.getBeans(mongoClientClass, DefaultLiteral.INSTANCE).isEmpty()) {
        // Iterate profiles and create Cluster/Session bean for each profile, that application code can @Inject
        for(String profile: getService().profileNames()) {
            log.log(Level.INFO, "Registering bean for profile {0}", profile);
            abd.addBean(bm.createBean(
                    new MongoClientBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(mongoClientClass)), profile),
                    mongoClientClass, new MongoClientProducerFactory(profile, mongoClientClass)));
            abd.addBean(bm.createBean(
                    new MongoDatabaseBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(mongoDatabaseClass)), profile),
                    mongoDatabaseClass, new MongoDatabaseProducerFactory(profile, mongoDatabaseClass)));
        }
     } else {
        log.log(Level.INFO, "Application contains a default MongoClient Bean, automatic registration will be disabled");
    }
}
项目: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;
}
项目: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;
}
项目:command-context-example    文件:CommandExtension.java   
void afterBeanDiscovery(@Observes AfterBeanDiscovery event, BeanManager beanManager) {

        final CommandContextImpl commandContext = new CommandContextImpl();

        // Register the command context
        event.addContext(commandContext);

        // Register the command context bean using CDI 2 configurators API
        event.addBean()
            .addType(CommandContext.class)
            .createWith(ctx -> new InjectableCommandContext(commandContext, beanManager))
            .addQualifier(Default.Literal.INSTANCE)
            .scope(Dependent.class)
            .beanClass(CommandExtension.class);

        // Register the CommandExecution bean using CDI 2 configurators API
        event.addBean()
            .createWith(ctx -> commandContext.getCurrentCommandExecution())
            .addType(CommandExecution.class)
            .addQualifier(Default.Literal.INSTANCE)
            .scope(CommandScoped.class)
            .beanClass(CommandExtension.class);
    }
项目: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);
        }
    }
}
项目:ozark    文件:CdiUtilsTest.java   
/**
 * Test newBean method.
 *
 * @throws Exception when a serious error occurs.
 */
@Test
public void testNewBean() throws Exception {
    CdiUtils utils = new CdiUtils();

    Field bmField = utils.getClass().getDeclaredField("beanManager");
    bmField.setAccessible(true);
    BeanManager bm = EasyMock.createMock(BeanManager.class);
    bmField.set(utils, bm);

    expect(bm.getBeans(CdiUtilsTest.class)).andReturn(null);
    expect(bm.resolve(null)).andReturn(null);
    expect(bm.createCreationalContext(null)).andReturn(null);
    expect(bm.getReference(null, CdiUtilsTest.class, null)).andReturn(null);
    replay(bm);
    assertNull(utils.newBean(CdiUtilsTest.class));
    verify(bm);
}
项目:maven-cdi-plugin-utils    文件:AbstractCDIMojo.java   
@SuppressWarnings("unused")
 // will be called automatically by the CDI container once the bean discovery has finished
 private void processMojoCdiProducerFields(@Observes AfterBeanDiscovery event, BeanManager beanManager)
     throws MojoExecutionException {

Class<?> cls = getClass();
   Set<Field> fields = Sets.newHashSet();

   while (cls != AbstractCDIMojo.class) {
    fields.addAll(Sets.newHashSet(cls.getFields()));
    fields.addAll(Sets.newHashSet(cls.getDeclaredFields()));
    cls = cls.getSuperclass();
   }

   for (Field f : fields) {
     if (f.isAnnotationPresent(MojoProduces.class)) {
       try {
         f.setAccessible(true);
         event.addBean(
             new CdiBeanWrapper<Object>(f.get(this), f.getGenericType(), f.getType(), CDIUtil.getCdiQualifiers(f)));
       } catch (Throwable t) {
         throw new MojoExecutionException("Could not process CDI producer field of the Mojo.", t);
       }
     }
   }
 }
项目:weld-vertx    文件:AsyncReferenceImpl.java   
@Inject
public AsyncReferenceImpl(InjectionPoint injectionPoint, Vertx vertx, BeanManager beanManager, @Any WeldInstance<Object> instance) {
    this.isDone = new AtomicBoolean(false);
    this.future = new VertxCompletableFuture<>(vertx);
    this.instance = instance;

    ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType();
    Type requiredType = parameterizedType.getActualTypeArguments()[0];
    Annotation[] qualifiers = injectionPoint.getQualifiers().toArray(new Annotation[] {});

    // First check if there is a relevant async producer method available
    WeldInstance<Object> completionStage = instance.select(new ParameterizedTypeImpl(CompletionStage.class, requiredType), qualifiers);

    if (completionStage.isAmbiguous()) {
        failure(new AmbiguousResolutionException(
                "Ambiguous async producer methods for type " + requiredType + " with qualifiers " + injectionPoint.getQualifiers()));
    } else if (!completionStage.isUnsatisfied()) {
        // Use the produced CompletionStage
        initWithCompletionStage(completionStage.getHandler());
    } else {
        // Use Vertx worker thread
        initWithWorker(requiredType, qualifiers, vertx, beanManager);
    }
}
项目:opendata-common    文件:SchedulerExtension.java   
<T> void findJobs( @Observes @WithAnnotations({Cron.class}) ProcessAnnotatedType<T> pat, BeanManager beanManager )
{
    // Ensure we are named otherwise job won't fire as we can't locate it
    AnnotatedType<?> type = pat.getAnnotatedType();
    Class<?> clazz = type.getJavaClass();
    CDIUtils.addTypeAnnotation( pat, Named.class, () -> new NamedImpl( "Schedule_" + (id++) ) );

    if( type.isAnnotationPresent( Cron.class ) ) {
        if( Job.class.isAssignableFrom( clazz ) ) {
            jobClasses.add( clazz );
        }
        else {
            throw new UnsupportedOperationException( "@Cron on type must implement Job" );
        }
    }
    else {
        for( AnnotatedMethod<?> meth: type.getMethods() ) {
            if( meth.isAnnotationPresent( Cron.class ) ) {
                jobClasses.add( clazz );
            }
        }
    }
}
项目: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();
    }
项目:yasson    文件:JsonbComponentInstanceCreatorFactory.java   
/**
 * First check a CDI provider, if available use those.
 * Try to lookup in a JNDI if no provider is registered.
 * If one of the above is found {@link BeanManagerInstanceCreator} is returned,
 * or {@link DefaultConstructorCreator} otherwise.
 * @return Component instance creator, either CDI or default constructor.
 */
public static JsonbComponentInstanceCreator getComponentInstanceCreator() {
    try {
        return new BeanManagerInstanceCreator(CDI.current().getBeanManager());
    } catch (Throwable e) {
        log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_NO_PROVIDER));
        try {
            InitialContext context = new InitialContext();
            final BeanManager lookup = (BeanManager) context.lookup(BEAN_MANAGER_NAME);
            return new BeanManagerInstanceCreator(lookup);
        } catch (NamingException e1) {
            log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_JNDI, BEAN_MANAGER_NAME, e1.getExplanation()));
        }
    }
    log.finest(Messages.getMessage(MessageKeys.BEAN_MANAGER_NOT_FOUND_USING_DEFAULT));
    return new DefaultConstructorCreator();
}
项目:wildfly-swarm    文件:HystrixCommandInterceptor.java   
@SuppressWarnings("unchecked")
@Inject
public HystrixCommandInterceptor(@ConfigProperty(name = "MP_Fault_Tolerance_NonFallback_Enabled", defaultValue = "true") Boolean nonFallBackEnable,  @ConfigProperty(name = SYNC_CIRCUIT_BREAKER_KEY, defaultValue = "true") Boolean syncCircuitBreakerEnabled, BeanManager beanManager) {
    this.nonFallBackEnable = nonFallBackEnable;
    this.syncCircuitBreakerEnabled = syncCircuitBreakerEnabled;
    this.beanManager = beanManager;
    this.extension = beanManager.getExtension(HystrixExtension.class);
    this.commandMetadataMap = new ConcurrentHashMap<>();
    // WORKAROUND: Hystrix does not allow to use custom HystrixCircuitBreaker impl
    // See also https://github.com/Netflix/Hystrix/issues/9
    try {
        Field field = SecurityActions.getDeclaredField(com.netflix.hystrix.HystrixCircuitBreaker.Factory.class, "circuitBreakersByCommand");
        SecurityActions.setAccessible(field);
        this.circuitBreakers = (ConcurrentHashMap<String, HystrixCircuitBreaker>) field.get(null);
    } catch (Exception e) {
        throw new IllegalStateException("Could not obtain reference to com.netflix.hystrix.HystrixCircuitBreaker.Factory.circuitBreakersByCommand");
    }
}
项目:drinkwater-java    文件:Main.java   
public ServiceRepository getDrinkWaterApplication() {
    BeanManager mgr = cdiContainer.getBeanManager();
    ServiceRepository dwapp =
            (ServiceRepository) mgr.getReference(
                    mgr.resolve(mgr.getBeans(DrinkWaterApplication.class)),
                    DrinkWaterApplication.class,
                    mgr.createCreationalContext(null)
            );

    return dwapp;

}
项目:aries-jpa    文件:JpaExtension.java   
public <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> event, BeanManager manager) {
    boolean hasPersistenceField = false;
    for (AnnotatedField<? super T> field : event.getAnnotatedType().getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)
                || field.isAnnotationPresent(PersistenceUnit.class)) {
            hasPersistenceField = true;
            break;
        }
    }
    if (hasPersistenceField) {
        PersistenceAnnotatedType<T> pat = new PersistenceAnnotatedType<T>(manager, event.getAnnotatedType());
        beans.addAll(pat.getProducers());
        event.setAnnotatedType(pat);
    }
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
public PersistenceAnnotatedType(BeanManager manager, AnnotatedType<T> delegate) {
    super(delegate);
    this.manager = manager;
    this.fields = new HashSet<>();
    for (AnnotatedField<? super T> field : delegate.getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)) {
            field = decorateContext(field);
        } else if (field.isAnnotationPresent(PersistenceUnit.class)) {
            field = decorateUnit(field);
        }
        this.fields.add(field);
    }
}
项目:redpipe    文件:CdiPlugin.java   
@Override
public Single<Void> init() {
    // Setup the Vertx-CDI integration
    VertxExtension vertxExtension = CDI.current().select(VertxExtension.class).get();
    BeanManager beanManager = CDI.current().getBeanManager();
    // has to be done in a blocking thread
    Vertx vertx = AppGlobals.get().getVertx();
    return vertx.rxExecuteBlocking(future -> {
        vertxExtension.registerConsumers(vertx.getDelegate(), BeanManagerProxy.unwrap(beanManager).event());
        future.complete();
    });
}
项目:crnk-framework    文件:CdiServiceDiscovery.java   
public BeanManager getBeanManager() {
    if (beanManager != null) {
        return beanManager;
    }
    else {
        return CDI.current().getBeanManager();
    }
}
项目:crnk-framework    文件:CdiServiceDiscoveryTest.java   
@Test
public void testSetter() {
    CdiServiceDiscovery discovery = new CdiServiceDiscovery();

    BeanManager beanManager = discovery.getBeanManager();
    Assert.assertNotNull(discovery.getBeanManager());

    BeanManager mock = Mockito.mock(BeanManager.class);
    discovery.setBeanManager(mock);
    Assert.assertSame(mock, discovery.getBeanManager());
    Assert.assertNotSame(mock, beanManager);
}
项目:weld-junit    文件:WeldJunit5Extension.java   
private List<Annotation> resolveQualifiers(ParameterContext pc, BeanManager bm) {
    List<Annotation> qualifiers = new ArrayList<>();
    if (pc.getParameter().getAnnotations().length == 0) {
        return Collections.emptyList();
    } else {
        for (Annotation annotation : pc.getParameter().getAnnotations()) {
            // use BeanManager.isQualifier to be able to detect custom qualifiers which don't need to have @Qualifier
            if (bm.isQualifier(annotation.annotationType())) {
                qualifiers.add(annotation);
            }
        }
    }
    return qualifiers;
}
项目:weld-junit    文件:AbstractWeldInitiator.java   
void inject() {
    BeanManager beanManager = container.getBeanManager();
    CreationalContext<Object> ctx = beanManager.createCreationalContext(null);
    @SuppressWarnings("unchecked")
    InjectionTarget<Object> injectionTarget = (InjectionTarget<Object>) beanManager
            .getInjectionTargetFactory(beanManager.createAnnotatedType(instance.getClass())).createInjectionTarget(null);
    injectionTarget.inject(instance, ctx);
    creationalContext = ctx;
}
项目:spring-data-snowdrop    文件:SnowdropRepositoryExtension.java   
private <T> CdiRepositoryBean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {
    Bean<DatasourceMapper> dsBean = dsMap.get(qualifiers);
    if (dsBean == null) {
        throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", DatasourceMapper.class.getName(), qualifiers));
    }

    return new SnowdropRepositoryBean<>(dsBean, qualifiers, repositoryType, beanManager, getCustomImplementationDetector());
}
项目:wildfly-microprofile-health    文件:CDIExtension.java   
/**
 * Instantiates <em>unmanaged instances</em> of HealthCheckProcedure and
 * handle manually their CDI creation lifecycle.
 * Add them to the {@link HealthMonitor}.
 */
private void afterDeploymentValidation(@Observes final AfterDeploymentValidation avd, BeanManager bm) {
   for (AnnotatedType delegate : delegates) {
      try {
         Unmanaged<HealthCheck> unmanagedHealthCheck = new Unmanaged<HealthCheck>(bm, delegate.getJavaClass());
         UnmanagedInstance<HealthCheck> healthCheckInstance = unmanagedHealthCheck.newInstance();
         HealthCheck healthCheck =  healthCheckInstance.produce().inject().postConstruct().get();
         healthChecks.add(healthCheck);
         healthCheckInstances.add(healthCheckInstance);
         healthMonitor.addHealthCheck(healthCheck);
      } catch (Exception e) {
         throw new RuntimeException("Failed to register health bean", e);
      }
   }
}
项目:mid-tier    文件:AbstractAuditable.java   
private BeanManager getBeanManager() {
    try {
        InitialContext ctx = new InitialContext();
        return (BeanManager) ctx.lookup("java:comp/BeanManager");
    } catch (NamingException e) {
        throw new RuntimeException("Unable to lookup CDI bean manager", e);
    }
}
项目:Camel    文件:CamelCdiRunner.java   
@Override
protected Object createTest() {
    BeanManager manager = context.getBeanManager();
    Set<Bean<?>> beans = manager.getBeans(getTestClass().getJavaClass(), AnyLiteral.INSTANCE);
    Bean<?> bean = beans.iterator().next();
    // TODO: manage lifecycle of @Dependent beans
    return manager.getReference(bean, bean.getBeanClass(), manager.createCreationalContext(bean));
}
项目:wildfly-nosql    文件:Neo4jExtension.java   
void registerNoSQLSourceBeans(@Observes AfterBeanDiscovery abd, BeanManager bm) {
        if (bm.getBeans(driverClass, DefaultLiteral.INSTANCE).isEmpty()) {
            for(String profile: getService().profileNames()) {
                log.log(Level.INFO, "Registering bean for profile {0}", profile);
                abd.addBean(bm.createBean(
                        new DriverBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(driverClass)), profile),
                        driverClass, new DriverProducerFactory(profile, driverClass)));
//                TODO: uncomment or delete the following.
//                abd.addBean(bm.createBean(new SessionBeanAttributes(bm.createBeanAttributes(bm.createAnnotatedType(Session.class)),profile),
//                        Session.class, new SessionProducerFactory(profile)));
            }
         } else {
            log.log(Level.INFO, "Application contains a default Driver Bean, automatic registration will be disabled");
        }
    }
项目:parco    文件:BeanStartupHelper.java   
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onStartup(@Observes @Initialized WebApplication webApplication, BeanManager beanManager)
   {

    for( Bean bean : beanManager.getBeans(Startup.class) )
    {
        CreationalContext context = beanManager.createCreationalContext(bean);
        Startup st = (Startup) beanManager.getReference(bean, Startup.class, context);
        st.init();
    }
   }
项目:drinkwater-java    文件:Main.java   
public ServiceRepository getDrinkWaterApplication() {
    BeanManager mgr = cdiContainer.getBeanManager();
    ServiceRepository dwapp =
            (ServiceRepository) mgr.getReference(
                    mgr.resolve(mgr.getBeans(DrinkWaterApplication.class)),
                    DrinkWaterApplication.class,
                    mgr.createCreationalContext(null)
            );

    return dwapp;

}
项目:hibernate-json    文件:CdiDriverLocator.java   
@Override
public JsonDriver locate(Annotation[] fieldAnnotations, Optional<String> name) {
    final BeanManager bm = CDI.current().getBeanManager();        
    final Annotation[] qualifiers = Arrays.stream(fieldAnnotations).filter(a -> searchAnnotation(a, Qualifier.class).isPresent()).toArray(n -> new Annotation[n]);
    JsonDriverNotFound.failIf(qualifiers.length > 0 && name.isPresent(), "found both @Qualifiers and @WithDriver.value()");
    final Set<Bean<?>> beans = name.map(n -> bm.getBeans(n)).orElseGet(() -> bm.getBeans(JsonDriver.class, qualifiers));
    JsonDriverNotFound.failIf(beans.isEmpty(), "no JsonDriver found in BeanManager");
    JsonDriverNotFound.failIf(beans.size() > 1, "more than one JsonDriver found in BeanManager, use @JsonType.WithDriver to disambiguate");
    final Bean<?> bean = beans.iterator().next();
    final CreationalContext<?> ctx = bm.createCreationalContext(bean);
    return (JsonDriver) bm.getReference(bean, JsonDriver.class, ctx);           
}
项目:ozark    文件:CdiUtils.java   
/**
 * Returns a list of CDI beans with the specified bean type and qualifiers.
 * Please note that this method supports looking up beans deployed with the application
 * even if Ozark is deployed as a container archive.
 */
public static <T> List<T> getApplicationBeans(Class<T> type, Annotation... qualifiers) {
    BeanManager manager = getApplicationBeanManager();
    return manager.getBeans(type, qualifiers).stream()
            .map(bean -> (T) manager.getReference(bean, type, manager.createCreationalContext(bean)))
            .collect(Collectors.toList());
}
项目:kumuluzee-examples    文件:EagerExtension.java   
/**
 * <p>Initializes all beans found and saved in the {@link #collect(ProcessBean) collect} method. This enables eager loading of annotated beans on application (CDI) startup.</p>
 *
 * @param event CDI event that is triggered after CDI deployment. When this is triggered, the eager beans are instantiate.
 * @param beanManager The CDI bean manager that contains and manages all CDI beans.
 */
public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) {

    for (Bean<?> bean : eagerBeansList) {
        // note: toString() is important to instantiate the bean
        beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString();
    }
}
项目:katharsis-framework    文件:CdiServiceDiscovery.java   
@SuppressWarnings("unchecked")
@Override
public <T> List<T> getInstancesByType(Class<T> clazz) {
    BeanManager beanManager = CDI.current().getBeanManager();
    Set<Bean<?>> beans = beanManager.getBeans(clazz);
    List<T> list = new ArrayList<>();
    for (Bean<?> bean : beans) {
        CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);
        T object = (T) beanManager.getReference(bean, clazz, creationalContext);
        list.add(object);
    }
    return list;
}