Java Code Examples for javax.enterprise.inject.spi.BeanManager

The following are top voted examples for showing how to use javax.enterprise.inject.spi.BeanManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: Mastering-Java-EE-Development-with-WildFly   File: InjectSPITestCase.java   View source code 6 votes vote down vote up
@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());
}
 
Example 2
Project: Mastering-Java-EE-Development-with-WildFly   File: InjectSPITestCase.java   View source code 6 votes vote down vote up
@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
}
 
Example 3
Project: Mastering-Java-EE-Development-with-WildFly   File: InjectSPITestCase.java   View source code 6 votes vote down vote up
@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);
}
 
Example 4
Project: crnk-framework   File: CdiServiceDiscovery.java   View source code 6 votes vote down vote up
@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;
}
 
Example 5
Project: crnk-framework   File: CdiServiceDiscovery.java   View source code 6 votes vote down vote up
@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;
}
 
Example 6
Project: wildfly-microprofile-config   File: ConfigExtension.java   View source code 6 votes vote down vote up
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)));
}
 
Example 7
Project: wildfly-microprofile-config   File: ConfigExtension.java   View source code 6 votes vote down vote up
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)));
    }

}
 
Example 8
Project: mid-tier   File: AbstractAuditable.java   View source code 6 votes vote down vote up
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);
    }
}
 
Example 9
Project: cito   File: BodyProducerExtension.java   View source code 6 votes vote down vote up
/**
 * 
 * @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();
}
 
Example 10
Project: wildfly-nosql   File: CassandraExtension.java   View source code 6 votes vote down vote up
/**
 */
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");
    }
}
 
Example 11
Project: wildfly-nosql   File: MongoExtension.java   View source code 6 votes vote down vote up
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");
    }
}
 
Example 12
Project: webpedidos   File: CDIServiceLocator.java   View source code 6 votes vote down vote up
@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;
}
 
Example 13
Project: Camel   File: CdiCamelExtension.java   View source code 6 votes vote down vote up
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;
}
 
Example 14
Project: command-context-example   File: CommandExtension.java   View source code 6 votes vote down vote up
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);
    }
 
Example 15
Project: ozark   File: RedirectScopeManager.java   View source code 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example 16
Project: ozark   File: CdiUtilsTest.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 17
Project: maven-cdi-plugin-utils   File: AbstractCDIMojo.java   View source code 6 votes vote down vote up
@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);
       }
     }
   }
 }
 
Example 18
Project: weld-vertx   File: AsyncReferenceImpl.java   View source code 6 votes vote down vote up
@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);
    }
}
 
Example 19
Project: opendata-common   File: SchedulerExtension.java   View source code 6 votes vote down vote up
<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 );
            }
        }
    }
}
 
Example 20
Project: wildfly-swarm   File: MetricCdiInjectionExtension.java   View source code 6 votes vote down vote up
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();
    }
 
Example 21
Project: yasson   File: JsonbComponentInstanceCreatorFactory.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 22
Project: wildfly-swarm   File: HystrixCommandInterceptor.java   View source code 6 votes vote down vote up
@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");
    }
}
 
Example 23
Project: drinkwater-java   File: Main.java   View source code 5 votes vote down vote up
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;

}
 
Example 24
Project: aries-jpa   File: JpaExtension.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 25
Project: aries-jpa   File: PersistenceAnnotatedType.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 26
Project: redpipe   File: CdiPlugin.java   View source code 5 votes vote down vote up
@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();
	});
}
 
Example 27
Project: crnk-framework   File: CdiServiceDiscovery.java   View source code 5 votes vote down vote up
public BeanManager getBeanManager() {
	if (beanManager != null) {
		return beanManager;
	}
	else {
		return CDI.current().getBeanManager();
	}
}
 
Example 28
Project: crnk-framework   File: CdiServiceDiscoveryTest.java   View source code 5 votes vote down vote up
@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);
}
 
Example 29
Project: weld-junit   File: WeldJunit5Extension.java   View source code 5 votes vote down vote up
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;
}
 
Example 30
Project: weld-junit   File: AbstractWeldInitiator.java   View source code 5 votes vote down vote up
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;
}
 
Example 31
Project: spring-data-snowdrop   File: SnowdropRepositoryExtension.java   View source code 5 votes vote down vote up
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());
}
 
Example 32
Project: wildfly-microprofile-health   File: CDIExtension.java   View source code 5 votes vote down vote up
/**
 * 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);
      }
   }
}
 
Example 33
Project: Camel   File: CamelCdiRunner.java   View source code 5 votes vote down vote up
@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));
}
 
Example 34
Project: wildfly-nosql   File: Neo4jExtension.java   View source code 5 votes vote down vote up
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");
        }
    }
 
Example 35
Project: parco   File: BeanStartupHelper.java   View source code 5 votes vote down vote up
@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();
   	}
   }
 
Example 36
Project: drinkwater-java   File: Main.java   View source code 5 votes vote down vote up
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;

}
 
Example 37
Project: hibernate-json   File: CdiDriverLocator.java   View source code 5 votes vote down vote up
@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);	        
}
 
Example 38
Project: ozark   File: CdiUtils.java   View source code 5 votes vote down vote up
/**
 * 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());
}
 
Example 39
Project: kumuluzee-examples   File: EagerExtension.java   View source code 5 votes vote down vote up
/**
 * <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();
    }
}
 
Example 40
Project: katharsis-framework   File: CdiServiceDiscovery.java   View source code 5 votes vote down vote up
@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;
}