Search in sources :

Example 6 with BeanManager

use of jakarta.enterprise.inject.spi.BeanManager in project cdi-tck by eclipse-ee4j.

the class ActivateRequestContextProgrammaticallyTest method programmaticRequestContextActivation.

@Test
@SpecAssertions({ @SpecAssertion(section = ACTIVATING_REQUEST_CONTEXT, id = "a"), @SpecAssertion(section = ACTIVATING_REQUEST_CONTEXT, id = "c"), @SpecAssertion(section = ACTIVATING_REQUEST_CONTEXT, id = "da"), @SpecAssertion(section = ACTIVATING_REQUEST_CONTEXT, id = "e") })
public void programmaticRequestContextActivation() {
    SeContainerInitializer seContainerInitializer = SeContainerInitializer.newInstance();
    try (SeContainer container = seContainerInitializer.initialize()) {
        TestContextActivator contextActivator = container.select(TestContextActivator.class).get();
        boolean activated = contextActivator.activate();
        Assert.assertTrue(activated);
        Assert.assertFalse(contextActivator.activate());
        contextActivator.callRequestScopeBean();
        RequestScopeCounter counter = container.select(RequestScopeCounter.class).get();
        Assert.assertEquals(contextActivator.callRequestScopeBean(), 2);
        contextActivator.deactivate();
        contextActivator.activate();
        BeanManager beanManager = container.getBeanManager();
        Assert.assertTrue(beanManager.getContext(RequestScoped.class).isActive());
        Assert.assertEquals(contextActivator.callRequestScopeBean(), 1);
        contextActivator.deactivate();
        try {
            beanManager.getContext(RequestScoped.class).isActive();
            Assert.fail(ContextNotActiveException.class.getSimpleName() + " was not thrown !");
        } catch (ContextNotActiveException e) {
        }
    }
}
Also used : ContextNotActiveException(jakarta.enterprise.context.ContextNotActiveException) RequestScoped(jakarta.enterprise.context.RequestScoped) SeContainer(jakarta.enterprise.inject.se.SeContainer) BeanManager(jakarta.enterprise.inject.spi.BeanManager) SeContainerInitializer(jakarta.enterprise.inject.se.SeContainerInitializer) SpecAssertions(org.jboss.test.audit.annotations.SpecAssertions) Test(org.testng.annotations.Test)

Example 7 with BeanManager

use of jakarta.enterprise.inject.spi.BeanManager in project cdi-tck by eclipse-ee4j.

the class InjectionOfResourceTest method testProduceResourceProxy.

@Test
@SpecAssertions({ @SpecAssertion(section = RESOURCE_LIFECYCLE, id = "la"), @SpecAssertion(section = RESOURCE_LIFECYCLE, id = "ma"), @SpecAssertion(section = RESOURCE_LIFECYCLE, id = "o") })
public void testProduceResourceProxy() {
    Bean<BeanManager> beanManagerBean = getBeans(BeanManager.class, new AnnotationLiteral<Another>() {
    }).iterator().next();
    CreationalContext<BeanManager> beanManagerCc = getCurrentManager().createCreationalContext(beanManagerBean);
    BeanManager beanManager = beanManagerBean.create(beanManagerCc);
    assert beanManager != null;
}
Also used : BeanManager(jakarta.enterprise.inject.spi.BeanManager) SpecAssertions(org.jboss.test.audit.annotations.SpecAssertions) AbstractTest(org.jboss.cdi.tck.AbstractTest) Test(org.testng.annotations.Test)

Example 8 with BeanManager

use of jakarta.enterprise.inject.spi.BeanManager in project quarkus by quarkusio.

the class QuarkusRestClientBuilder method build.

