Search in sources :

Example 31 with Instance

use of javax.enterprise.inject.Instance in project quarkus by quarkusio.

the class RestClientsContainer method getClientData.

/**
 * Used in Dev UI
 *
 * @return info about exposed clients
 */
public RestClientData getClientData() {
    ClientContext context = CLIENT_CONTEXT_RESOLVER.resolve(Thread.currentThread().getContextClassLoader());
    ClientProxies.ClientData clientData = context.getClientProxies().getClientData();
    List<RestClientInfo> restClients = new ArrayList<>();
    List<PossibleRestClientInfo> possibleRestClients = new ArrayList<>();
    for (Class<?> clientClass : clientData.clientClasses) {
        Instance<?> select = injectableClients.select(clientClass);
        String interfaceName = clientClass.getName();
        if (select.isResolvable()) {
            String configKey = RestClientRecorder.getConfigKeys().get(interfaceName);
            if (configKey == null) {
                configKey = String.format("\"%s\"", interfaceName);
            }
            restClients.add(new RestClientInfo(interfaceName, true, configKey));
        } else {
            restClients.add(new RestClientInfo(interfaceName, false, null));
        }
    }
    restClients.sort(Comparator.comparing(info -> info.interfaceClass));
    for (Map.Entry<Class<?>, String> clientEntry : clientData.failures.entrySet()) {
        possibleRestClients.add(new PossibleRestClientInfo(clientEntry.getKey().getName(), clientEntry.getValue()));
    }
    possibleRestClients.sort(Comparator.comparing(info -> info.interfaceClass));
    return new RestClientData(restClients, possibleRestClients);
}
Also used : ClientProxies(org.jboss.resteasy.reactive.client.impl.ClientProxies) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) ClientContextResolver(org.jboss.resteasy.reactive.client.spi.ClientContextResolver) RestClientRecorder(io.quarkus.rest.client.reactive.runtime.RestClientRecorder) Singleton(javax.inject.Singleton) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) List(java.util.List) Unremovable(io.quarkus.arc.Unremovable) IfBuildProfile(io.quarkus.arc.profile.IfBuildProfile) Map(java.util.Map) Comparator(java.util.Comparator) ClientContext(org.jboss.resteasy.reactive.client.spi.ClientContext) Instance(javax.enterprise.inject.Instance) ClientProxies(org.jboss.resteasy.reactive.client.impl.ClientProxies) ClientContext(org.jboss.resteasy.reactive.client.spi.ClientContext) ArrayList(java.util.ArrayList) Map(java.util.Map)

Example 32 with Instance

use of javax.enterprise.inject.Instance in project quarkus by quarkusio.

the class WebsocketCoreRecorder method createServerContainer.

