Search in sources :

Example 11 with BeanManager

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

the class GrpcServiceBuilder method addServiceMethod.

/**
 * Add a method to the {@link ServiceDescriptor.Builder}.
 * <p>
 * The method configuration will be determined by the annotations present on the
 * method and the method signature.
 *
 * @param builder  the {@link ServiceDescriptor.Builder} to add the method to
 * @param method   the {@link AnnotatedMethod} representing the method to add
 * @param beanManager  the {@link jakarta.enterprise.inject.spi.BeanManager} to use
 *                     to look-up CDI beans.
 */
@SuppressWarnings("unchecked")
private void addServiceMethod(ServiceDescriptor.Builder builder, AnnotatedMethod method, BeanManager beanManager) {
    GrpcMethod annotation = method.firstAnnotationOrMetaAnnotation(GrpcMethod.class);
    String name = determineMethodName(method, annotation);
    Supplier<?> instanceSupplier = instanceSupplier();
    MethodHandler handler = handlerSuppliers().stream().filter(supplier -> supplier.supplies(method)).findFirst().map(supplier -> supplier.get(name, method, instanceSupplier)).orElseThrow(() -> new IllegalArgumentException("Cannot locate a method handler supplier for method " + method));
    Class<?> requestType = handler.getRequestType();
    Class<?> responseType = handler.getResponseType();
    List<ServerInterceptor> interceptors = lookupMethodInterceptors(beanManager, method);
    GrpcInterceptors grpcInterceptors = method.getAnnotation(GrpcInterceptors.class);
    if (grpcInterceptors != null) {
        for (Class<?> interceptorClass : grpcInterceptors.value()) {
            ServerInterceptor interceptor = resolveInterceptor(beanManager, interceptorClass);
            if (interceptor != null) {
                interceptors.add(interceptor);
            }
        }
    }
    AnnotatedMethodConfigurer configurer = new AnnotatedMethodConfigurer(method, requestType, responseType, interceptors);
    switch(annotation.type()) {
        case UNARY:
            builder.unary(name, handler, configurer);
            break;
        case CLIENT_STREAMING:
            builder.clientStreaming(name, handler, configurer);
            break;
        case SERVER_STREAMING:
            builder.serverStreaming(name, handler, configurer);
            break;
        case BIDI_STREAMING:
            builder.bidirectional(name, handler, configurer);
            break;
        case UNKNOWN:
        default:
            LOGGER.log(Level.SEVERE, () -> "Unrecognized method type " + annotation.type());
    }
}
Also used : GrpcMethod(io.helidon.microprofile.grpc.core.GrpcMethod) Any(jakarta.enterprise.inject.Any) GrpcMethod(io.helidon.microprofile.grpc.core.GrpcMethod) Arrays(java.util.Arrays) Builder(io.helidon.common.Builder) GrpcInterceptors(io.helidon.microprofile.grpc.core.GrpcInterceptors) GrpcMarshaller(io.helidon.microprofile.grpc.core.GrpcMarshaller) AnnotatedMethodList(io.helidon.microprofile.grpc.core.AnnotatedMethodList) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) ServerInterceptor(io.grpc.ServerInterceptor) ContextKeys(io.helidon.grpc.core.ContextKeys) GrpcInterceptor(io.helidon.microprofile.grpc.core.GrpcInterceptor) BeanManager(jakarta.enterprise.inject.spi.BeanManager) GrpcInterceptorBinding(io.helidon.microprofile.grpc.core.GrpcInterceptorBinding) MethodDescriptor(io.helidon.grpc.server.MethodDescriptor) ServiceDescriptor(io.helidon.grpc.server.ServiceDescriptor) MethodHandler(io.helidon.grpc.core.MethodHandler) AnnotatedMethod(io.helidon.microprofile.grpc.core.AnnotatedMethod) ServiceLoader(java.util.ServiceLoader) HelidonServiceLoader(io.helidon.common.serviceloader.HelidonServiceLoader) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ModelHelper(io.helidon.microprofile.grpc.core.ModelHelper) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) Annotation(java.lang.annotation.Annotation) Instance(io.helidon.microprofile.grpc.core.Instance) Collections(java.util.Collections) AbstractServiceBuilder(io.helidon.microprofile.grpc.core.AbstractServiceBuilder) MethodHandler(io.helidon.grpc.core.MethodHandler) GrpcInterceptors(io.helidon.microprofile.grpc.core.GrpcInterceptors) ServerInterceptor(io.grpc.ServerInterceptor)

Example 12 with BeanManager

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

the class SchedulingCdiExtension method invoke.

