javax.enterprise.inject.spi.AfterBeanDiscovery Java Examples

The following examples show how to use javax.enterprise.inject.spi.AfterBeanDiscovery. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommandLineArgsExtension.java    From thorntail with Apache License 2.0 6 votes vote down vote up
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) {
    CommonBean<String[]> stringBean = CommonBeanBuilder.newBuilder(String[].class)
            .beanClass(CommandLineArgsExtension.class)
            .scope(Dependent.class)
            .createSupplier(() -> args)
            .addQualifier(CommandLineArgs.Literal.INSTANCE)
            .addType(String[].class)
            .addType(Object.class).build();
    abd.addBean(stringBean);
    CommonBean<List> listBean = CommonBeanBuilder.newBuilder(List.class)
            .beanClass(CommandLineArgsExtension.class)
            .scope(Dependent.class)
            .createSupplier(() -> argsList)
            .addQualifier(Default.Literal.INSTANCE)
            .addType(List.class)
            .addType(Object.class).build();
    abd.addBean(listBean);
}
 
Example #2
Source File: ExtraJCacheExtension.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
public void addJCacheBeans(final @Observes AfterBeanDiscovery afterBeanDiscovery)
{
    if (!ACTIVATED)
    {
        return;
    }

    if (cacheManagerFound && cacheProviderFound) {
        return;
    }

    cachingProvider = Caching.getCachingProvider();
    if (!cacheManagerFound)
    {
        cacheManager = cachingProvider.getCacheManager(
                cachingProvider.getDefaultURI(),
                cachingProvider.getDefaultClassLoader(),
                new Properties());
        afterBeanDiscovery.addBean(new CacheManagerBean(cacheManager));
    }
    if (!cacheProviderFound)
    {
        afterBeanDiscovery.addBean(new CacheProviderBean(cachingProvider));
    }
}
 
Example #3
Source File: MakeJCacheCDIInterceptorFriendly.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
protected void addHelper(final @Observes AfterBeanDiscovery afterBeanDiscovery,
                         final BeanManager bm)
{
    if (!needHelper) {
        return;
    }
    /* CDI >= 1.1 only. Actually we shouldn't go here with CDI 1.1 since we defined the annotated type for the helper
    final AnnotatedType<CDIJCacheHelper> annotatedType = bm.createAnnotatedType(CDIJCacheHelper.class);
    final BeanAttributes<CDIJCacheHelper> beanAttributes = bm.createBeanAttributes(annotatedType);
    final InjectionTarget<CDIJCacheHelper> injectionTarget = bm.createInjectionTarget(annotatedType);
    final Bean<CDIJCacheHelper> bean = bm.createBean(beanAttributes, CDIJCacheHelper.class, new InjectionTargetFactory<CDIJCacheHelper>() {
        @Override
        public InjectionTarget<CDIJCacheHelper> createInjectionTarget(Bean<CDIJCacheHelper> bean) {
            return injectionTarget;
        }
    });
    */
    final AnnotatedType<CDIJCacheHelper> annotatedType = bm.createAnnotatedType(CDIJCacheHelper.class);
    final InjectionTarget<CDIJCacheHelper> injectionTarget = bm.createInjectionTarget(annotatedType);
    final HelperBean bean = new HelperBean(annotatedType, injectionTarget, findIdSuffix());
    afterBeanDiscovery.addBean(bean);
}
 
Example #4
Source File: ExtraJCacheExtension.java    From jcache-cdi with Apache License 2.0 6 votes vote down vote up
public void addJCacheBeans(final @Observes AfterBeanDiscovery afterBeanDiscovery)
{
    if (!ACTIVATED)
    {
        return;
    }

    if (cacheManagerFound && cacheProviderFound) {
        return;
    }

    cachingProvider = Caching.getCachingProvider();
    if (!cacheManagerFound)
    {
        cacheManager = cachingProvider.getCacheManager(
                cachingProvider.getDefaultURI(),
                cachingProvider.getDefaultClassLoader(),
                new Properties());
        afterBeanDiscovery.addBean(new CacheManagerBean(cacheManager));
    }
    if (!cacheProviderFound)
    {
        afterBeanDiscovery.addBean(new CacheProviderBean(cachingProvider));
    }
}
 