public RuntimeValue<ServerWebSocketContainer> createServerContainer(BeanContainer beanContainer, RuntimeValue<WebSocketDeploymentInfo> infoVal, ServerWebSocketContainerFactory serverContainerFactory) throws DeploymentException {
    WebSocketDeploymentInfo info = infoVal.getValue();
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    ManagedContext requestContext = Arc.container().requestContext();
    if (serverContainerFactory == null) {
        serverContainerFactory = ServerWebSocketContainer::new;
    }
    Instance<CurrentIdentityAssociation> currentIdentityAssociation = Arc.container().select(CurrentIdentityAssociation.class);
    ServerWebSocketContainer container = serverContainerFactory.create(new ObjectIntrospecter() {

        @Override
        public <T> ObjectFactory<T> createInstanceFactory(Class<T> clazz) {
            BeanContainer.Factory<T> factory = beanContainer.instanceFactory(clazz);
            return new ObjectFactory<T>() {

                @Override
                public ObjectHandle<T> createInstance() {
                    BeanContainer.Instance<T> instance = factory.create();
                    return new ObjectHandle<T>() {

                        @Override
                        public T getInstance() {
                            return instance.get();
                        }

                        @Override
                        public void release() {
                            instance.close();
                        }
                    };
                }
            };
        }
    }, Thread.currentThread().getContextClassLoader(), new Supplier<EventLoopGroup>() {

        @Override
        public EventLoopGroup get() {
            return ((VertxInternal) VertxCoreRecorder.getVertx().get()).getEventLoopGroup();
        }
    }, Collections.singletonList(new ContextSetupHandler() {

        @Override
        public <T, C> Action<T, C> create(Action<T, C> action) {
            return new Action<T, C>() {

                CurrentIdentityAssociation getCurrentIdentityAssociation() {
                    if (currentIdentityAssociation.isResolvable()) {
                        return currentIdentityAssociation.get();
                    }
                    return null;
                }

                @Override
                public T call(C context, UndertowSession session) throws Exception {
                    ClassLoader old = Thread.currentThread().getContextClassLoader();
                    Thread.currentThread().setContextClassLoader(cl);
                    boolean required = !requestContext.isActive();
                    if (required) {
                        requestContext.activate();
                        Principal p = session.getUserPrincipal();
                        if (p instanceof WebSocketPrincipal) {
                            var current = getCurrentIdentityAssociation();
                            if (current != null) {
                                current.setIdentity(((WebSocketPrincipal) p).getSecurityIdentity());
                            }
                        }
                    }
                    try {
                        return action.call(context, session);
                    } finally {
                        try {
                            if (required) {
                                requestContext.terminate();
                            }
                        } finally {
                            Thread.currentThread().setContextClassLoader(old);
                        }
                    }
                }
            };
        }
    }), info.isDispatchToWorkerThread(), null, null, info.getExecutor(), Collections.emptyList(), info.getMaxFrameSize(), new Supplier<Principal>() {

        @Override
        public Principal get() {
            if (currentIdentityAssociation.isResolvable()) {
                return new WebSocketPrincipal(currentIdentityAssociation.get().getIdentity());
            }
            return null;
        }
    });
    for (Class<?> i : info.getAnnotatedEndpoints()) {
        container.addEndpoint(i);
    }
    for (ServerEndpointConfig i : info.getProgramaticEndpoints()) {
        container.addEndpoint(i);
    }
    UndertowContainerProvider.setDefaultContainer(container);
    return new RuntimeValue<>(container);
}
Also used : ContextSetupHandler(io.undertow.websockets.util.ContextSetupHandler) Instance(javax.enterprise.inject.Instance) ObjectFactory(io.undertow.websockets.util.ObjectFactory) ObjectFactory(io.undertow.websockets.util.ObjectFactory) ServerWebSocketContainer(io.undertow.websockets.ServerWebSocketContainer) ServerEndpointConfig(javax.websocket.server.ServerEndpointConfig) ObjectIntrospecter(io.undertow.websockets.util.ObjectIntrospecter) WebSocketDeploymentInfo(io.undertow.websockets.WebSocketDeploymentInfo) ObjectHandle(io.undertow.websockets.util.ObjectHandle) EventLoopGroup(io.netty.channel.EventLoopGroup) CurrentIdentityAssociation(io.quarkus.security.identity.CurrentIdentityAssociation) ManagedContext(io.quarkus.arc.ManagedContext) UndertowSession(io.undertow.websockets.UndertowSession) RuntimeValue(io.quarkus.runtime.RuntimeValue) Principal(java.security.Principal)

Example 33 with Instance

use of javax.enterprise.inject.Instance in project quarkus by quarkusio.

the class InjectionPointMetadataTest method testInjectionPointMetadata.