void invoke(@Observes @Priority(PLATFORM_AFTER + 4000) @Initialized(ApplicationScoped.class) Object event, BeanManager beanManager) {
    ScheduledThreadPoolSupplier scheduledThreadPoolSupplier = ScheduledThreadPoolSupplier.builder().threadNamePrefix(schedulingConfig.get("thread-name-prefix").asString().orElse("scheduled-")).config(schedulingConfig).build();
    for (AnnotatedMethod<?> am : methods) {
        Class<?> aClass = am.getDeclaringType().getJavaClass();
        Bean<?> bean = beans.get(am);
        Object beanInstance = lookup(bean, beanManager);
        ScheduledExecutorService executorService = scheduledThreadPoolSupplier.get();
        executors.add(executorService);
        Method method = am.getJavaMember();
        if (!method.trySetAccessible()) {
            throw new DeploymentException(String.format("Scheduled method %s#%s is not accessible!", method.getDeclaringClass().getName(), method.getName()));
        }
        if (am.isAnnotationPresent(FixedRate.class) && am.isAnnotationPresent(Scheduled.class)) {
            throw new DeploymentException(String.format("Scheduled method %s#%s can have only one scheduling annotation.", method.getDeclaringClass().getName(), method.getName()));
        }
        Config methodConfig = config.get(aClass.getName() + "." + method.getName() + ".schedule");
        if (am.isAnnotationPresent(FixedRate.class)) {
            FixedRate annotation = am.getAnnotation(FixedRate.class);
            long initialDelay = methodConfig.get("initial-delay").asLong().orElseGet(annotation::initialDelay);
            long delay = methodConfig.get("delay").asLong().orElseGet(annotation::value);
            TimeUnit timeUnit = methodConfig.get("time-unit").asString().map(TimeUnit::valueOf).orElseGet(annotation::timeUnit);
            Task task = Scheduling.fixedRateBuilder().executor(executorService).initialDelay(initialDelay).delay(delay).timeUnit(timeUnit).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        } else if (am.isAnnotationPresent(Scheduled.class)) {
            Scheduled annotation = am.getAnnotation(Scheduled.class);
            String cron = methodConfig.get("cron").asString().orElseGet(() -> resolvePlaceholders(annotation.value(), config));
            boolean concurrent = methodConfig.get("concurrent").asBoolean().orElseGet(annotation::concurrentExecution);
            Task task = Scheduling.cronBuilder().executor(executorService).concurrentExecution(concurrent).expression(cron).task(inv -> invokeWithOptionalParam(beanInstance, method, inv)).build();
            LOGGER.log(Level.FINE, () -> String.format("Method %s#%s scheduled to be executed %s", aClass.getSimpleName(), method.getName(), task.description()));
        }
    }
}
Also used : Observes(jakarta.enterprise.event.Observes) Task(io.helidon.scheduling.Task) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) Invocation(io.helidon.scheduling.Invocation) ProcessManagedBean(jakarta.enterprise.inject.spi.ProcessManagedBean) Level(java.util.logging.Level) Bean(jakarta.enterprise.inject.spi.Bean) RuntimeStart(io.helidon.microprofile.cdi.RuntimeStart) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Matcher(java.util.regex.Matcher) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) Map(java.util.Map) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) PLATFORM_AFTER(jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Priority(jakarta.annotation.Priority) LinkedList(java.util.LinkedList) Method(java.lang.reflect.Method) Initialized(jakarta.enterprise.context.Initialized) ExecutorService(java.util.concurrent.ExecutorService) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Scheduling(io.helidon.scheduling.Scheduling) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) CreationalContext(jakarta.enterprise.context.spi.CreationalContext) Logger(java.util.logging.Logger) BeforeDestroyed(jakarta.enterprise.context.BeforeDestroyed) InvocationTargetException(java.lang.reflect.InvocationTargetException) TimeUnit(java.util.concurrent.TimeUnit) WithAnnotations(jakarta.enterprise.inject.spi.WithAnnotations) Queue(java.util.Queue) Pattern(java.util.regex.Pattern) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Task(io.helidon.scheduling.Task) Config(io.helidon.config.Config) ScheduledThreadPoolSupplier(io.helidon.common.configurable.ScheduledThreadPoolSupplier) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Method(java.lang.reflect.Method) TimeUnit(java.util.concurrent.TimeUnit) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException)

Example 13 with BeanManager

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

the class HelidonTestNGListener method injectTestToCdi.

/*
     * Helper method to inject TestNG initialized classes into CDI Container.
     */
private <T> void injectTestToCdi(Object bean, final Class<T> clazz) {
    BeanManager beanManager = CDI.current().getBeanManager();
    AnnotatedType<T> annotatedType = beanManager.createAnnotatedType(clazz);
    InjectionTargetFactory<T> injectionTargetFactory = beanManager.getInjectionTargetFactory(annotatedType);
    InjectionTarget<T> injectionTarget = injectionTargetFactory.createInjectionTarget(null);
    CreationalContext<T> creationalContext = beanManager.createCreationalContext(null);
    injectionTarget.inject((T) bean, creationalContext);
}
Also used : BeanManager(jakarta.enterprise.inject.spi.BeanManager)

Example 14 with BeanManager

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

the class AnnotatedServiceTest method descriptor.

private static ServiceDescriptor descriptor(Class<?> cls) {
    BeanManager beanManager = mock(BeanManager.class);
    Instance instance = mock(Instance.class);
    when(beanManager.createInstance()).thenReturn(instance);
    GrpcServiceBuilder builder = GrpcServiceBuilder.create(cls, beanManager);
    return builder.build();
}
Also used : Instance(jakarta.enterprise.inject.Instance) BeanManager(jakarta.enterprise.inject.spi.BeanManager)

Example 15 with BeanManager

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

the class InterceptorsTest method shouldUseSpecificServiceInterceptorBean.

@Test
public void shouldUseSpecificServiceInterceptorBean() {
    BeanManager beanManager = weld.getBeanManager();
    GrpcServiceBuilder builder = GrpcServiceBuilder.create(InterceptedServiceFive.class, beanManager);
    ServiceDescriptor descriptor = builder.build();
    PriorityBag<ServerInterceptor> interceptors = descriptor.interceptors();
    boolean hasInterceptorOne = interceptors.stream().anyMatch(interceptor -> ServerInterceptorOne.class.isAssignableFrom(interceptor.getClass()));
    boolean hasInterceptorTwo = interceptors.stream().anyMatch(interceptor -> ServerInterceptorTwo.class.isAssignableFrom(interceptor.getClass()));
    assertThat(hasInterceptorOne, is(true));
    assertThat(hasInterceptorTwo, is(true));
    assertThat(sizeOf(descriptor.method("foo").interceptors()), is(0));
}
Also used : ServiceDescriptor(io.helidon.grpc.server.ServiceDescriptor) ServerInterceptor(io.grpc.ServerInterceptor) 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