Example #5
Source File: ConverterAndValidatorProxyExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public <X> void createBeans(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (!this.isActivated)
    {
        return;
    }

    for (Class<?> originalClass : this.classesToProxy)
    {
        Bean bean = createBean(originalClass, beanManager);

        if (bean != null)
        {
            afterBeanDiscovery.addBean(bean);
        }
    }

    this.classesToProxy.clear();
}
 
Example #6
Source File: JtaExtension.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
void addContextAndBeans(@Observes final AfterBeanDiscovery afterBeanDiscovery, final BeanManager bm) {
    context = new TransactionContext();
    afterBeanDiscovery.addContext(context);

    if (!hasManager && !hasRegistry) {
        try {
            final GeronimoTransactionManager mgr = new GeronimoTransactionManager();
            afterBeanDiscovery.addBean(new JtaBean(mgr));
        } catch (final XAException e) {
            throw new IllegalStateException(e);
        }
        hasManager = true;
        hasRegistry = true;
    }

    afterBeanDiscovery.addBean(new JtaConfigBean(config));
}
 
Example #7
Source File: InterfaceExtensionTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@Test
public void testAfterBeanDiscovery() throws Exception {
    ConfigView configView = mock(ConfigView.class);
    List<SimpleKey> interfaces = Arrays.asList(new SimpleKey("test"));
    when(configView.simpleSubkeys(any(ConfigKey.class))).thenReturn(interfaces);
    when(configView.valueOf(any(ConfigKey.class))).thenReturn("192.168.1.1");
    ext = new InterfaceExtension(configView);
    
    BeanManager beanManager = mock(BeanManager.class);
    AfterBeanDiscovery abd = mock(AfterBeanDiscovery.class);

    @SuppressWarnings("unchecked")
    ArgumentCaptor<CommonBean<Interface>> captor = ArgumentCaptor.forClass(CommonBean.class);
    
    ext.afterBeanDiscovery(abd, beanManager);
    
    verify(abd,times(1)).addBean(captor.capture());
    assertThat(captor.getValue().create(null).getName()).isEqualTo("test");
    assertThat(captor.getValue().create(null).getExpression()).isEqualTo("192.168.1.1");
}
 
Example #8
Source File: MessageBundleExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
protected void installMessageBundleProducerBeans(@Observes AfterBeanDiscovery abd, BeanManager beanManager)
{
    if (!deploymentErrors.isEmpty())
    {
        abd.addDefinitionError(new IllegalArgumentException("The following MessageBundle problems where found: " +
                Arrays.toString(deploymentErrors.toArray())));
        return;
    }

    MessageBundleExtension parentExtension = ParentExtensionStorage.getParentExtension(this);
    if (parentExtension != null)
    {
        messageBundleTypes.addAll(parentExtension.messageBundleTypes);
    }

    for (AnnotatedType<?> type : messageBundleTypes)
    {
        abd.addBean(createMessageBundleBean(type, beanManager));
    }
}
 
Example #9
Source File: ConfigExtension.java    From smallrye-config with Apache License 2.0 6 votes vote down vote up
protected void registerCustomBeans(@Observes AfterBeanDiscovery abd, BeanManager bm) {
    Set<Class<?>> customTypes = new HashSet<>();
    for (InjectionPoint ip : injectionPoints) {
        Type requiredType = ip.getType();
        if (requiredType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) requiredType;
            // TODO We should probably handle all parameterized types correctly
            if (type.getRawType().equals(Provider.class) || type.getRawType().equals(Instance.class)) {
                // These injection points are satisfied by the built-in Instance bean 
                Type typeArgument = type.getActualTypeArguments()[0];
                if (typeArgument instanceof Class && !isClassHandledByConfigProducer(typeArgument)) {
                    customTypes.add((Class<?>) typeArgument);
                }
            }
        } else if (requiredType instanceof Class
                && !isClassHandledByConfigProducer(requiredType)) {
            // type is not produced by ConfigProducer
            customTypes.add((Class<?>) requiredType);
        }
    }

    for (Class<?> customType : customTypes) {
        abd.addBean(new ConfigInjectionBean(bm, customType));
    }
}
 