@SuppressWarnings({ "unchecked", "rawtypes", "serial" })
@Test
public void testInjectionPointMetadata() {
    ArcContainer arc = Arc.container();
    Controller controller = arc.instance(Controller.class).get();
    // Field
    InjectionPoint injectionPoint = controller.controlled.injectionPoint;
    assertNotNull(injectionPoint);
    assertEquals(Controlled.class, injectionPoint.getType());
    Set<Annotation> qualifiers = injectionPoint.getQualifiers();
    assertEquals(1, qualifiers.size());
    assertEquals(Default.class, qualifiers.iterator().next().annotationType());
    Bean<?> bean = injectionPoint.getBean();
    assertNotNull(bean);
    assertTrue(bean.getTypes().stream().anyMatch(t -> t.equals(Controller.class)));
    assertNotNull(injectionPoint.getAnnotated());
    assertTrue(injectionPoint.getAnnotated() instanceof AnnotatedField);
    AnnotatedField<Controller> annotatedField = (AnnotatedField<Controller>) injectionPoint.getAnnotated();
    assertEquals("controlled", annotatedField.getJavaMember().getName());
    assertEquals(Controlled.class, annotatedField.getBaseType());
    assertEquals(2, annotatedField.getAnnotations().size());
    assertTrue(annotatedField.isAnnotationPresent(Inject.class));
    assertTrue(annotatedField.isAnnotationPresent(FooAnnotation.class));
    assertFalse(annotatedField.isAnnotationPresent(Deprecated.class));
    assertTrue(annotatedField.getAnnotation(Singleton.class) == null);
    assertTrue(annotatedField.getAnnotations(Singleton.class).isEmpty());
    // Method
    InjectionPoint methodInjectionPoint = controller.controlledMethod.injectionPoint;
    assertNotNull(methodInjectionPoint);
    assertEquals(Controlled.class, methodInjectionPoint.getType());
    assertTrue(methodInjectionPoint.getAnnotated() instanceof AnnotatedParameter);
    assertEquals(bean, methodInjectionPoint.getBean());
    AnnotatedParameter<Controller> methodParam = (AnnotatedParameter<Controller>) methodInjectionPoint.getAnnotated();
    assertEquals(0, methodParam.getPosition());
    assertEquals(Controller.class, methodParam.getDeclaringCallable().getJavaMember().getDeclaringClass());
    assertEquals("setControlled", methodParam.getDeclaringCallable().getJavaMember().getName());
    // Constructor
    InjectionPoint ctorInjectionPoint = controller.controlledCtor.injectionPoint;
    assertNotNull(ctorInjectionPoint);
    assertEquals(Controlled.class, ctorInjectionPoint.getType());
    assertTrue(ctorInjectionPoint.getAnnotated() instanceof AnnotatedParameter);
    assertEquals(bean, ctorInjectionPoint.getBean());
    AnnotatedParameter<Controller> ctorParam = (AnnotatedParameter<Controller>) ctorInjectionPoint.getAnnotated();
    assertEquals(1, ctorParam.getPosition());
    assertTrue(ctorParam.isAnnotationPresent(Singleton.class));
    assertTrue(ctorParam.getAnnotation(Singleton.class) != null);
    assertTrue(!ctorParam.getAnnotations(Singleton.class).isEmpty());
    assertEquals(1, ctorParam.getAnnotations().size());
    assertTrue(ctorParam.getDeclaringCallable() instanceof AnnotatedConstructor);
    assertEquals(Controller.class, ctorParam.getDeclaringCallable().getJavaMember().getDeclaringClass());
    // Instance
    InjectionPoint instanceInjectionPoint = controller.instanceControlled.get().injectionPoint;
    assertNotNull(instanceInjectionPoint);
    assertEquals(Controlled.class, instanceInjectionPoint.getType());
    qualifiers = instanceInjectionPoint.getQualifiers();
    assertEquals(1, qualifiers.size());
    assertEquals(Default.class, qualifiers.iterator().next().annotationType());
    bean = instanceInjectionPoint.getBean();
    assertNotNull(bean);
    assertTrue(bean.getTypes().stream().anyMatch(t -> t.equals(Controller.class)));
    assertNotNull(instanceInjectionPoint.getAnnotated());
    assertTrue(instanceInjectionPoint.getAnnotated() instanceof AnnotatedField);
    annotatedField = (AnnotatedField) instanceInjectionPoint.getAnnotated();
    assertEquals("instanceControlled", annotatedField.getJavaMember().getName());
    assertEquals(new TypeLiteral<Instance<Controlled>>() {
    }.getType(), annotatedField.getBaseType());
    assertTrue(annotatedField.isAnnotationPresent(Inject.class));
    assertTrue(annotatedField.getAnnotation(Singleton.class) == null);
    assertTrue(annotatedField.getAnnotations(Singleton.class).isEmpty());
    assertEquals(1, annotatedField.getAnnotations().size());
}
Also used : Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Singleton(javax.inject.Singleton) AtomicReference(java.util.concurrent.atomic.AtomicReference) Retention(java.lang.annotation.Retention) Inject(javax.inject.Inject) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) TypeLiteral(javax.enterprise.util.TypeLiteral) RegisterExtension(org.junit.jupiter.api.extension.RegisterExtension) Observes(javax.enterprise.event.Observes) ArcContainer(io.quarkus.arc.ArcContainer) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Instance(javax.enterprise.inject.Instance) AnnotatedConstructor(javax.enterprise.inject.spi.AnnotatedConstructor) Arc(io.quarkus.arc.Arc) Default(javax.enterprise.inject.Default) ArcTestContainer(io.quarkus.arc.test.ArcTestContainer) Set(java.util.Set) AnnotatedParameter(javax.enterprise.inject.spi.AnnotatedParameter) AnnotatedField(javax.enterprise.inject.spi.AnnotatedField) Test(org.junit.jupiter.api.Test) Dependent(javax.enterprise.context.Dependent) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Annotation(java.lang.annotation.Annotation) Assertions(org.junit.jupiter.api.Assertions) Bean(javax.enterprise.inject.spi.Bean) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) BeanManager(javax.enterprise.inject.spi.BeanManager) RetentionPolicy(java.lang.annotation.RetentionPolicy) Inject(javax.inject.Inject) ArcContainer(io.quarkus.arc.ArcContainer) InjectionPoint(javax.enterprise.inject.spi.InjectionPoint) AnnotatedParameter(javax.enterprise.inject.spi.AnnotatedParameter) Annotation(java.lang.annotation.Annotation) AnnotatedConstructor(javax.enterprise.inject.spi.AnnotatedConstructor) TypeLiteral(javax.enterprise.util.TypeLiteral) Singleton(javax.inject.Singleton) AnnotatedField(javax.enterprise.inject.spi.AnnotatedField) Test(org.junit.jupiter.api.Test)

