Search in sources :

Example 6 with Observes

use of jakarta.enterprise.event.Observes 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 7 with Observes

use of jakarta.enterprise.event.Observes in project vertx-sandbox by hantsy.

the class DataInitializer method run.

public void run(@Observes @Initialized(ApplicationScoped.class) Object o) {
    LOGGER.info("Data initialization is starting...");
    Tuple first = Tuple.of("Hello Quarkus", "My first post of Quarkus");
    Tuple second = Tuple.of("Hello Again, Quarkus", "My second post of Quarkus");
    client.withTransaction(conn -> conn.query("DELETE FROM posts").execute().flatMap(r -> conn.preparedQuery("INSERT INTO posts (title, content) VALUES ($1, $2)").executeBatch(List.of(first, second))).flatMap(r -> conn.query("SELECT * FROM posts").execute())).onSuccess(data -> StreamSupport.stream(data.spliterator(), true).forEach(row -> LOGGER.log(Level.INFO, "saved data:{0}", new Object[] { row.toJson() }))).onComplete(r -> {
        // client.close(); will block the application.
        LOGGER.info("Data initialization is done...");
    }).onFailure(throwable -> LOGGER.warning("Data initialization is failed:" + throwable.getMessage()));
}
Also used : List(java.util.List) Observes(jakarta.enterprise.event.Observes) RequiredArgsConstructor(lombok.RequiredArgsConstructor) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) PgPool(io.vertx.pgclient.PgPool) StreamSupport(java.util.stream.StreamSupport) Inject(jakarta.inject.Inject) Logger(java.util.logging.Logger) Initialized(jakarta.enterprise.context.Initialized) Tuple(io.vertx.sqlclient.Tuple) Level(java.util.logging.Level) Tuple(io.vertx.sqlclient.Tuple)

Example 8 with Observes

use of jakarta.enterprise.event.Observes in project helidon by oracle.

the class ConfigCdiExtension method registerConfigProducer.

/**
 * Register a config producer bean for each {@link org.eclipse.microprofile.config.inject.ConfigProperty} injection.
 *
 * @param abd event from CDI container
 */