Example #10
Source File: AxonCdiExtension.java    From cdi with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void registerSagas(BeanManager beanManager, AfterBeanDiscovery afterBeanDiscovery, Configurer configurer) {
    sagas.forEach(sagaDefinition -> {
        logger.info("Registering saga {}.", sagaDefinition.sagaType().getSimpleName());

        if (!sagaDefinition.explicitConfiguration()
                && !sagaConfigurationProducerMap.containsKey(sagaDefinition.configurationName())) {

            SagaConfiguration<?> sagaConfiguration = SagaConfiguration
                    .subscribingSagaManager(sagaDefinition.sagaType());

            afterBeanDiscovery.addBean(new BeanWrapper<>(sagaDefinition.configurationName(),
                    SagaConfiguration.class,
                    () -> sagaConfiguration));
            sagaDefinition.sagaStore()
                    .ifPresent(sagaStore -> sagaConfiguration
                    .configureSagaStore(c -> produce(beanManager, sagaStoreProducerMap.get(sagaStore))));
            configurer.registerModule(sagaConfiguration);
        }
    });
}
 
Example #11
Source File: ConfigurationExtension.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public void addDynamicBeans(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager bm)
{
    if (dynamicProducer != null && !dynamicConfigTypes.isEmpty())
    {
        afterBeanDiscovery.addBean(new DynamicBean(dynamicProducer, dynamicConfigTypes));
    }
    for (final Class<?> proxyType : dynamicConfigurationBeanClasses)
    {
        afterBeanDiscovery.addBean(new BeanBuilder(null)
                .types(proxyType, Object.class)
                .qualifiers(new DefaultLiteral(), new AnyLiteral())
                .beanLifecycle(new ProxyConfigurationLifecycle(proxyType))
                .scope(ApplicationScoped.class)
                .passivationCapable(true)
                .id("DeltaSpikeConfiguration#" + proxyType.getName())
                .beanClass(proxyType)
                .create());
    }
}
 
Example #12
Source File: DeltaSpikeContextExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public void registerDeltaSpikeContexts(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (!isActivated)
    {
        return;
    }

    windowContext = new WindowContextImpl(beanManager);
    conversationContext = new GroupedConversationContext(beanManager, windowContext);
    viewAccessScopedContext = new ViewAccessContext(beanManager, windowContext);
    afterBeanDiscovery.addContext(windowContext);
    afterBeanDiscovery.addContext(conversationContext);
    afterBeanDiscovery.addContext(viewAccessScopedContext);
}
 
Example #13
Source File: MPJWTCDIExtension.java    From tomee with Apache License 2.0 5 votes vote down vote up
public void registerClaimProducer(@Observes final AfterBeanDiscovery abd, final BeanManager bm) {

        final Set<Type> types = injectionPoints.stream()
                .filter(NOT_PROVIDERS)
                .filter(NOT_INSTANCES)
                .map(ip -> REPLACED_TYPES.getOrDefault(ip.getType(), ip.getType()))
                .collect(Collectors.<Type>toSet());

        final Set<Type> providerTypes = injectionPoints.stream()
                .filter(NOT_PROVIDERS.negate())
                .map(ip -> ((ParameterizedType) ip.getType()).getActualTypeArguments()[0])
                .collect(Collectors.<Type>toSet());

        final Set<Type> instanceTypes = injectionPoints.stream()
                .filter(NOT_INSTANCES.negate())
                .map(ip -> ((ParameterizedType) ip.getType()).getActualTypeArguments()[0])
                .collect(Collectors.<Type>toSet());

        types.addAll(providerTypes);
        types.addAll(instanceTypes);

        types.stream()
                .map(type -> new ClaimBean<>(bm, type))
                .forEach((Consumer<ClaimBean>) abd::addBean);

        abd.addBean()
                .id(MPJWTCDIExtension.class.getName() + "#" + JsonWebToken.class.getName())
                .beanClass(JsonWebToken.class)
                .types(JsonWebToken.class, Object.class)
                .qualifiers(Default.Literal.INSTANCE, Any.Literal.INSTANCE)
                .scope(Dependent.class)
                .createWith(ctx -> {
                    final Principal principal = getContextualReference(Principal.class, bm);
                    if (JsonWebToken.class.isInstance(principal)) {
                        return JsonWebToken.class.cast(principal);
                    }

                    return null;
                });
    }
 