public <T> T build(Class<T> aClass, ClientHttpEngine httpEngine) throws IllegalStateException, RestClientDefinitionException {
    RestClientListeners.get().forEach(listener -> listener.onNewClient(aClass, this));
    // Interface validity
    verifyInterface(aClass);
    if (baseURI == null) {
        throw new IllegalStateException("Neither baseUri nor baseUrl was specified");
    }
    // Provider annotations
    RegisterProvider[] providers = aClass.getAnnotationsByType(RegisterProvider.class);
    for (RegisterProvider provider : providers) {
        register(provider.value(), provider.priority());
    }
    // Default exception mapper
    if (!isMapperDisabled()) {
        register(DefaultResponseExceptionMapper.class);
    }
    builderDelegate.register(new ExceptionMapping(localProviderInstances), 1);
    ClassLoader classLoader = aClass.getClassLoader();
    T actualClient;
    ResteasyClient client;
    ResteasyClientBuilder resteasyClientBuilder = builderDelegate;
    if (this.proxyHost != null) {
        resteasyClientBuilder.defaultProxy(proxyHost, this.proxyPort);
    } else {
        String userProxyHost = Optional.ofNullable(getConfiguration().getProperty(PROPERTY_PROXY_HOST)).filter(String.class::isInstance).map(String.class::cast).orElse(null);
        Integer userProxyPort = Optional.ofNullable(getConfiguration().getProperty(PROPERTY_PROXY_PORT)).filter(Integer.class::isInstance).map(Integer.class::cast).orElse(null);
        // configuration of the builder has precedence over environment variables
        if (userProxyHost != null && userProxyPort != null) {
            String userProxyScheme = Optional.ofNullable(getConfiguration().getProperty(PROPERTY_PROXY_SCHEME)).filter(String.class::isInstance).map(String.class::cast).orElse(null);
            resteasyClientBuilder.defaultProxy(userProxyHost, userProxyPort, userProxyScheme);
        } else {
            selectHttpProxy().ifPresent(proxyAddress -> resteasyClientBuilder.defaultProxy(proxyAddress.getHostString(), proxyAddress.getPort()));
        }
    }
    if (this.executorService != null) {
        resteasyClientBuilder.executorService(this.executorService);
    } else {
        this.executorService = ContextualExecutors.threadPool();
        resteasyClientBuilder.executorService(executorService, !executorService.isManaged());
    }
    resteasyClientBuilder.register(DEFAULT_MEDIA_TYPE_FILTER);
    resteasyClientBuilder.register(METHOD_INJECTION_FILTER);
    resteasyClientBuilder.register(HEADERS_REQUEST_FILTER);
    register(new MpPublisherMessageBodyReader(executorService));
    resteasyClientBuilder.sslContext(sslContext);
    resteasyClientBuilder.trustStore(trustStore);
    resteasyClientBuilder.keyStore(keyStore, keystorePassword);
    resteasyClientBuilder.hostnameVerifier(hostnameVerifier);
    resteasyClientBuilder.setIsTrustSelfSignedCertificates(false);
    checkQueryParamStyleProperty(aClass);
    checkFollowRedirectProperty(aClass);
    resteasyClientBuilder.setFollowRedirects(followRedirect);
    if (readTimeout != null) {
        resteasyClientBuilder.readTimeout(readTimeout, readTimeoutUnit);
    }
    if (connectTimeout != null) {
        resteasyClientBuilder.connectTimeout(connectTimeout, connectTimeoutUnit);
    }
    if (httpEngine != null) {
        resteasyClientBuilder.httpEngine(httpEngine);
    } else {
        boolean registerEngine = false;
        for (Object p : getBuilderDelegate().getProviderFactory().getProviderInstances()) {
            if (p instanceof ClientHttpEngine) {
                resteasyClientBuilder.httpEngine((ClientHttpEngine) p);
                registerEngine = true;
                break;
            }
        }
        if (!registerEngine && useURLConnection()) {
            resteasyClientBuilder.httpEngine(new URLConnectionClientEngineBuilder().resteasyClientBuilder(resteasyClientBuilder).build());
            resteasyClientBuilder.sslContext(null);
            resteasyClientBuilder.trustStore(null);
            resteasyClientBuilder.keyStore(null, "");
        }
    }
    configureTrustAll(resteasyClientBuilder);
    // because otherwise Apache HTTP Client will try to initialize one and will fail
    if (ImageInfo.inImageRuntimeCode() && !SslContextConfiguration.isSslNativeEnabled()) {
        resteasyClientBuilder.sslContext(new DisabledSSLContext());
    }
    if (!invocationInterceptorFactories.isEmpty()) {
        resteasyClientBuilder.register(new AsyncInvocationInterceptorThreadContext(invocationInterceptorFactories));
    }
    client = resteasyClientBuilder.build();
    ((MpClient) client).setQueryParamStyle(queryParamStyle);
    client.register(AsyncInterceptorRxInvokerProvider.class);
    actualClient = client.target(baseURI).proxyBuilder(aClass).classloader(classLoader).defaultConsumes(MediaType.APPLICATION_JSON).defaultProduces(MediaType.APPLICATION_JSON).build();
    Class<?>[] interfaces = new Class<?>[3];
    interfaces[0] = aClass;
    interfaces[1] = RestClientProxy.class;
    interfaces[2] = Closeable.class;
    final BeanManager beanManager = getBeanManager();
    T proxy = (T) Proxy.newProxyInstance(classLoader, interfaces, new ProxyInvocationHandler(aClass, actualClient, getLocalProviderInstances(), client, beanManager));
    ClientHeaderProviders.registerForClass(aClass, proxy, beanManager);
    return proxy;
}
Also used : AsyncInvocationInterceptorThreadContext(org.jboss.resteasy.microprofile.client.async.AsyncInvocationInterceptorThreadContext) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) ResteasyClient(org.jboss.resteasy.client.jaxrs.ResteasyClient) MpClient(org.jboss.resteasy.microprofile.client.impl.MpClient) MpPublisherMessageBodyReader(org.jboss.resteasy.microprofile.client.publisher.MpPublisherMessageBodyReader) DisabledSSLContext(io.quarkus.runtime.graal.DisabledSSLContext) ProxyInvocationHandler(org.jboss.resteasy.microprofile.client.ProxyInvocationHandler) ClientHttpEngine(org.jboss.resteasy.client.jaxrs.ClientHttpEngine) ExceptionMapping(org.jboss.resteasy.microprofile.client.ExceptionMapping) PROPERTY_PROXY_PORT(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder.PROPERTY_PROXY_PORT) PROPERTY_PROXY_HOST(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder.PROPERTY_PROXY_HOST) RegisterProvider(org.eclipse.microprofile.rest.client.annotation.RegisterProvider) URLConnectionClientEngineBuilder(org.jboss.resteasy.client.jaxrs.engines.URLConnectionClientEngineBuilder) BeanManager(jakarta.enterprise.inject.spi.BeanManager)

