Search in sources :

Example 1 with PLATFORM_AFTER

use of jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER in project helidon by oracle.

the class MicronautCdiExtension method processTypes.

/**
 * Construct a list of Micronaut interceptors to execute on each CDI method.
 * In case a Micronaut bean definition is available for the CDI bean (which should be for application, as
 * the CDI annotation processor should be used, and it adds CDI beans as Micronaut beans), the information
 * is combined from Micronaut and CDI bean definitions.
 *
 * @param event CDI event
 */
@SuppressWarnings("unchecked")
void processTypes(@Priority(PLATFORM_AFTER) @Observes ProcessAnnotatedType<?> event) {
    Set<Class<?>> classInterceptors = new HashSet<>();
    Map<Method, Set<Class<?>>> allMethodInterceptors = new HashMap<>();
    List<MicronautBean> miBeans = unprocessedBeans.remove(event.getAnnotatedType().getJavaClass());
    if (miBeans != null && miBeans.size() > 0) {
        BeanDefinitionReference<?> miBean = findMicronautBeanDefinition(miBeans);
        // add all interceptors that are seen based on Micronaut
        findMicronautInterceptors(classInterceptors, allMethodInterceptors, miBean);
    }
    // find all annotations that have meta annotation Around and collect their Type list to add as interceptors
    addMicronautInterceptors(classInterceptors, event.getAnnotatedType().getAnnotations());
    // for each method, find the same (Around, collect Type), and add the interceptor binding for Micronaut interceptors
    // CDI interceptors will be automatic
    event.configureAnnotatedType().methods().forEach(method -> {
        Method javaMethod = method.getAnnotated().getJavaMember();
        Set<Class<?>> methodInterceptors = allMethodInterceptors.computeIfAbsent(javaMethod, it -> new HashSet<>());
        methodInterceptors.addAll(classInterceptors);
        addMicronautInterceptors(methodInterceptors, method.getAnnotated().getAnnotations());
        if (!methodInterceptors.isEmpty()) {
            // now I have a set of micronaut interceptors that are needed for this method
            method.add(MicronautIntercepted.Literal.INSTANCE);
            Set<Class<? extends MethodInterceptor<?, ?>>> interceptors = new HashSet<>();
            methodInterceptors.forEach(it -> interceptors.add((Class<? extends MethodInterceptor<?, ?>>) it));
            methods.computeIfAbsent(javaMethod, theMethod -> MethodInterceptorMetadata.create(method.getAnnotated(), executableMethodCache.get(theMethod))).addInterceptors(interceptors);
        }
    });
}
Also used : Dependent(jakarta.enterprise.context.Dependent) Around(io.micronaut.aop.Around) Observes(jakarta.enterprise.event.Observes) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutableMethod(io.micronaut.inject.ExecutableMethod) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) SoftServiceLoader(io.micronaut.core.io.service.SoftServiceLoader) ApplicationContext(io.micronaut.context.ApplicationContext) Extension(jakarta.enterprise.inject.spi.Extension) ProcessAnnotatedType(jakarta.enterprise.inject.spi.ProcessAnnotatedType) BeforeBeanDiscovery(jakarta.enterprise.inject.spi.BeforeBeanDiscovery) MethodInterceptor(io.micronaut.aop.MethodInterceptor) Map(java.util.Map) PLATFORM_AFTER(jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER) BeanConfigurator(jakarta.enterprise.inject.spi.configurator.BeanConfigurator) Priority(jakarta.annotation.Priority) LinkedList(java.util.LinkedList) Method(java.lang.reflect.Method) Initialized(jakarta.enterprise.context.Initialized) PLATFORM_BEFORE(jakarta.interceptor.Interceptor.Priority.PLATFORM_BEFORE) Iterator(java.util.Iterator) PropertySource(io.micronaut.context.env.PropertySource) Collection(java.util.Collection) ServiceDefinition(io.micronaut.core.io.service.ServiceDefinition) Set(java.util.Set) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) AdvisedBeanType(io.micronaut.inject.AdvisedBeanType) Config(org.eclipse.microprofile.config.Config) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) BeforeDestroyed(jakarta.enterprise.context.BeforeDestroyed) Objects(java.util.Objects) List(java.util.List) Type(io.micronaut.context.annotation.Type) Stream(java.util.stream.Stream) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Annotation(java.lang.annotation.Annotation) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) BeanDefinition(io.micronaut.inject.BeanDefinition) Comparator(java.util.Comparator) Qualifier(jakarta.inject.Qualifier) BeanDefinitionReference(io.micronaut.inject.BeanDefinitionReference) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) ExecutableMethod(io.micronaut.inject.ExecutableMethod) Method(java.lang.reflect.Method) MethodInterceptor(io.micronaut.aop.MethodInterceptor) HashSet(java.util.HashSet)

Example 2 with PLATFORM_AFTER

use of jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER 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)

Aggregations

Priority (jakarta.annotation.Priority)2 ApplicationScoped (jakarta.enterprise.context.ApplicationScoped)2 BeforeDestroyed (jakarta.enterprise.context.BeforeDestroyed)2 Initialized (jakarta.enterprise.context.Initialized)2 Observes (jakarta.enterprise.event.Observes)2 Extension (jakarta.enterprise.inject.spi.Extension)2 ProcessAnnotatedType (jakarta.enterprise.inject.spi.ProcessAnnotatedType)2 PLATFORM_AFTER (jakarta.interceptor.Interceptor.Priority.PLATFORM_AFTER)2 Method (java.lang.reflect.Method)2 HashMap (java.util.HashMap)2 LinkedList (java.util.LinkedList)2 Map (java.util.Map)2 Level (java.util.logging.Level)2 Logger (java.util.logging.Logger)2 ScheduledThreadPoolSupplier (io.helidon.common.configurable.ScheduledThreadPoolSupplier)1 Config (io.helidon.config.Config)1 RuntimeStart (io.helidon.microprofile.cdi.RuntimeStart)1 Invocation (io.helidon.scheduling.Invocation)1 Scheduling (io.helidon.scheduling.Scheduling)1 Task (io.helidon.scheduling.Task)1