Example #14
Source File: BatchCDIInjectionExtension.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
public void setBeanManager(final @Observes AfterBeanDiscovery afterBeanDiscovery, final BeanManager beanManager) {
    // bean manager holder
    if (bmpSingleton == null) {
        bmpSingleton = this;
    }

    if (!CDI_1_1_AVAILABLE) {
        final BeanManagerInfo bmi = getBeanManagerInfo(loader());
        bmi.loadTimeBm = beanManager;
    }
}
 
Example #15
Source File: BatchEEScopeExtension.java    From incubator-batchee with Apache License 2.0 5 votes vote down vote up
void addBatchScopes(final @Observes AfterBeanDiscovery afterBeanDiscovery, final BeanManager bm) {
    jobContext = new JobContextImpl(bm);
    stepContext = new StepContextImpl(bm);

    afterBeanDiscovery.addContext(jobContext);
    afterBeanDiscovery.addContext(stepContext);
}
 
Example #16
Source File: JAXRSCdiResourceExtension.java    From cxf with Apache License 2.0 5 votes vote down vote up
public void injectBus(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
    if (!hasBus) {
        final AnnotatedType< ExtensionManagerBus > busAnnotatedType =
            beanManager.createAnnotatedType(ExtensionManagerBus.class);

        final InjectionTarget<ExtensionManagerBus> busInjectionTarget =
            beanManager.createInjectionTarget(busAnnotatedType);
        event.addBean(new CdiBusBean(busInjectionTarget));
    }

    if (applicationBeans.isEmpty() && !serviceBeans.isEmpty()) {
        final DefaultApplicationBean applicationBean = new DefaultApplicationBean();
        applicationBeans.add(applicationBean);
        event.addBean(applicationBean);
    } else {
        // otherwise will be ambiguous since we scanned it with default qualifier already
        existingStandardClasses.add(Application.class.getName());
    }

    // always add the standard context classes
    InjectionUtils.STANDARD_CONTEXT_CLASSES.stream()
            .map(this::toClass)
            .filter(Objects::nonNull)
            .forEach(contextTypes::add);
    // add custom contexts
    contextTypes.addAll(getCustomContextClasses());
    // register all of the context types
    contextTypes.forEach(
        t -> event.addBean(new ContextProducerBean(t, !existingStandardClasses.contains(t.getTypeName()))));
}
 
Example #17
Source File: PortletCDIExtension.java    From portals-pluto with Apache License 2.0 5 votes vote down vote up
/**
 * Add the context for the custom scope implementations.
 * 
 * @param abd
 */
void addPortletCustomScopeContexts(@Observes AfterBeanDiscovery abd) {
   RedirectScopedContext rsc = new RedirectScopedContext();
   abd.addContext(rsc);

   PortletSessionScopedContext pssc = new PortletSessionScopedContext();
   abd.addContext(pssc);
   
   PortletStateScopedContext pstsc = new PortletStateScopedContext();
   abd.addContext(pstsc);
   
   PortletRequestScopedContext prsc = new PortletRequestScopedContext();
   abd.addContext(prsc);
}
 
Example #18
Source File: TransactionContextExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Register the TransactionContext as a CDI Context
 *
 * @param afterBeanDiscovery after-bean-discovery event
 */
protected void registerTransactionContext(@Observes AfterBeanDiscovery afterBeanDiscovery)
{
    if (!isActivated)
    {
        return;
    }

    TransactionContext transactionContext = new TransactionContext();
    afterBeanDiscovery.addContext(transactionContext);
}
 
