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()));
}
}
}
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()));
}
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())));
}
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);
}
}
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());
}
}
}
}
Aggregations