Search in sources :

Example 1 with Observes

use of jakarta.enterprise.event.Observes in project core by weld.

the class ObserverMethodConfiguratorImpl method read.

@Override
public ObserverMethodConfigurator<T> read(Method method) {
    checkArgumentNotNull(method);
    Set<Parameter> eventParameters = Configurators.getAnnotatedParameters(method, Observes.class, ObservesAsync.class);
    checkEventParams(eventParameters, method);
    Parameter eventParameter = eventParameters.iterator().next();
    Observes observesAnnotation = eventParameter.getAnnotation(Observes.class);
    if (observesAnnotation != null) {
        reception(observesAnnotation.notifyObserver());
        transactionPhase(observesAnnotation.during());
    } else {
        reception(eventParameter.getAnnotation(ObservesAsync.class).notifyObserver());
    }
    Priority priority = method.getAnnotation(Priority.class);
    if (priority != null) {
        priority(priority.value());
    }
    beanClass(eventParameter.getDeclaringExecutable().getDeclaringClass());
    observedType(eventParameter.getType());
    qualifiers(Configurators.getQualifiers(eventParameter));
    return this;
}
Also used : Observes(jakarta.enterprise.event.Observes) Priority(jakarta.annotation.Priority) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Parameter(java.lang.reflect.Parameter)

Example 2 with Observes

use of jakarta.enterprise.event.Observes in project core by weld.

the class ObserverMethodConfiguratorImpl method read.

@Override
public ObserverMethodConfigurator<T> read(AnnotatedMethod<?> method) {
    checkArgumentNotNull(method);
    Set<AnnotatedParameter<?>> eventParameters = method.getParameters().stream().filter((p) -> p.isAnnotationPresent(Observes.class) || p.isAnnotationPresent(ObservesAsync.class)).collect(Collectors.toSet());
    checkEventParams(eventParameters, method.getJavaMember());
    AnnotatedParameter<?> eventParameter = eventParameters.iterator().next();
    Observes observesAnnotation = eventParameter.getAnnotation(Observes.class);
    if (observesAnnotation != null) {
        reception(observesAnnotation.notifyObserver());
        transactionPhase(observesAnnotation.during());
        async(false);
    } else {
        reception(eventParameter.getAnnotation(ObservesAsync.class).notifyObserver());
        async(true);
    }
    Priority priority = method.getAnnotation(Priority.class);
    if (priority != null) {
        priority(priority.value());
    }
    beanClass(eventParameter.getDeclaringCallable().getDeclaringType().getJavaClass());
    observedType(eventParameter.getBaseType());
    qualifiers(Configurators.getQualifiers(eventParameter));
    return this;
}
Also used : EventLogger(org.jboss.weld.logging.EventLogger) Observes(jakarta.enterprise.event.Observes) ObserverMethodConfigurator(jakarta.enterprise.inject.spi.configurator.ObserverMethodConfigurator) Preconditions.checkArgumentNotNull(org.jboss.weld.util.Preconditions.checkArgumentNotNull) Reception(jakarta.enterprise.event.Reception) ObservesAsync(jakarta.enterprise.event.ObservesAsync) HashSet(java.util.HashSet) AnnotatedMethod(jakarta.enterprise.inject.spi.AnnotatedMethod) Extension(jakarta.enterprise.inject.spi.Extension) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Parameter(java.lang.reflect.Parameter) ObserverException(jakarta.enterprise.event.ObserverException) Formats(org.jboss.weld.util.reflection.Formats) Priority(jakarta.annotation.Priority) Method(java.lang.reflect.Method) TransactionPhase(jakarta.enterprise.event.TransactionPhase) SyntheticObserverMethod(org.jboss.weld.event.SyntheticObserverMethod) CovariantTypes(org.jboss.weld.resolution.CovariantTypes) ImmutableSet(org.jboss.weld.util.collections.ImmutableSet) Set(java.util.Set) ObserverMethod(jakarta.enterprise.inject.spi.ObserverMethod) Collectors(java.util.stream.Collectors) EventContext(jakarta.enterprise.inject.spi.EventContext) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) ObservesAsync(jakarta.enterprise.event.ObservesAsync) AnnotatedParameter(jakarta.enterprise.inject.spi.AnnotatedParameter) Observes(jakarta.enterprise.event.Observes) Priority(jakarta.annotation.Priority)

Example 3 with Observes

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

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

the class MicronautCdiExtension method afterBeanDiscovery.