Example #19
Source File: ViewScopedExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * Register and start the ViewScopedContext.
 */
public void registerViewContext(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (!isActivated)
    {
        return;
    }

    //X TODO check whether we still need this in EE6: CodiStartupBroadcaster.broadcastStartup();
    
    afterBeanDiscovery.addContext(new ViewScopedContext(beanManager));
}
 
Example #20
Source File: PartialBeanBindingExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public <X> void createBeans(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (!this.isActivated)
    {
        return;
    }

    if (this.definitionError != null)
    {
        afterBeanDiscovery.addDefinitionError(this.definitionError);
        return;
    }

    for (Map.Entry<Class<? extends Annotation>, PartialBeanDescriptor> entry : this.descriptors.entrySet())
    {
        PartialBeanDescriptor descriptor = entry.getValue();
        if (descriptor.getClasses() != null)
        {
            for (Class partialBeanClass : descriptor.getClasses())
            {
                Bean partialBean = createPartialBean(partialBeanClass, descriptor, afterBeanDiscovery, beanManager);
                if (partialBean != null)
                {
                    afterBeanDiscovery.addBean(partialBean);

                    List<Bean> partialProducerBeans =
                        createPartialProducersDefinedIn(partialBean, afterBeanDiscovery, beanManager);

                    for (Bean partialProducerBean : partialProducerBeans)
                    {
                        afterBeanDiscovery.addBean(partialProducerBean);
                    }
                }
            }
        }
    }

    this.descriptors.clear();
}
 
Example #21
Source File: ConfigurationExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public void registerUserConfigSources(@Observes AfterBeanDiscovery abd)
{
    if (!isActivated)
    {
        return;
    }

    // create a local copy with all the collected PropertyFileConfig
    Set<Class<? extends PropertyFileConfig>> allPropertyFileConfigClasses
        = new HashSet<Class<? extends PropertyFileConfig>>(this.propertyFileConfigClasses);

    // now add any PropertyFileConfigs from a 'parent BeanManager'
    // we start with the current TCCL
    ClassLoader currentClassLoader = ClassUtils.getClassLoader(null);
    addParentPropertyFileConfigs(currentClassLoader, allPropertyFileConfigClasses);

    // now let's add our own PropertyFileConfigs to the detected ones.
    // because maybe WE are a parent BeanManager ourselves!
    if (!this.propertyFileConfigClasses.isEmpty())
    {
        detectedParentPropertyFileConfigs.put(currentClassLoader, this.propertyFileConfigClasses);
    }

    // collect all the ConfigSources from our PropertyFileConfigs
    List<ConfigSource> configSources = new ArrayList<ConfigSource>();
    for (Class<? extends PropertyFileConfig> propertyFileConfigClass : allPropertyFileConfigClasses)
    {
        configSources.addAll(createPropertyConfigSource(propertyFileConfigClass));
    }
    ConfigResolver.addConfigSources(configSources);

    registerConfigMBean();

    logConfiguration();
}
 
Example #22
Source File: PartialBeanBindingExtension.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected <T> Bean<T> createPartialBean(Class<T> beanClass, PartialBeanDescriptor descriptor,
        AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager)
{
    if (descriptor.getHandler() == null)
    {
        afterBeanDiscovery.addDefinitionError(new IllegalStateException("A class which implements "
                + InvocationHandler.class.getName()
                + " and is annotated with @" + descriptor.getBinding().getName()
                + " is needed as a handler for " + beanClass.getName()
                + ". See the documentation about @" + PartialBeanBinding.class.getName() + "."));

        return null;
    }

    AnnotatedType<T> annotatedType = new AnnotatedTypeBuilder<T>().readFromType(beanClass).create();

    DeltaSpikeProxyContextualLifecycle lifecycle = new DeltaSpikeProxyContextualLifecycle(beanClass,
            descriptor.getHandler(),
            PartialBeanProxyFactory.getInstance(),
            beanManager);

    BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager)
            .readFromType(annotatedType)
            .passivationCapable(true)
            .beanLifecycle(lifecycle);

    return beanBuilder.create();
}
 
