Search in sources :

Example 1 with Initialized

use of jakarta.enterprise.context.Initialized 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 2 with Initialized

use of jakarta.enterprise.context.Initialized 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 3 with Initialized

use of jakarta.enterprise.context.Initialized in project helidon by oracle.

the class JwtAuthCdiExtension method registerProvider.

void registerProvider(@Observes @Initialized(ApplicationScoped.class) @Priority(PLATFORM_BEFORE + 5) Object event, BeanManager bm) {
    // Security extension to update and check builder
    SecurityCdiExtension security = bm.getExtension(SecurityCdiExtension.class);
    if (security.securityBuilder().hasProvider(JwtAuthProviderService.PROVIDER_NAME)) {
        return;
    }
    // JAX-RS extension to get to applications to see if we are needed
    JaxRsCdiExtension jaxrs = bm.getExtension(JaxRsCdiExtension.class);
    boolean notNeeded = jaxrs.applicationsToRun().stream().map(JaxRsApplication::applicationClass).flatMap(Optional::stream).map(clazz -> clazz.getAnnotation(LoginConfig.class)).filter(Objects::nonNull).map(LoginConfig::authMethod).noneMatch("MP-JWT"::equals);
    if (notNeeded) {
        return;
    }
    security.securityBuilder().addProvider(JwtAuthProvider.create(config), JwtAuthProviderService.PROVIDER_NAME);
}
Also used : Dependent(jakarta.enterprise.context.Dependent) Arrays(java.util.Arrays) JsonValue(jakarta.json.JsonValue) JaxRsCdiExtension(io.helidon.microprofile.server.JaxRsCdiExtension) AnnotationLiteral(jakarta.enterprise.util.AnnotationLiteral) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) AfterDeploymentValidation(jakarta.enterprise.inject.spi.AfterDeploymentValidation) RuntimeStart(io.helidon.microprofile.cdi.RuntimeStart) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) BeforeBeanDiscovery(jakarta.enterprise.inject.spi.BeforeBeanDiscovery) Map(java.util.Map) DeploymentException(jakarta.enterprise.inject.spi.DeploymentException) JsonObject(jakarta.json.JsonObject) Method(java.lang.reflect.Method) Initialized(jakarta.enterprise.context.Initialized) Claims(org.eclipse.microprofile.jwt.Claims) PLATFORM_BEFORE(jakarta.interceptor.Interceptor.Priority.PLATFORM_BEFORE) BeanManager(jakarta.enterprise.inject.spi.BeanManager) TYPE(java.lang.annotation.ElementType.TYPE) FIELD(java.lang.annotation.ElementType.FIELD) Member(java.lang.reflect.Member) Set(java.util.Set) Objects(java.util.Objects) List(java.util.List) JaxRsApplication(io.helidon.microprofile.server.JaxRsApplication) Type(java.lang.reflect.Type) Optional(java.util.Optional) JsonNumber(jakarta.json.JsonNumber) JsonArray(jakarta.json.JsonArray) SecurityCdiExtension(io.helidon.microprofile.security.SecurityCdiExtension) Observes(jakarta.enterprise.event.Observes) ClaimValue(org.eclipse.microprofile.jwt.ClaimValue) PARAMETER(java.lang.annotation.ElementType.PARAMETER) ProcessInjectionPoint(jakarta.enterprise.inject.spi.ProcessInjectionPoint) Constructor(java.lang.reflect.Constructor) Instance(jakarta.enterprise.inject.Instance) Retention(java.lang.annotation.Retention) LoginConfig(org.eclipse.microprofile.auth.LoginConfig) AnnotatedField(jakarta.enterprise.inject.spi.AnnotatedField) Extension(jakarta.enterprise.inject.spi.Extension) Priority(jakarta.annotation.Priority) LinkedList(java.util.LinkedList) Config(io.helidon.config.Config) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) Claim(org.eclipse.microprofile.jwt.Claim) Target(java.lang.annotation.Target) Nonbinding(jakarta.enterprise.util.Nonbinding) RUNTIME(java.lang.annotation.RetentionPolicy.RUNTIME) METHOD(java.lang.annotation.ElementType.METHOD) ParameterizedType(java.lang.reflect.ParameterizedType) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Annotated(jakarta.enterprise.inject.spi.Annotated) Provider(jakarta.inject.Provider) Qualifier(jakarta.inject.Qualifier) RequestScoped(jakarta.enterprise.context.RequestScoped) JsonString(jakarta.json.JsonString) Optional(java.util.Optional) SecurityCdiExtension(io.helidon.microprofile.security.SecurityCdiExtension) Objects(java.util.Objects) JaxRsCdiExtension(io.helidon.microprofile.server.JaxRsCdiExtension)

Aggregations

ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)3 Initialized (jakarta.enterprise.context.Initialized)3 Observes (jakarta.enterprise.event.Observes)3 Config (io.helidon.config.Config)2 RuntimeStart (io.helidon.microprofile.cdi.RuntimeStart)2 Priority (jakarta.annotation.Priority)2 BeanManager (jakarta.enterprise.inject.spi.BeanManager)2 DeploymentException (jakarta.enterprise.inject.spi.DeploymentException)2 Extension (jakarta.enterprise.inject.spi.Extension)2 List (java.util.List)2 ScheduledThreadPoolSupplier (io.helidon.common.configurable.ScheduledThreadPoolSupplier)1 SecurityCdiExtension (io.helidon.microprofile.security.SecurityCdiExtension)1 JaxRsApplication (io.helidon.microprofile.server.JaxRsApplication)1 JaxRsCdiExtension (io.helidon.microprofile.server.JaxRsCdiExtension)1 Invocation (io.helidon.scheduling.Invocation)1 Scheduling (io.helidon.scheduling.Scheduling)1 Task (io.helidon.scheduling.Task)1 PgPool (io.vertx.pgclient.PgPool)1 Tuple (io.vertx.sqlclient.Tuple)1 BeforeDestroyed (jakarta.enterprise.context.BeforeDestroyed)1