javax.enterprise.inject.Any Java Examples

The following examples show how to use javax.enterprise.inject.Any. 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: DefaultJoynrRuntimeFactory.java    From joynr with Apache License 2.0 6 votes vote down vote up
private <T> AbstractModule getModuleForBeansOfType(Class<T> beanType,
                                                   Supplier<TypeLiteral<T>> typeLiteralSupplier) {
    final Set<Bean<?>> beans = beanManager.getBeans(beanType, new AnnotationLiteral<Any>() {
        private static final long serialVersionUID = 1L;
    });
    return new AbstractModule() {
        @SuppressWarnings("unchecked")
        @Override
        protected void configure() {

            Multibinder<T> beanMultibinder = Multibinder.newSetBinder(binder(), typeLiteralSupplier.get());
            for (Bean<?> bean : beans) {
                beanMultibinder.addBinding()
                               .toInstance((T) Proxy.newProxyInstance(getClass().getClassLoader(),
                                                                      new Class[]{ beanType },
                                                                      new BeanCallingProxy<T>((Bean<T>) bean,
                                                                                              beanManager)));
            }
        }
    };
}
 
Example #2
Source File: AsyncReferenceImpl.java    From weld-vertx with Apache License 2.0 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 #3
Source File: VertxProducer.java    From quarkus with Apache License 2.0 6 votes vote down vote up
/**
 * Undeploy verticles backed by contextual instances of {@link ApplicationScoped} beans before the application context is
 * destroyed. Otherwise Vertx may attempt to stop the verticles after the CDI container is shut down.
 * 
 * @param event
 * @param beanManager
 */
void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event,
        BeanManager beanManager, io.vertx.mutiny.core.Vertx mutiny) {
    // Only beans with the AbstractVerticle in the set of bean types are considered - we need a deployment id 
    Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
    Context applicationContext = beanManager.getContext(ApplicationScoped.class);
    for (Bean<?> bean : beans) {
        if (ApplicationScoped.class.equals(bean.getScope())) {
            // Only beans with @ApplicationScoped are considered
            Object instance = applicationContext.get(bean);
            if (instance != null) {
                // Only existing instances are considered
                try {
                    AbstractVerticle verticle = (AbstractVerticle) instance;
                    mutiny.undeploy(verticle.deploymentID()).await().indefinitely();
                    LOGGER.debugf("Undeployed verticle: %s", instance.getClass());
                } catch (Exception e) {
                    // In theory, a user can undeploy the verticle manually
                    LOGGER.debugf("Unable to undeploy verticle %s: %s", instance.getClass(), e.toString());
                }
            }
        }
    }
}
 
Example #4
Source File: DataSources.java    From quarkus with Apache License 2.0 6 votes vote down vote up
public DataSources(DataSourcesBuildTimeConfig dataSourcesBuildTimeConfig,
        DataSourcesRuntimeConfig dataSourcesRuntimeConfig, DataSourcesJdbcBuildTimeConfig dataSourcesJdbcBuildTimeConfig,
        DataSourcesJdbcRuntimeConfig dataSourcesJdbcRuntimeConfig,
        LegacyDataSourcesJdbcBuildTimeConfig legacyDataSourcesJdbcBuildTimeConfig,
        LegacyDataSourcesRuntimeConfig legacyDataSourcesRuntimeConfig,
        LegacyDataSourcesJdbcRuntimeConfig legacyDataSourcesJdbcRuntimeConfig, TransactionManager transactionManager,
        TransactionSynchronizationRegistry transactionSynchronizationRegistry, DataSourceSupport dataSourceSupport,
        @Any Instance<AgroalPoolInterceptor> agroalPoolInterceptors) {
    this.dataSourcesBuildTimeConfig = dataSourcesBuildTimeConfig;
    this.dataSourcesRuntimeConfig = dataSourcesRuntimeConfig;
    this.dataSourcesJdbcBuildTimeConfig = dataSourcesJdbcBuildTimeConfig;
    this.dataSourcesJdbcRuntimeConfig = dataSourcesJdbcRuntimeConfig;
    this.legacyDataSourcesJdbcBuildTimeConfig = legacyDataSourcesJdbcBuildTimeConfig;
    this.legacyDataSourcesRuntimeConfig = legacyDataSourcesRuntimeConfig;
    this.legacyDataSourcesJdbcRuntimeConfig = legacyDataSourcesJdbcRuntimeConfig;
    this.transactionManager = transactionManager;
    this.transactionSynchronizationRegistry = transactionSynchronizationRegistry;
    this.dataSourceSupport = dataSourceSupport;
    this.agroalPoolInterceptors = agroalPoolInterceptors;
}
 