Example #23
Source File: WeldCDIExtension.java    From weld-junit with Apache License 2.0 5 votes vote down vote up
void afterBeandiscovery(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
    if (scopesToActivate != null) {
        for (Class<? extends Annotation> scope : scopesToActivate) {
            ContextImpl ctx = new ContextImpl(scope, beanManager);
            contexts.add(ctx);
            event.addContext(ctx);
        }
    }
    if (beans != null) {
        for (Bean<?> bean : beans) {
            event.addBean(bean);
        }
    }
}
 
Example #24
Source File: InterfaceExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {

    List<SimpleKey> configuredInterfaces = this.configView.simpleSubkeys(ROOT);

    for (SimpleKey interfaceName : configuredInterfaces) {

        Set<Bean<?>> ifaces = beanManager.getBeans(Interface.class, Any.Literal.INSTANCE);

        if (ifaces
                .stream()
                .noneMatch(e -> e.getQualifiers()
                        .stream()
                        .anyMatch(anno -> anno instanceof Named && ((Named) anno).value().equals(interfaceName + "-interface")))) {

            Interface iface = new Interface(interfaceName.name(), "0.0.0.0");
            applyConfiguration(iface);
            CommonBean<Interface> interfaceBean = CommonBeanBuilder.newBuilder(Interface.class)
                        .beanClass(InterfaceExtension.class)
                        .scope(ApplicationScoped.class)
                        .addQualifier(Any.Literal.INSTANCE)
                        .addQualifier(NamedLiteral.of(interfaceName.name() + "-interface"))
                        .createSupplier(() -> iface)
                        .addType(Interface.class)
                        .addType(Object.class)
                        .build();

            abd.addBean(interfaceBean);
        }
    }
}
 
Example #25
Source File: ConfigurableExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"unused"})
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) throws Exception {
    try (AutoCloseable handle = Performance.time("ConfigurationExtension.afterBeanDiscovery")) {
        CommonBean<ConfigurableManager> configurableManagerBean = CommonBeanBuilder.newBuilder(ConfigurableManager.class)
                .beanClass(ConfigurableManager.class)
                .scope(Singleton.class)
                .addQualifier(Default.Literal.INSTANCE)
                .createSupplier(() -> configurableManager)
                .addType(ConfigurableManager.class)
                .addType(Object.class).build();
        abd.addBean(configurableManagerBean);
    }
}
 
Example #26
Source File: SocketBindingGroupExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {

    List<SimpleKey> configuredGroups = this.configView.simpleSubkeys(ROOT);
    for (SimpleKey groupName : configuredGroups) {
        Set<Bean<?>> groups = beanManager.getBeans(SocketBindingGroup.class, Any.Literal.INSTANCE);
        AtomicBoolean producerRequired = new AtomicBoolean(false);
        if (groups
                .stream()
                .noneMatch(e -> e.getQualifiers()
                        .stream()
                        .anyMatch(anno -> anno instanceof Named && ((Named) anno).value().equals(groupName)))) {

            SocketBindingGroup group = new SocketBindingGroup(groupName.name(), null, "0");

            applyConfiguration(group);

            if (producerRequired.get()) {
                CommonBean<SocketBindingGroup> interfaceBean = CommonBeanBuilder.newBuilder(SocketBindingGroup.class)
                        .beanClass(SocketBindingGroupExtension.class)
                        .scope(ApplicationScoped.class)
                        .addQualifier(Any.Literal.INSTANCE)
                        .addQualifier(NamedLiteral.of(group.name()))
                        .createSupplier(() -> group)
                        .addType(SocketBindingGroup.class)
                        .addType(Object.class)
                        .build();

                abd.addBean(interfaceBean);
            }
        }
    }
}
 