/**
 * Add all (not yet added) Micronaut beans for injection as long as they are singletons.
 *
 * @param event CDI event
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
void afterBeanDiscovery(@Priority(PLATFORM_BEFORE) @Observes AfterBeanDiscovery event) {
    event.addBean().addType(ApplicationContext.class).id(MICRONAUT_BEAN_PREFIX + "context").scope(ApplicationScoped.class).produceWith(instance -> micronautContext.get());
    // add the remaining Micronaut beans
    for (var entry : unprocessedBeans.entrySet()) {
        Class<?> beanType = entry.getKey();
        List<MicronautBean> beans = entry.getValue();
        List<? extends BeanDefinitionReference<?>> refs = List.of();
        if (beans.size() > 1) {
            // first make sure these are singletons; if not, ignore
            refs = beans.stream().map(MicronautBean::definitionRef).filter(it -> !it.getBeanType().getName().endsWith("$Intercepted")).filter(BeanDefinitionReference::isSingleton).collect(Collectors.toList());
        }
        // primary
        event.addBean().addType(beanType).id(MICRONAUT_BEAN_PREFIX + beanType.getName()).scope(Dependent.class).produceWith(instance -> micronautContext.get().getBean(beanType));
        if (refs.size() > 1) {
            // we must care about qualifiers
            for (var ref : refs) {
                AnnotationMetadata annotationMetadata = ref.getAnnotationMetadata();
                List<Class<? extends Annotation>> qualifiers = annotationMetadata.getAnnotationTypesByStereotype(Qualifier.class);
                Annotation[] synthesized = new Annotation[qualifiers.size()];
                io.micronaut.context.Qualifier[] mq = new io.micronaut.context.Qualifier[qualifiers.size()];
                for (int i = 0; i < qualifiers.size(); i++) {
                    Annotation annotation = annotationMetadata.synthesize(qualifiers.get(i));
                    synthesized[i] = annotation;
                    if (annotation != null) {
                        mq[i] = Qualifiers.byAnnotation(annotation);
                    }
                }
                io.micronaut.context.Qualifier composite = Qualifiers.byQualifiers(mq);
                BeanConfigurator<Object> newBean = event.addBean().addType(beanType).id(MICRONAUT_BEAN_PREFIX + ref.getBeanDefinitionName()).scope(Dependent.class).produceWith(instance -> micronautContext.get().getBean(beanType, composite));
                for (Annotation annotation : synthesized) {
                    newBean.addQualifier(annotation);
                }
            }
        }
    }
    unprocessedBeans.clear();
}
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) Dependent(jakarta.enterprise.context.Dependent) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) AnnotationMetadata(io.micronaut.core.annotation.AnnotationMetadata) Annotation(java.lang.annotation.Annotation) ApplicationContext(io.micronaut.context.ApplicationContext) BeanDefinitionReference(io.micronaut.inject.BeanDefinitionReference) Qualifier(jakarta.inject.Qualifier)

Example 5 with Observes

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

the class JedisExtension method addBeans.

private void addBeans(@Observes final AfterBeanDiscovery event, final BeanManager beanManager) throws IntrospectionException {
    if (event != null && beanManager != null) {
        for (final String instanceName : this.instanceNames) {
            if (instanceName != null) {
                final Set<Annotation> qualifiers;
                if (instanceName.equals("default")) {
                    qualifiers = Collections.singleton(Default.Literal.INSTANCE);
                } else {
                    qualifiers = Collections.singleton(NamedLiteral.of(instanceName));
                }
                event.<JedisPoolConfig>addBean().addTransitiveTypeClosure(JedisPoolConfig.class).scope(ApplicationScoped.class).addQualifiers(qualifiers).produceWith((instance) -> {
                    final JedisPoolConfig returnValue = new JedisPoolConfig();
                    try {
                        this.configure(instance.select(Config.class).get(), returnValue, JedisPoolConfig.class, instanceName);
                    } catch (final IntrospectionException | ReflectiveOperationException e) {
                        throw new CreationException(e.getMessage(), e);
                    }
                    return returnValue;
                });
                final Annotation[] qualifiersArray = qualifiers.toArray(new Annotation[qualifiers.size()]);
                event.<JedisPool>addBean().addTransitiveTypeClosure(JedisPool.class).scope(ApplicationScoped.class).addQualifiers(qualifiers).produceWith(instance -> {
                    return produceJedisPool(instance, instanceName, qualifiersArray);
                }).disposeWith((p, instance) -> p.destroy());
                event.<Jedis>addBean().addTransitiveTypeClosure(Jedis.class).scope(Dependent.class).addQualifiers(qualifiers).produceWith(instance -> instance.select(JedisPool.class, qualifiersArray).get().getResource()).disposeWith((j, instance) -> j.close());
            }
        }
    }
}
Also used : Dependent(jakarta.enterprise.context.Dependent) Observes(jakarta.enterprise.event.Observes) SSLParameters(javax.net.ssl.SSLParameters) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) HashMap(java.util.HashMap) ProcessInjectionPoint(jakarta.enterprise.inject.spi.ProcessInjectionPoint) Instance(jakarta.enterprise.inject.Instance) Default(jakarta.enterprise.inject.Default) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Introspector(java.beans.Introspector) BeanInfo(java.beans.BeanInfo) Map(java.util.Map) JedisPool(redis.clients.jedis.JedisPool) HostnameVerifier(javax.net.ssl.HostnameVerifier) Method(java.lang.reflect.Method) BeanManager(jakarta.enterprise.inject.spi.BeanManager) CreationException(jakarta.enterprise.inject.CreationException) InjectionPoint(jakarta.enterprise.inject.spi.InjectionPoint) NamedLiteral(jakarta.enterprise.inject.literal.NamedLiteral) Set(java.util.Set) Config(org.eclipse.microprofile.config.Config) IntrospectionException(java.beans.IntrospectionException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Objects(java.util.Objects) Protocol(redis.clients.jedis.Protocol) ParameterizedType(java.lang.reflect.ParameterizedType) AfterBeanDiscovery(jakarta.enterprise.inject.spi.AfterBeanDiscovery) Type(java.lang.reflect.Type) Provider(jakarta.inject.Provider) Jedis(redis.clients.jedis.Jedis) PropertyDescriptor(java.beans.PropertyDescriptor) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig) Collections(java.util.Collections) Named(jakarta.inject.Named) IntrospectionException(java.beans.IntrospectionException) CreationException(jakarta.enterprise.inject.CreationException) Dependent(jakarta.enterprise.context.Dependent) ApplicationScoped(jakarta.enterprise.context.ApplicationScoped) JedisPoolConfig(redis.clients.jedis.JedisPoolConfig) Annotation(java.lang.annotation.Annotation)

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