Example #5
Source File: AuthorizationProcessingFilter.java    From oxTrust with MIT License 6 votes vote down vote up
/**
 * Builds a map around url patterns and service beans that are aimed to perform
 * actual protection
 */
@SuppressWarnings("unchecked")
@PostConstruct
private void init() {
	protectionMapping = new HashMap<String, Class<BaseUmaProtectionService>>();
	Set<Bean<?>> beans = beanManager.getBeans(BaseUmaProtectionService.class, Any.Literal.INSTANCE);
	
	for (Bean bean : beans) {
		Class beanClass = bean.getBeanClass();
		Annotation beanAnnotation = beanClass.getAnnotation(BindingUrls.class);
		if (beanAnnotation != null) {
			for (String pattern : ((BindingUrls) beanAnnotation).value()) {
				if (pattern.length() > 0) {
					protectionMapping.put(pattern, beanClass);
				}
			}
		}
	}
}
 
Example #6
Source File: WebContextProducer.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
public CDIPortletWebContext(BeanManager beanManager, VariableValidator variableInspector, Models models,
	String lifecyclePhase, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
	ServletContext servletContext, Locale locale) {

	super(httpServletRequest, httpServletResponse, servletContext, locale);
	this.beanManager = beanManager;
	this.models = models;
	this.beanNames = new HashSet<>();

	boolean headerPhase = lifecyclePhase.equals(PortletRequest.HEADER_PHASE);
	boolean renderPhase = lifecyclePhase.equals(PortletRequest.RENDER_PHASE);
	boolean resourcePhase = lifecyclePhase.equals(PortletRequest.RESOURCE_PHASE);

	Set<Bean<?>> beans = beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
			});

	for (Bean<?> bean : beans) {
		String beanName = bean.getName();

		if ((beanName != null) &&
				variableInspector.isValidName(beanName, headerPhase, renderPhase, resourcePhase)) {
			this.beanNames.add(beanName);
		}
	}
}
 
Example #7
Source File: ServiceProviderDiscovery.java    From joynr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("serial")
public Set<Bean<?>> findServiceProviderBeans() {
    Set<Bean<?>> result = new HashSet<>();
    for (Bean<?> bean : beanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })) {
        ServiceProvider serviceProvider = bean.getBeanClass().getAnnotation(ServiceProvider.class);
        if (serviceProvider != null) {
            ProvidedBy providedBy = getProvidedByAnnotation(serviceProvider.serviceInterface());
            verifyProvidedBy(providedBy, serviceProvider.serviceInterface(), bean);
            result.add(bean);
            if (logger.isTraceEnabled()) {
                logger.trace(format("Bean %s is a service provider. Adding to result.", bean));
            }
        } else if (logger.isTraceEnabled()) {
            logger.trace(format("Ignoring bean: %s", bean));
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug(format("Found the following service provider beans:%n%s", result));
    }
    return result;
}
 
Example #8
Source File: ServiceProviderDiscoveryTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "serial" })
@Test
public void testFindServiceProviderBeans() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
    Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanTwo> mockBeanTwo = mock(Bean.class);
    Mockito.doReturn(DummyBeanTwo.class).when(mockBeanTwo).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(mockBeanOne);
    beans.add(mockBeanTwo);
    Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    Set<Bean<?>> result = subject.findServiceProviderBeans();

    assertNotNull(result);
    assertEquals(1, result.size());
    assertTrue(result.iterator().next().getBeanClass().equals(DummyBeanOne.class));
}
 
Example #9
Source File: BeanArchives.java    From quarkus with Apache License 2.0 6 votes vote down vote up
private static IndexView buildAdditionalIndex() {
    Indexer indexer = new Indexer();
    // CDI API
    index(indexer, ActivateRequestContext.class.getName());
    index(indexer, Default.class.getName());
    index(indexer, Any.class.getName());
    index(indexer, Named.class.getName());
    index(indexer, Initialized.class.getName());
    index(indexer, BeforeDestroyed.class.getName());
    index(indexer, Destroyed.class.getName());
    index(indexer, Intercepted.class.getName());
    index(indexer, Model.class.getName());
    // Arc built-in beans
    index(indexer, ActivateRequestContextInterceptor.class.getName());
    index(indexer, InjectableRequestContextController.class.getName());
    return indexer.complete();
}
 