Example 34 with Instance

use of javax.enterprise.inject.Instance in project quarkus by quarkusio.

the class UndertowDeploymentRecorder method createDeployment.

public RuntimeValue<DeploymentInfo> createDeployment(String name, Set<String> knownFile, Set<String> knownDirectories, LaunchMode launchMode, ShutdownContext context, String mountPoint, String defaultCharset, String requestCharacterEncoding, String responseCharacterEncoding, boolean proactiveAuth, List<String> welcomeFiles) {
    DeploymentInfo d = new DeploymentInfo();
    d.setDefaultRequestEncoding(requestCharacterEncoding);
    d.setDefaultResponseEncoding(responseCharacterEncoding);
    d.setDefaultEncoding(defaultCharset);
    d.setSessionIdGenerator(new QuarkusSessionIdGenerator());
    d.setClassLoader(getClass().getClassLoader());
    d.setDeploymentName(name);
    d.setContextPath(mountPoint);
    d.setEagerFilterInit(true);
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl == null) {
        cl = new ClassLoader() {
        };
    }
    d.setClassLoader(cl);
    // TODO: we need better handling of static resources
    ResourceManager resourceManager;
    if (hotDeploymentResourcePaths == null) {
        resourceManager = new KnownPathResourceManager(knownFile, knownDirectories, new ClassPathResourceManager(d.getClassLoader(), "META-INF/resources"));
    } else {
        List<ResourceManager> managers = new ArrayList<>();
        for (Path i : hotDeploymentResourcePaths) {
            managers.add(new PathResourceManager(i));
        }
        managers.add(new ClassPathResourceManager(d.getClassLoader(), "META-INF/resources"));
        resourceManager = new DelegatingResourceManager(managers.toArray(new ResourceManager[0]));
    }
    if (launchMode == LaunchMode.NORMAL) {
        // todo: cache configuration
        resourceManager = new CachingResourceManager(1000, 0, null, resourceManager, 2000);
    }
    d.setResourceManager(resourceManager);
    if (welcomeFiles != null) {
        // if available, use welcome-files from web.xml
        d.addWelcomePages(welcomeFiles);
    } else {
        d.addWelcomePages("index.html", "index.htm");
    }
    d.addServlet(new ServletInfo(ServletPathMatches.DEFAULT_SERVLET_NAME, DefaultServlet.class).setAsyncSupported(true));
    for (HandlerWrapper i : hotDeploymentWrappers) {
        d.addOuterHandlerChainWrapper(i);
    }
    d.addAuthenticationMechanism("QUARKUS", new ImmediateAuthenticationMechanismFactory(QuarkusAuthMechanism.INSTANCE));
    d.setLoginConfig(new LoginConfig("QUARKUS", "QUARKUS"));
    context.addShutdownTask(new ShutdownContext.CloseRunnable(d.getResourceManager()));
    d.addNotificationReceiver(new NotificationReceiver() {

        @Override
        public void handleNotification(SecurityNotification notification) {
            if (notification.getEventType() == SecurityNotification.EventType.AUTHENTICATED) {
                QuarkusUndertowAccount account = (QuarkusUndertowAccount) notification.getAccount();
                Instance<CurrentIdentityAssociation> instance = CDI.current().select(CurrentIdentityAssociation.class);
                if (instance.isResolvable())
                    instance.get().setIdentity(account.getSecurityIdentity());
            }
        }
    });
    if (proactiveAuth) {
        d.setAuthenticationMode(AuthenticationMode.PRO_ACTIVE);
    } else {
        d.setAuthenticationMode(AuthenticationMode.CONSTRAINT_DRIVEN);
    }
    return new RuntimeValue<>(d);
}
Also used : Instance(javax.enterprise.inject.Instance) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) HandlerWrapper(io.undertow.server.HandlerWrapper) ClassPathResourceManager(io.undertow.server.handlers.resource.ClassPathResourceManager) PathResourceManager(io.undertow.server.handlers.resource.PathResourceManager) SecurityNotification(io.undertow.security.api.SecurityNotification) ServletInfo(io.undertow.servlet.api.ServletInfo) ShutdownContext(io.quarkus.runtime.ShutdownContext) LoginConfig(io.undertow.servlet.api.LoginConfig) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) Path(java.nio.file.Path) ImmediateAuthenticationMechanismFactory(io.undertow.util.ImmediateAuthenticationMechanismFactory) ClassPathResourceManager(io.undertow.server.handlers.resource.ClassPathResourceManager) PathResourceManager(io.undertow.server.handlers.resource.PathResourceManager) ResourceManager(io.undertow.server.handlers.resource.ResourceManager) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) NotificationReceiver(io.undertow.security.api.NotificationReceiver) CurrentIdentityAssociation(io.quarkus.security.identity.CurrentIdentityAssociation) RuntimeValue(io.quarkus.runtime.RuntimeValue) ClassPathResourceManager(io.undertow.server.handlers.resource.ClassPathResourceManager)