private void registerConfigProducer(@Observes AfterBeanDiscovery abd) {
    // we also must support injection of Config itself
    abd.addBean().addTransitiveTypeClosure(org.eclipse.microprofile.config.Config.class).beanClass(org.eclipse.microprofile.config.Config.class).scope(ApplicationScoped.class).createWith(creationalContext -> new SerializableConfig());
    abd.addBean().addTransitiveTypeClosure(io.helidon.config.Config.class).beanClass(io.helidon.config.Config.class).scope(ApplicationScoped.class).createWith(creationalContext -> {
        Config config = ConfigProvider.getConfig();
        if (config instanceof io.helidon.config.Config) {
            return config;
        } else {
            return MpConfig.toHelidonConfig(config);
        }
    });
    Set<Type> types = ips.stream().map(InjectionPoint::getType).map(it -> {
        if (it instanceof Class) {
            Class<?> clazz = (Class<?>) it;
            if (clazz.isPrimitive()) {
                return REPLACED_TYPES.getOrDefault(clazz, clazz);
            }
        }
        return it;
    }).collect(Collectors.toSet());
    types.forEach(type -> {
        abd.addBean().addType(type).scope(Dependent.class).addQualifier(CONFIG_PROPERTY_LITERAL).produceWith(it -> produce(it.select(InjectionPoint.class).get()));
    });
    configBeans.values().forEach(beanDescriptor -> abd.addBean().addType(beanDescriptor.type()).addTransitiveTypeClosure(beanDescriptor.type()).qualifiers(ConfigProperties.Literal.NO_PREFIX).scope(Dependent.class).produceWith(it -> beanDescriptor.produce(it.select(InjectionPoint.class).get(), ConfigProvider.getConfig())));
}
Also used : Dependent(jakarta.enterprise.context.Dependent) ProcessObserverMethod(jakarta.enterprise.inject.spi.ProcessObserverMethod) MpConfig(io.helidon.config.mp.MpConfig) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) AfterDeploymentValidation(jakarta.enterprise.inject.spi.AfterDeploymentValidation) ConfigException(io.helidon.config.ConfigException) Bean(jakarta.enterprise.inject.spi.Bean) ProcessBean(jakarta.enterprise.inject.spi.ProcessBean) Matcher(java.util.regex.Matcher) Converter(org.eclipse.microprofile.config.spi.Converter) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Map(java.util.Map) Method(java.lang.reflect.Method) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Member(java.lang.reflect.Member) Set(java.util.Set) Config(org.eclipse.microprofile.config.Config) Logger(java.util.logging.Logger) ConfigValue(org.eclipse.microprofile.config.ConfigValue) Collectors(java.util.stream.Collectors) List(java.util.List) Type(java.lang.reflect.Type) WithAnnotations(jakarta.enterprise.inject.spi.WithAnnotations) ConfigProvider(org.eclipse.microprofile.config.ConfigProvider) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) AnnotatedType(jakarta.enterprise.inject.spi.AnnotatedType) NativeImageHelper(io.helidon.common.NativeImageHelper) Observes(jakarta.enterprise.event.Observes) OptionalDouble(java.util.OptionalDouble) HashMap(java.util.HashMap) Constructor(java.lang.reflect.Constructor) OptionalInt(java.util.OptionalInt) Supplier(java.util.function.Supplier) OptionalLong(java.util.OptionalLong) AnnotatedField(jakarta.enterprise.inject.spi.AnnotatedField) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) LinkedList(java.util.LinkedList) NoSuchElementException(java.util.NoSuchElementException) LinkedHashSet(java.util.LinkedHashSet) ConfigProperties(org.eclipse.microprofile.config.inject.ConfigProperties) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) CreationalContext(jakarta.enterprise.context.spi.CreationalContext) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Annotated(jakarta.enterprise.inject.spi.Annotated) ConfigProperty(org.eclipse.microprofile.config.inject.ConfigProperty) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) MpConfig(io.helidon.config.mp.MpConfig) Config(org.eclipse.microprofile.config.Config) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) Type(java.lang.reflect.Type) AnnotatedType(jakarta.enterprise.inject.spi.AnnotatedType) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType)

Example 9 with Observes

use of jakarta.enterprise.event.Observes in project helidon by oracle.

the class GrpcClientCdiExtension method afterBean.

/**
 * Process the previously captured {@link GrpcProxy} injection points.
 * <p>
 * For each {@link GrpcProxy} injection point we create a producer bean
 * for the required type.
 *
 * @param event the {@link AfterBeanDiscovery} event
 * @param beanManager the CDI bean manager
 */
public void afterBean(@Observes AfterBeanDiscovery event, BeanManager beanManager) {
    AnnotatedType<GrpcProxyProducer> producerType = beanManager.createAnnotatedType(GrpcProxyProducer.class);
    AnnotatedMethod<? super GrpcProxyProducer> producerMethod = producerType.getMethods().stream().filter(m -> m.isAnnotationPresent(GrpcProxy.class)).filter(m -> m.isAnnotationPresent(GrpcChannel.class)).findFirst().get();
    AnnotatedMethod<? super GrpcProxyProducer> inProcessMethod = producerType.getMethods().stream().filter(m -> m.isAnnotationPresent(GrpcProxy.class)).filter(m -> m.isAnnotationPresent(InProcessGrpcChannel.class)).findFirst().get();
    for (Type type : proxyTypes) {
        addProducerBean(event, beanManager, producerMethod, type);
    }
    for (Type type : inProcessProxyTypes) {
        addProducerBean(event, beanManager, inProcessMethod, type);
    }
}
Also used : InProcessGrpcChannel(io.helidon.microprofile.grpc.core.InProcessGrpcChannel) BeanAttributes(jakarta.enterprise.inject.spi.BeanAttributes) Observes(jakarta.enterprise.event.Observes) Set(java.util.Set) ProcessInjectionPoint(jakarta.enterprise.inject.spi.ProcessInjectionPoint) HashSet(java.util.HashSet) ProducerFactory(jakarta.enterprise.inject.spi.ProducerFactory) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Extension(jakarta.enterprise.inject.spi.Extension) Type(java.lang.reflect.Type) Annotated(jakarta.enterprise.inject.spi.Annotated) AnnotatedType(jakarta.enterprise.inject.spi.AnnotatedType) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Type(java.lang.reflect.Type) AnnotatedType(jakarta.enterprise.inject.spi.AnnotatedType) InProcessGrpcChannel(io.helidon.microprofile.grpc.core.InProcessGrpcChannel) InProcessGrpcChannel(io.helidon.microprofile.grpc.core.InProcessGrpcChannel)