Example 9 with BeanManager

use of jakarta.enterprise.inject.spi.BeanManager in project helidon by oracle.

the class JedisExtension method addBeans.

private void addBeans(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) throws IntrospectionException {
    if (event != null && beanManager != null) {
        for (final String instanceName : this.instanceNames) {
            if (instanceName != null) {
                final Set<Annotation> qualifiers;
                if (instanceName.equals("default")) {
                    qualifiers = Collections.singleton(Default.Literal.INSTANCE);
                } else {
                    qualifiers = Collections.singleton(NamedLiteral.of(instanceName));
                }
                event.<JedisPoolConfig>addBean().addTransitiveTypeClosure(JedisPoolConfig.class).scope(ApplicationScoped.class).addQualifiers(qualifiers).produceWith((instance) -> {
                    final JedisPoolConfig returnValue = new JedisPoolConfig();
                    try {
                        this.configure(instance.select(Config.class).get(), returnValue, JedisPoolConfig.class, instanceName);
                    } catch (final IntrospectionException | ReflectiveOperationException e) {
                        throw new CreationException(e.getMessage(), e);
                    }
                    return returnValue;
                });
                final Annotation[] qualifiersArray = qualifiers.toArray(new Annotation[qualifiers.size()]);
                event.<JedisPool>addBean().addTransitiveTypeClosure(JedisPool.class).scope(ApplicationScoped.class).addQualifiers(qualifiers).produceWith(instance -> {
                    return produceJedisPool(instance, instanceName, qualifiersArray);
                }).disposeWith((p, instance) -> p.destroy());
                event.<Jedis>addBean().addTransitiveTypeClosure(Jedis.class).scope(Dependent.class).addQualifiers(qualifiers).produceWith(instance -> instance.select(JedisPool.class, qualifiersArray).get().getResource()).disposeWith((j, instance) -> j.close());
            }
        }
    }
}
Also used : Dependent(jakarta.enterprise.context.Dependent) Observes(jakarta.enterprise.event.Observes) SSLParameters(javax.net.ssl.SSLParameters) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) ProcessInjectionPoint(jakarta.enterprise.inject.spi.ProcessInjectionPoint) Instance(jakarta.enterprise.inject.Instance) Default(jakarta.enterprise.inject.Default) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Introspector(java.beans.Introspector) BeanInfo(java.beans.BeanInfo) Map(java.util.Map) JedisPool(redis.clients.jedis.JedisPool) HostnameVerifier(javax.net.ssl.HostnameVerifier) Method(java.lang.reflect.Method) BeanManager(jakarta.enterprise.inject.spi.BeanManager) CreationException(jakarta.enterprise.inject.CreationException) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) NamedLiteral(jakarta.enterprise.inject.literal.NamedLiteral) Set(java.util.Set) Config(org.eclipse.microprofile.config.Config) IntrospectionException(java.beans.IntrospectionException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Objects(java.util.Objects) Protocol(redis.clients.jedis.Protocol) ParameterizedType(java.lang.reflect.ParameterizedType) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Type(java.lang.reflect.Type) Provider(jakarta.inject.Provider) Jedis(redis.clients.jedis.Jedis) PropertyDescriptor(java.beans.PropertyDescriptor) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig) Collections(java.util.Collections) Named(jakarta.inject.Named) IntrospectionException(java.beans.IntrospectionException) CreationException(jakarta.enterprise.inject.CreationException) Dependent(jakarta.enterprise.context.Dependent) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig) Annotation(java.lang.annotation.Annotation)