Example #27
Source File: OutboundSocketBindingExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {
    try (AutoCloseable handle = Performance.time("OutboundSocketBindingExtension.afterBeanDiscovery")) {
        for (OutboundSocketBindingRequest each : this.bindings) {

            Supplier<Customizer> customizerSupplier = () -> (Customizer) () -> {
                Set<Bean<?>> groups = beanManager.getBeans(SocketBindingGroup.class, Any.Literal.INSTANCE);

                groups.stream()
                        .map((Bean<?> e) -> {
                            CreationalContext<?> ctx = beanManager.createCreationalContext(e);
                            return (SocketBindingGroup) beanManager.getReference(e, SocketBindingGroup.class, ctx);
                        })
                        .filter(group -> group.name().equals(each.socketBindingGroup()))
                        .findFirst()
                        .ifPresent((group) -> group.outboundSocketBinding(each.outboundSocketBinding()));
            };
            CommonBean<Customizer> customizerBean = CommonBeanBuilder.newBuilder(Customizer.class)
                    .beanClass(OutboundSocketBindingExtension.class)
                    .scope(Singleton.class)
                    .addQualifier(Pre.Literal.INSTANCE)
                    .addQualifier(Any.Literal.INSTANCE)
                    .createSupplier(customizerSupplier)
                    .addType(Customizer.class)
                    .addType(Object.class).build();
            abd.addBean(customizerBean);
        }
    }
}
 
Example #28
Source File: SocketBindingExtension.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unused")
void afterBeanDiscovery(@Observes AfterBeanDiscovery abd, BeanManager beanManager) throws Exception {
    try (AutoCloseable handle = Performance.time("SocketBindingExtension.afterBeanDiscovery")) {

        for (SocketBindingRequest each : this.bindings) {

            Supplier<Customizer> supplier = () -> (Customizer) () -> {
                Set<Bean<?>> groups = beanManager.getBeans(SocketBindingGroup.class, Any.Literal.INSTANCE);

                groups.stream()
                        .map((Bean<?> e) -> {
                            CreationalContext<?> ctx = beanManager.createCreationalContext(e);
                            return (SocketBindingGroup) beanManager.getReference(e, SocketBindingGroup.class, ctx);
                        })
                        .filter(group -> group.name().equals(each.socketBindingGroup()))
                        .findFirst()
                        .ifPresent((group) -> group.socketBinding(each.socketBinding()));
            };

            CommonBean<Customizer> customizerBean = CommonBeanBuilder.newBuilder(Customizer.class)
                    .beanClass(SocketBindingExtension.class)
                    .scope(Singleton.class)
                    .addQualifier(Pre.Literal.INSTANCE)
                    .addQualifier(Any.Literal.INSTANCE)
                    .createSupplier(supplier)
                    .addType(Customizer.class)
                    .addType(Object.class).build();
            abd.addBean(customizerBean);
        }
    }
}
 
Example #29
Source File: CdiConfig.java    From ee8-sandbox with Apache License 2.0 5 votes vote down vote up
public void addABean(@Observes AfterBeanDiscovery event) {
    // get an instance of BeanConfigurator
    event.addBean()
            // set the desired data
            .types(Greeter.class)
            .scope(ApplicationScoped.class)
            .addQualifier(Default.Literal.INSTANCE)
            //.addQualifier(Custom.CustomLiteral.INSTANCE);
            //finally, add a callback to tell CDI how to instantiate this bean
            .produceWith(obj -> new Greeter());
}
 
Example #30
Source File: VertxExtension.java    From weld-vertx with Apache License 2.0 5 votes vote down vote up
public void registerBeansAfterBeanDiscovery(@Observes AfterBeanDiscovery event) {
    if (vertx == null) {
        // Do no register beans - no Vertx instance available during bootstrap
        return;
    }
    // Allow to inject Vertx used to deploy the WeldVerticle
    event.addBean().types(getBeanTypes(vertx.getClass(), Vertx.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE)
            .scope(ApplicationScoped.class).createWith(c -> vertx);
    // Allow to inject Context of the WeldVerticle
    event.addBean().types(getBeanTypes(context.getClass(), Context.class)).addQualifiers(Any.Literal.INSTANCE, Default.Literal.INSTANCE)
            .scope(ApplicationScoped.class).createWith(c -> context);
}