Example 10 with Observes

use of jakarta.enterprise.event.Observes in project helidon by oracle.

the class CacheExtension method addBeans.

/*
     * create EmbeddedStorageManager beans
     */
private void addBeans(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) {
    if (event != null && beanManager != null) {
        if (!this.cacheBeans.isEmpty()) {
            for (final Descriptor entry : this.cacheBeans) {
                assert entry != null;
                // create Microstream Cache bean
                final Set<Annotation> qualifiers = entry.getAnnotations();
                assert qualifiers != null;
                assert !qualifiers.isEmpty();
                ParameterizedType types = entry.getTypes();
                GenericType<?> keyType = GenericType.create(types.getActualTypeArguments()[0]);
                GenericType<?> valueType = GenericType.create(types.getActualTypeArguments()[1]);
                String name = getName(qualifiers);
                event.<Cache<?, ?>>addBean().qualifiers(qualifiers).scope(ApplicationScoped.class).addTransitiveTypeClosure(Cache.class).addTypes(types).createWith(cc -> {
                    return CacheBuilder.create(name, getConfigNode(qualifiers), keyType.rawType(), valueType.rawType());
                }).destroyWith((cache, context) -> cache.close());
            }
        }
    }
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) Cache(one.microstream.cache.types.Cache) Observes(jakarta.enterprise.event.Observes) Config(io.helidon.config.Config) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) CacheBuilder(io.helidon.integrations.microstream.cache.CacheBuilder) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) Set(java.util.Set) ProcessInjectionPoint(jakarta.enterprise.inject.spi.ProcessInjectionPoint) GenericType(io.helidon.common.GenericType) HashSet(java.util.HashSet) Objects(java.util.Objects) ParameterizedType(java.lang.reflect.ParameterizedType) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Extension(jakarta.enterprise.inject.spi.Extension) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) Priority(jakarta.annotation.Priority) PLATFORM_BEFORE(jakarta.interceptor.Interceptor.Priority.PLATFORM_BEFORE) BeanManager(jakarta.enterprise.inject.spi.BeanManager) Annotation(java.lang.annotation.Annotation) Cache(one.microstream.cache.types.Cache)

Aggregations

Observes (jakarta.enterprise.event.Observes)11 ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)8 Extension (jakarta.enterprise.inject.spi.Extension)8 Set (java.util.Set)8 Priority (jakarta.annotation.Priority)7 AfterBeanDiscovery (jakarta.enterprise.inject.spi.AfterBeanDiscovery)7 Method (java.lang.reflect.Method)7 BeanManager (jakarta.enterprise.inject.spi.BeanManager)6 Annotation (java.lang.annotation.Annotation)6 HashSet (java.util.HashSet)6 Map (java.util.Map)6 Dependent (jakarta.enterprise.context.Dependent)5 Initialized (jakarta.enterprise.context.Initialized)5 LinkedList (java.util.LinkedList)5 Objects (java.util.Objects)5 Logger (java.util.logging.Logger)5 AnnotatedMethod (jakarta.enterprise.inject.spi.AnnotatedMethod)4 AnnotatedParameter (jakarta.enterprise.inject.spi.AnnotatedParameter)4 HashMap (java.util.HashMap)4 BeforeDestroyed (jakarta.enterprise.context.BeforeDestroyed)3