Example #10
Source File: ServiceProviderDiscoveryTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testInvalidServiceInterfaceSpecified() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
    Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanFour> mockBeanThree = mock(Bean.class);
    Mockito.doReturn(DummyBeanThree.class).when(mockBeanThree).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(mockBeanOne);
    beans.add(mockBeanThree);
    Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    subject.findServiceProviderBeans();
    fail("Shouldn't be able to get here with an invalid bean (DummyBeanThree)");
}
 
Example #11
Source File: SmallRyeHealthReporter.java    From smallrye-health with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private <T> List<T> getHealthGroupsChecks(Class<T> checkClass) {
    Iterator<Bean<?>> iterator = beanManager.getBeans(checkClass, Any.Literal.INSTANCE).iterator();

    List<T> groupHealthChecks = new ArrayList<>();

    while (iterator.hasNext()) {
        Bean<?> bean = iterator.next();
        if (bean.getQualifiers().stream().anyMatch(annotation -> annotation.annotationType().equals(HealthGroup.class))) {
            groupHealthChecks.add((T) beanManager.getReference(bean, bean.getBeanClass(),
                    beanManager.createCreationalContext(bean)));
        }
    }

    return groupHealthChecks;
}
 
Example #12
Source File: ServiceProviderDiscoveryTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testWrongServiceInterfaceSpecified() {
    BeanManager mockBeanManager = mock(BeanManager.class);

    Bean<DummyBeanOne> mockBeanOne = mock(Bean.class);
    Mockito.doReturn(DummyBeanOne.class).when(mockBeanOne).getBeanClass();
    Bean<DummyBeanFour> mockBeanFour = mock(Bean.class);
    Mockito.doReturn(DummyBeanFour.class).when(mockBeanFour).getBeanClass();

    Set<Bean<?>> beans = new HashSet<>();
    beans.add(mockBeanOne);
    beans.add(mockBeanFour);
    Mockito.when(mockBeanManager.getBeans(Object.class, new AnnotationLiteral<Any>() {
    })).thenReturn(beans);

    ServiceProviderDiscovery subject = new ServiceProviderDiscovery(mockBeanManager);

    subject.findServiceProviderBeans();
    fail("Shouldn't be able to get here with an invalid bean (DummyBeanFour)");
}
 
Example #13
Source File: MakeJCacheCDIInterceptorFriendly.java    From commons-jcs with Apache License 2.0 6 votes vote down vote up
public HelperBean(final AnnotatedType<CDIJCacheHelper> annotatedType,
                  final InjectionTarget<CDIJCacheHelper> injectionTarget,
                  final String id) {
    this.at = annotatedType;
    this.it = injectionTarget;
    this.id =  "JCS#CDIHelper#" + id;

    this.qualifiers = new HashSet<>();
    this.qualifiers.add(new AnnotationLiteral<Default>() {

        /**
         * 
         */
        private static final long serialVersionUID = 3314657767813459983L;});
    this.qualifiers.add(new AnnotationLiteral<Any>() {

        /**
         * 
         */
        private static final long serialVersionUID = 7419841275942488170L;});
}
 
Example #14
Source File: ConfiguredChannelFactory.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
ConfiguredChannelFactory(@Any Instance<IncomingConnectorFactory> incomingConnectorFactories,
        @Any Instance<OutgoingConnectorFactory> outgoingConnectorFactories,
        Instance<Config> config, @Any Instance<ChannelRegistry> registry,
        BeanManager beanManager, boolean logConnectors) {
    this.registry = registry.get();
    if (config.isUnsatisfied()) {
        this.incomingConnectorFactories = null;
        this.outgoingConnectorFactories = null;
        this.config = null;
    } else {
        this.incomingConnectorFactories = incomingConnectorFactories;
        this.outgoingConnectorFactories = outgoingConnectorFactories;
        if (logConnectors) {
            log.foundIncomingConnectors(getConnectors(beanManager, IncomingConnectorFactory.class));
            log.foundOutgoingConnectors(getConnectors(beanManager, OutgoingConnectorFactory.class));
        }
        //TODO Should we try to merge all the config?
        // For now take the first one.
        this.config = config.stream().findFirst()
                .orElseThrow(() -> ex.illegalStateRetieveConfig());
    }
}
 
Example #15
Source File: ServiceLocator.java    From acmeair with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the services that are available for use with the description for each service. 
 * The Services are determined by looking up all of the implementations of the 
 * Customer Service interface that are using the  DataService qualifier annotation. 
 * The DataService annotation contains the service name and description information. 
 * @return Map containing a list of services available and a description of each one.
 */