Example 10 with BeanManager

use of jakarta.enterprise.inject.spi.BeanManager in project helidon by oracle.

the class MainTest method testEvents.

@Test
void testEvents() {
    // build time
    HelidonContainer instance = HelidonContainer.instance();
    BeanManager beanManager = CDI.current().getBeanManager();
    TestExtension extension = beanManager.getExtension(TestExtension.class);
    assertThat(extension.runtimeConfig(), nullValue());
    assertThat(extension.events(), contains(TestExtension.BUILD_TIME_START, TestExtension.BUILD_TIME_END));
    Config config = ConfigProviderResolver.instance().getBuilder().withSources(MpConfigSources.create(Map.of("key", "value"))).build();
    ConfigProviderResolver.instance().registerConfig(config, Thread.currentThread().getContextClassLoader());
    instance.start();
    Object runtimeConfig = extension.runtimeConfig();
    assertThat(runtimeConfig, instanceOf(Config.class));
    Config mpConfig = (Config) runtimeConfig;
    try {
        mpConfig = ((Config) runtimeConfig).unwrap(Config.class);
    } catch (Exception ignored) {
    }
    assertThat(mpConfig, sameInstance(config));
    instance.shutdown();
    assertThat(extension.events(), is(List.of(TestExtension.BUILD_TIME_START, TestExtension.BUILD_TIME_END, TestExtension.RUNTIME_INIT, TestExtension.APPLICATION_INIT, TestExtension.APPLICATION_BEFORE_DESTROYED, TestExtension.APPLICATION_DESTROYED)));
}
Also used : Config(org.eclipse.microprofile.config.Config) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Test(org.junit.jupiter.api.Test)

Aggregations

BeanManager (jakarta.enterprise.inject.spi.BeanManager)129 Bean (jakarta.enterprise.inject.spi.Bean)29 Test (org.testng.annotations.Test)22 Test (org.junit.Test)15 IOException (java.io.IOException)10 Test (org.junit.jupiter.api.Test)10 ServiceDescriptor (io.helidon.grpc.server.ServiceDescriptor)9 ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)9 SeContainer (jakarta.enterprise.inject.se.SeContainer)9 FacesContext (jakarta.faces.context.FacesContext)9 NamingException (javax.naming.NamingException)9 TestContainer (org.jboss.arquillian.container.weld.embedded.mock.TestContainer)9 Map (java.util.Map)8 Set (java.util.Set)8 SpecAssertions (org.jboss.test.audit.annotations.SpecAssertions)8 Observes (jakarta.enterprise.event.Observes)7 Instance (jakarta.enterprise.inject.Instance)7 HashSet (java.util.HashSet)7 CreationalContext (jakarta.enterprise.context.spi.CreationalContext)6 SeContainerInitializer (jakarta.enterprise.inject.se.SeContainerInitializer)6