Example 35 with Instance

use of javax.enterprise.inject.Instance in project kogito-apps by kiegroup.

the class ExplanationServiceImplTest method init.

@BeforeEach
@SuppressWarnings("unchecked")
void init() {
    instance = mock(Instance.class);
    limeExplainerMock = mock(LimeExplainer.class);
    cfExplainerMock = mock(CounterfactualExplainer.class);
    PredictionProviderFactory predictionProviderFactory = mock(PredictionProviderFactory.class);
    explainerServiceHandlerRegistryMock = new LocalExplainerServiceHandlerRegistry(instance);
    limeExplainerServiceHandlerMock = spy(new LimeExplainerServiceHandler(limeExplainerMock, predictionProviderFactory));
    cfExplainerServiceHandlerMock = spy(new CounterfactualExplainerServiceHandler(cfExplainerMock, predictionProviderFactory, MAX_RUNNING_TIME_SECONDS));
    predictionProviderMock = mock(PredictionProvider.class);
    callbackMock = mock(Consumer.class);
    explanationService = new ExplanationServiceImpl(explainerServiceHandlerRegistryMock);
    when(predictionProviderFactory.createPredictionProvider(any(), any(), any())).thenReturn(predictionProviderMock);
}
Also used : LocalExplainerServiceHandlerRegistry(org.kie.kogito.explainability.handlers.LocalExplainerServiceHandlerRegistry) LimeExplainerServiceHandler(org.kie.kogito.explainability.handlers.LimeExplainerServiceHandler) Consumer(java.util.function.Consumer) Instance(javax.enterprise.inject.Instance) LimeExplainer(org.kie.kogito.explainability.local.lime.LimeExplainer) CounterfactualExplainer(org.kie.kogito.explainability.local.counterfactual.CounterfactualExplainer) PredictionProvider(org.kie.kogito.explainability.model.PredictionProvider) CounterfactualExplainerServiceHandler(org.kie.kogito.explainability.handlers.CounterfactualExplainerServiceHandler) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

Instance (javax.enterprise.inject.Instance)41 Test (org.junit.Test)14 List (java.util.List)12 Inject (javax.inject.Inject)12 ArrayList (java.util.ArrayList)11 Map (java.util.Map)10 Optional (java.util.Optional)10 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)9 Collectors (java.util.stream.Collectors)8 Logger (org.slf4j.Logger)6 LoggerFactory (org.slf4j.LoggerFactory)6 IOException (java.io.IOException)5 InjectionPoint (javax.enterprise.inject.spi.InjectionPoint)4 Path (javax.ws.rs.Path)4 MediaType (javax.ws.rs.core.MediaType)4 ProcessInstanceExporter (io.automatiko.engine.addons.process.management.export.ProcessInstanceExporter)3 ErrorInfoDTO (io.automatiko.engine.addons.process.management.model.ErrorInfoDTO)3 JsonExportedProcessInstance (io.automatiko.engine.addons.process.management.model.JsonExportedProcessInstance)3 ProcessDTO (io.automatiko.engine.addons.process.management.model.ProcessDTO)3 ProcessInstanceDTO (io.automatiko.engine.addons.process.management.model.ProcessInstanceDTO)3