public Map<String,String> getServices (){
	TreeMap<String,String> services = new TreeMap<String,String>();
	logger.fine("Getting CustomerService Impls");
   	Set<Bean<?>> beans = beanManager.getBeans(CustomerService.class,new AnnotationLiteral<Any>() {
		private static final long serialVersionUID = 1L;});
   	for (Bean<?> bean : beans) {    		
   		for (Annotation qualifer: bean.getQualifiers()){
   			if(DataService.class.getName().equalsIgnoreCase(qualifer.annotationType().getName())){
   				DataService service = (DataService) qualifer;
   				logger.fine("   name="+service.name()+" description="+service.description());
   				services.put(service.name(), service.description());
   			}
   		}
   	}    	
   	return services;
}
 
Example #16
Source File: TransactionStrategyHelper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * <p>This method uses the InvocationContext to scan the &#064;Transactional
 * interceptor for a manually specified Qualifier.</p>
 *
 * <p>If none is given (defaults to &#04;Any.class) then we scan the intercepted
 * instance and resolve the Qualifiers of all it's injected EntityManagers.</p>
 *
 * <p>Please note that we will only pickup the first Qualifier on the
 * injected EntityManager. We also do <b>not</b> parse for binding or
 * &h#064;NonBinding values. A &#064;Qualifier should not have any parameter at all.</p>
 * @param entityManagerMetadata the metadata to locate the entity manager
 * @param interceptedTargetClass the Class of the intercepted target
 */
public Set<Class<? extends Annotation>> resolveEntityManagerQualifiers(EntityManagerMetadata entityManagerMetadata,
                                                                       Class interceptedTargetClass)
{
    Set<Class<? extends Annotation>> emQualifiers = new HashSet<>();
    Class<? extends Annotation>[] qualifierClasses = entityManagerMetadata.getQualifiers();

    if (qualifierClasses == null || qualifierClasses.length == 1 && Any.class.equals(qualifierClasses[0]) )
    {
        // this means we have no special EntityManager configured in the interceptor
        // thus we should scan all the EntityManagers ourselfs from the intercepted class
        collectEntityManagerQualifiersOnClass(emQualifiers, interceptedTargetClass);
    }
    else
    {
        // take the qualifierKeys from the qualifierClasses
        Collections.addAll(emQualifiers, qualifierClasses);
    }

    //see DELTASPIKE-320
    if (emQualifiers.isEmpty())
    {
        emQualifiers.add(Default.class);
    }
    return emQualifiers;
}
 
Example #17
Source File: ConversationKey.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public ConversationKey(Class<?> groupKey, Annotation... qualifiers)
{
    this.groupKey = groupKey;

    //TODO maybe we have to add a real qualifier instead
    Class<? extends Annotation> annotationType;
    for (Annotation qualifier : qualifiers)
    {
        annotationType = qualifier.annotationType();

        if (Any.class.isAssignableFrom(annotationType) ||
                Default.class.isAssignableFrom(annotationType) ||
                Named.class.isAssignableFrom(annotationType) ||
                ConversationGroup.class.isAssignableFrom(annotationType))
        {
            //won't be used for this key!
            continue;
        }

        if (this.qualifiers == null)
        {
            this.qualifiers = new HashSet<Annotation>();
        }
        this.qualifiers.add(qualifier);
    }
}
 
Example #18
Source File: BeanQualifierTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testManagementOfBeanUsingAQualifier() {
    addBeanClass(BeanWithQualifier.class);
    initialize();
    BeanWithQualifier bean = container.getBeanManager().createInstance()
            .select(BeanWithQualifier.class, Any.Literal.INSTANCE).get();
    assertThat(bean).isNotNull();
    assertThat(bean.get()).isNotEmpty().containsExactly("HELLO", "SMALLRYE", "REACTIVE", "MESSAGE");
}
 
Example #19
Source File: ConfiguredChannelFactory.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private List<String> getConnectors(BeanManager beanManager, Class<?> clazz) {
    return beanManager.getBeans(clazz, Any.Literal.INSTANCE).stream()
            .map(BeanAttributes::getQualifiers)
            .flatMap(set -> set.stream().filter(a -> a.annotationType().equals(Connector.class)))
            .map(annotation -> ((Connector) annotation).value())
            .collect(Collectors.toList());
}
 
Example #20
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 #21
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 #22
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 #23
Source File: ConfigurableFractionBean.java    From thorntail with Apache License 2.0 5 votes vote down vote up
@Override
public Set<Annotation> getQualifiers() {
    Set<Annotation> qualifiers = new HashSet<>();
    qualifiers.add(Default.Literal.INSTANCE);
    qualifiers.add(Any.Literal.INSTANCE);
    return qualifiers;
}
 
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: 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);
}
 
Example #26
Source File: BeanLocator.java    From AngularBeans with GNU Lesser General Public License v3.0 5 votes vote down vote up
public Object lookup(String beanName, String sessionID) {

		NGSessionScopeContext.setCurrentContext(sessionID);

		Set<Bean<?>> beans = beanManager.getBeans(beanName);

		Class beanClass = CommonUtils.beanNamesHolder.get(beanName);
		if (beans.isEmpty()) {
			beans = beanManager.getBeans(beanClass, new AnnotationLiteral<Any>() { //
			});
		}

		Bean bean = beanManager.resolve(beans);

		Class scopeAnnotationClass = bean.getScope();
		Context context;

		if (scopeAnnotationClass.equals(RequestScoped.class)) {
			context = beanManager.getContext(scopeAnnotationClass);
			if (context == null)
				return bean.create(beanManager.createCreationalContext(bean));

		} else {

			if (scopeAnnotationClass.equals(NGSessionScopeContext.class)) {
				context = NGSessionScopeContext.getINSTANCE();
			} else {
				context = beanManager.getContext(scopeAnnotationClass);
			}

		}
		CreationalContext creationalContext = beanManager.createCreationalContext(bean);
		Object reference = context.get(bean, creationalContext);

		// if(reference==null && scopeAnnotationClass.equals(RequestScoped.class)){
		// reference= bean.create(beanManager.createCreationalContext(bean));
		// }

		return reference;
	}
 
Example #27
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 #28
Source File: FlywayExtension.java    From tutorials with MIT License 5 votes vote down vote up
void afterBeanDiscovery(@Observes AfterBeanDiscovery abdEvent, BeanManager bm) {
    abdEvent.addBean()
            .types(javax.sql.DataSource.class, DataSource.class)
            .qualifiers(new AnnotationLiteral<Default>() {}, new AnnotationLiteral<Any>() {})
            .scope(ApplicationScoped.class)
            .name(DataSource.class.getName())
            .beanClass(DataSource.class)
            .createWith(creationalContext -> {
                DataSource instance = new DataSource();
                instance.setUrl(dataSourceDefinition.url());
                instance.setDriverClassName(dataSourceDefinition.className());
                return instance;
            });
}
 
Example #29
Source File: JoynrIntegrationBean.java    From joynr with Apache License 2.0 5 votes vote down vote up
/**
 * A util method to find factories which provide some customized settings needed for
 * registration of joynr providers, i.e. implementations of the interface
 * {@link ProviderRegistrationSettingsFactory}.
 *
 * @return set of factories implementing the interface
 */
@SuppressWarnings({ "rawtypes", "unchecked", "serial" })
private Set<ProviderRegistrationSettingsFactory> getProviderRegistrationSettingsFactories() {
    Set<Bean<?>> providerSettingsFactoryBeans = beanManager.getBeans(ProviderRegistrationSettingsFactory.class,
                                                                     new AnnotationLiteral<Any>() {
                                                                     });
    Set<ProviderRegistrationSettingsFactory> providerSettingsFactories = new HashSet<>();
    for (Bean providerSettingsFactoryBean : providerSettingsFactoryBeans) {
        ProviderRegistrationSettingsFactory factory = (ProviderRegistrationSettingsFactory) providerSettingsFactoryBean.create(beanManager.createCreationalContext(providerSettingsFactoryBean));
        providerSettingsFactories.add(factory);
    }
    return providerSettingsFactories;
}
 
Example #30
Source File: GsonBuilderWrapper.java    From vraptor4 with Apache License 2.0 5 votes vote down vote up
@Inject
public GsonBuilderWrapper(@Any Instance<JsonSerializer<?>> jsonSerializers, 
		@Any Instance<JsonDeserializer<?>> jsonDeserializers,
		Serializee serializee, ReflectionProvider reflectionProvider) {
	this.jsonSerializers = jsonSerializers;
	this.jsonDeserializers = jsonDeserializers;
	this.serializee = serializee;
	ExclusionStrategy exclusion = new Exclusions(serializee, reflectionProvider);
	exclusions = singletonList(exclusion);
}