Search in sources :

Example 1 with ObserverMethod

use of javax.enterprise.inject.spi.ObserverMethod in project tomee by apache.

the class CdiPlugin method defineSessionBean.

@Override
public <T> Bean<T> defineSessionBean(final Class<T> clazz, final BeanAttributes<T> attributes, final AnnotatedType<T> annotatedType) {
    final BeanContext bc = findBeanContext(webBeansContext, clazz);
    final Class<?> superClass = bc.getManagedClass().getSuperclass();
    if (annotatedType.isAnnotationPresent(Specializes.class)) {
        if (superClass != Object.class && !isSessionBean(superClass)) {
            throw new DefinitionException("You can only specialize another EJB: " + clazz);
        }
        final BeanContext parentBc = findBeanContext(webBeansContext, superClass);
        final List<Class> businessLocalInterfaces = new ArrayList<>(parentBc.getBusinessLocalInterfaces());
        for (final Class<?> api : bc.getBusinessLocalInterfaces()) {
            businessLocalInterfaces.removeAll(GenericsUtil.getTypeClosure(api));
        }
        if (!businessLocalInterfaces.isEmpty()) {
            throw new DefinitionException("You can only specialize another EJB with at least the same API: " + clazz);
        }
    }
    final CdiEjbBean<T> bean = new OpenEJBBeanBuilder<T>(bc, webBeansContext, annotatedType, attributes).createBean(clazz, !annotatedType.isAnnotationPresent(Vetoed.class));
    bc.set(CdiEjbBean.class, bean);
    bc.set(CurrentCreationalContext.class, new CurrentCreationalContext());
    validateDisposeMethods(bean);
    validateScope(bean);
    final Set<ObserverMethod<?>> observerMethods;
    if (bean.isEnabled()) {
        observerMethods = new ObserverMethodsBuilder<T>(webBeansContext, bean.getAnnotatedType()).defineObserverMethods(bean);
    } else {
        observerMethods = new HashSet<>();
    }
    final WebBeansUtil webBeansUtil = webBeansContext.getWebBeansUtil();
    final Set<ProducerFieldBean<?>> producerFields = new ProducerFieldBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerFields(bean);
    final Set<ProducerMethodBean<?>> producerMethods = new ProducerMethodBeansBuilder(bean.getWebBeansContext(), bean.getAnnotatedType()).defineProducerMethods(bean, producerFields);
    final Map<ProducerMethodBean<?>, AnnotatedMethod<?>> annotatedMethods = new HashMap<>();
    for (final ProducerMethodBean<?> producerMethod : producerMethods) {
        final AnnotatedMethod<?> method = webBeansContext.getAnnotatedElementFactory().newAnnotatedMethod(producerMethod.getCreatorMethod(), annotatedType);
        webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for " + "ProducerMethods. Look at logs for further details");
        annotatedMethods.put(producerMethod, method);
    }
    final Map<ProducerFieldBean<?>, AnnotatedField<?>> annotatedFields = new HashMap<>();
    for (final ProducerFieldBean<?> producerField : producerFields) {
        if (!Modifier.isStatic(producerField.getCreatorField().getModifiers())) {
            throw new DefinitionException("In an EJB all producer fields should be static");
        }
        webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducer event observers for" + " ProducerFields. Look at logs for further details");
        annotatedFields.put(producerField, webBeansContext.getAnnotatedElementFactory().newAnnotatedField(producerField.getCreatorField(), webBeansContext.getAnnotatedElementFactory().newAnnotatedType(producerField.getBeanClass())));
    }
    final Map<ObserverMethod<?>, AnnotatedMethod<?>> observerMethodsMap = new HashMap<>();
    for (final ObserverMethod<?> observerMethod : observerMethods) {
        final ObserverMethodImpl<?> impl = (ObserverMethodImpl<?>) observerMethod;
        final AnnotatedMethod<?> method = impl.getObserverMethod();
        observerMethodsMap.put(observerMethod, method);
    }
    validateProduceMethods(bean, producerMethods);
    validateObserverMethods(bean, observerMethodsMap);
    final BeanManagerImpl beanManager = webBeansContext.getBeanManagerImpl();
    // Fires ProcessManagedBean
    final GProcessSessionBean event = new GProcessSessionBean(Bean.class.cast(bean), annotatedType, bc.getEjbName(), bean.getEjbType());
    beanManager.fireEvent(event, true);
    event.setStarted();
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessSessionBean event observers for managed beans. Look at logs for further details");
    // Fires ProcessProducerMethod
    webBeansUtil.fireProcessProducerMethodBeanEvent(annotatedMethods, annotatedType);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerMethod event observers for producer method beans. Look at logs for further details");
    // Fires ProcessProducerField
    webBeansUtil.fireProcessProducerFieldBeanEvent(annotatedFields);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessProducerField event observers for producer field beans. Look at logs for further details");
    // Fire ObservableMethods
    webBeansUtil.fireProcessObservableMethodBeanEvent(observerMethodsMap);
    webBeansUtil.inspectDeploymentErrorStack("There are errors that are added by ProcessObserverMethod event observers for observer methods. Look at logs for further details");
    if (!webBeansUtil.isAnnotatedTypeDecoratorOrInterceptor(annotatedType)) {
        for (final ProducerMethodBean<?> producerMethod : producerMethods) {
            beanManager.addBean(producerMethod);
        }
        for (final ProducerFieldBean<?> producerField : producerFields) {
            beanManager.addBean(producerField);
        }
    }
    beanManager.addBean(bean);
    return bean;
}
Also used : AnnotatedMethod(javax.enterprise.inject.spi.AnnotatedMethod) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WeakHashMap(java.util.WeakHashMap) ArrayList(java.util.ArrayList) ProducerFieldBean(org.apache.webbeans.component.ProducerFieldBean) GProcessSessionBean(org.apache.webbeans.portable.events.generics.GProcessSessionBean) ProducerMethodBean(org.apache.webbeans.component.ProducerMethodBean) Bean(javax.enterprise.inject.spi.Bean) OwbBean(org.apache.webbeans.component.OwbBean) AbstractOwbBean(org.apache.webbeans.component.AbstractOwbBean) ProducerFieldBeansBuilder(org.apache.webbeans.component.creation.ProducerFieldBeansBuilder) GProcessSessionBean(org.apache.webbeans.portable.events.generics.GProcessSessionBean) ObserverMethodsBuilder(org.apache.webbeans.component.creation.ObserverMethodsBuilder) ObserverMethodImpl(org.apache.webbeans.event.ObserverMethodImpl) DefinitionException(javax.enterprise.inject.spi.DefinitionException) ProducerMethodBean(org.apache.webbeans.component.ProducerMethodBean) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod) ProducerFieldBean(org.apache.webbeans.component.ProducerFieldBean) BeanContext(org.apache.openejb.BeanContext) WebBeansUtil(org.apache.webbeans.util.WebBeansUtil) ProducerMethodBeansBuilder(org.apache.webbeans.component.creation.ProducerMethodBeansBuilder) BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) AnnotatedField(javax.enterprise.inject.spi.AnnotatedField)

Example 2 with ObserverMethod

use of javax.enterprise.inject.spi.ObserverMethod in project core by weld.

the class ObserverNotifier method notifyAsyncObservers.

protected <T, U extends T> CompletionStage<U> notifyAsyncObservers(List<ObserverMethod<? super T>> observers, U event, EventMetadata metadata, Executor executor, NotificationOptions options) {
    if (executor == null) {
        executor = asyncEventExecutor;
    }
    if (observers.isEmpty()) {
        return AsyncEventDeliveryStage.completed(event, executor);
    }
    // We should always initialize and validate all notification options first
    final NotificationMode mode = initModeOption(options.get(WeldNotificationOptions.MODE));
    final Long timeout = initTimeoutOption(options.get(WeldNotificationOptions.TIMEOUT));
    final Consumer<Runnable> securityContextActionConsumer = securityServices.getSecurityContextAssociator();
    final ObserverExceptionHandler exceptionHandler;
    CompletableFuture<U> completableFuture;
    if (observers.size() > 1 && NotificationMode.PARALLEL.equals(mode)) {
        // Attempt to notify async observers in parallel
        exceptionHandler = new CollectingExceptionHandler(new CopyOnWriteArrayList<>());
        List<CompletableFuture<T>> completableFutures = new ArrayList<>(observers.size());
        for (ObserverMethod<? super T> observer : observers) {
            completableFutures.add(CompletableFuture.supplyAsync(createSupplier(securityContextActionConsumer, event, metadata, exceptionHandler, false, () -> {
                notifyAsyncObserver(observer, event, metadata, exceptionHandler);
            }), executor));
        }
        completableFuture = CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[] {})).thenApply((ignoredVoid) -> {
            handleExceptions(exceptionHandler);
            return event;
        });
    } else {
        // Async observers are notified serially in a single worker thread
        exceptionHandler = new CollectingExceptionHandler();
        completableFuture = CompletableFuture.supplyAsync(createSupplier(securityContextActionConsumer, event, metadata, exceptionHandler, true, () -> {
            for (ObserverMethod<? super T> observer : observers) {
                notifyAsyncObserver(observer, event, metadata, exceptionHandler);
            }
        }), executor);
    }
    // If NotificationOptionKeys.TIMEOUT is set, we will trigger the counter and use CompletableFuture.anyOf()
    if (timeout != null) {
        completableFuture = CompletableFuture.anyOf(completableFuture, startTimer(timeout)).thenApply((ignoredObject) -> event);
    }
    return new AsyncEventDeliveryStage<>(completableFuture, executor);
}
Also used : ServiceRegistry(org.jboss.weld.bootstrap.api.ServiceRegistry) WeldNotificationOptions(org.jboss.weld.events.WeldNotificationOptions) EventLogger(org.jboss.weld.logging.EventLogger) Reflections(org.jboss.weld.util.reflection.Reflections) SharedObjectCache(org.jboss.weld.resources.SharedObjectCache) TimeoutException(java.util.concurrent.TimeoutException) CompletableFuture(java.util.concurrent.CompletableFuture) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod) Types(org.jboss.weld.util.Types) Reflections.cast(org.jboss.weld.util.reflection.Reflections.cast) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) ComputingCache(org.jboss.weld.util.cache.ComputingCache) QualifierInstance(org.jboss.weld.resolution.QualifierInstance) LazyValueHolder(org.jboss.weld.util.LazyValueHolder) NotificationOptions(javax.enterprise.event.NotificationOptions) SecurityServices(org.jboss.weld.security.spi.SecurityServices) ExecutorServices(org.jboss.weld.manager.api.ExecutorServices) Observers(org.jboss.weld.util.Observers) EventMetadata(javax.enterprise.inject.spi.EventMetadata) UtilLogger(org.jboss.weld.logging.UtilLogger) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) RequestContext(org.jboss.weld.context.RequestContext) LinkedList(java.util.LinkedList) ResolvableBuilder(org.jboss.weld.resolution.ResolvableBuilder) ThreadLocalStackReference(org.jboss.weld.injection.ThreadLocalStack.ThreadLocalStackReference) NotificationMode(org.jboss.weld.events.WeldNotificationOptions.NotificationMode) Executor(java.util.concurrent.Executor) UnboundLiteral(org.jboss.weld.context.unbound.UnboundLiteral) Set(java.util.Set) ObserverException(javax.enterprise.event.ObserverException) CompletionException(java.util.concurrent.CompletionException) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Resolvable(org.jboss.weld.resolution.Resolvable) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) ComputingCacheBuilder(org.jboss.weld.util.cache.ComputingCacheBuilder) Type(java.lang.reflect.Type) ForkJoinPool(java.util.concurrent.ForkJoinPool) Annotation(java.lang.annotation.Annotation) Collections(java.util.Collections) TypeSafeObserverResolver(org.jboss.weld.resolution.TypeSafeObserverResolver) Container(org.jboss.weld.Container) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) NotificationMode(org.jboss.weld.events.WeldNotificationOptions.NotificationMode) ArrayList(java.util.ArrayList) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) CompletableFuture(java.util.concurrent.CompletableFuture) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList)

Example 3 with ObserverMethod

use of javax.enterprise.inject.spi.ObserverMethod in project core by weld.

the class ProbeObserver method notify.

@Override
public void notify(Object event) {
    EventMetadata metadata = currentEventMetadata.peek();
    if (excludePattern != null && excludePattern.matcher(Formats.formatType(metadata.getType(), false)).matches()) {
        ProbeLogger.LOG.eventExcluded(metadata.getType());
        return;
    }
    boolean containerEvent = isContainerEvent(metadata.getQualifiers());
    List<ObserverMethod<?>> observers = resolveObservers(metadata, containerEvent);
    EventInfo info = new EventInfo(metadata.getType(), metadata.getQualifiers(), event, metadata.getInjectionPoint(), observers, containerEvent, System.currentTimeMillis());
    probe.addEvent(info);
}
Also used : EventMetadata(javax.enterprise.inject.spi.EventMetadata) CurrentEventMetadata(org.jboss.weld.event.CurrentEventMetadata) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod)

Example 4 with ObserverMethod

use of javax.enterprise.inject.spi.ObserverMethod in project tomee by apache.

the class WebappBeanManager method resolveObserverMethods.

@Override
public <T> Set<ObserverMethod<? super T>> resolveObserverMethods(final T event, final EventMetadataImpl metadata) {
    final Set<ObserverMethod<? super T>> set = new HashSet<>();
    set.addAll(getNotificationManager().resolveObservers(event, metadata, false));
    if (isEvent(event)) {
        final BeanManagerImpl parentBm = getParentBm();
        if (parentBm != null) {
            set.addAll(parentBm.getNotificationManager().resolveObservers(event, metadata, false));
        }
    }
    return set;
}
Also used : BeanManagerImpl(org.apache.webbeans.container.BeanManagerImpl) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod) HashSet(java.util.HashSet)

Example 5 with ObserverMethod

use of javax.enterprise.inject.spi.ObserverMethod in project core by weld.

the class Probe method findUnusedBeans.

private void findUnusedBeans() {
    Collection<Bean<?>> beans = idToBean.values();
    Collection<ObserverMethod<?>> observers = idToObserver.values();
    for (Bean<?> bean : beans) {
        BeanKind kind = BeanKind.from(bean);
        if (BeanKind.BUILT_IN.equals(kind) || BeanKind.EXTENSION.equals(kind) || BeanKind.DECORATOR.equals(kind) || BeanKind.INTERCEPTOR.equals(kind)) {
            continue;
        }
        if (bean.getName() != null) {
            // Is annotated with @Named
            continue;
        }
        if (!(BeanKind.PRODUCER_FIELD.equals(kind) || BeanKind.PRODUCER_METHOD.equals(kind)) && !getDeclaredProducers(bean).isEmpty()) {
            // Has declared producers
            continue;
        }
        if (Components.hasDependents(bean, beans, this)) {
            // Has direct or potential (Instance<>) dependents
            continue;
        }
        if (hasDeclaredObserversOrIsInjectedIntoObserver(bean, observers)) {
            continue;
        }
        if (isInjectedIntoDisposer(bean, beans)) {
            continue;
        }
        unusedBeans.add(bean);
    }
}
Also used : BeanKind(org.jboss.weld.probe.Components.BeanKind) AbstractProducerBean(org.jboss.weld.bean.AbstractProducerBean) ExtensionBean(org.jboss.weld.bean.builtin.ExtensionBean) AbstractBuiltInBean(org.jboss.weld.bean.builtin.AbstractBuiltInBean) Bean(javax.enterprise.inject.spi.Bean) ObserverMethod(javax.enterprise.inject.spi.ObserverMethod)

Aggregations

ObserverMethod (javax.enterprise.inject.spi.ObserverMethod)6 ArrayList (java.util.ArrayList)3 Bean (javax.enterprise.inject.spi.Bean)2 EventMetadata (javax.enterprise.inject.spi.EventMetadata)2 BeanManagerImpl (org.apache.webbeans.container.BeanManagerImpl)2 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 Annotation (java.lang.annotation.Annotation)1 Type (java.lang.reflect.Type)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1 Set (java.util.Set)1 WeakHashMap (java.util.WeakHashMap)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 CompletionException (java.util.concurrent.CompletionException)1 CompletionStage (java.util.concurrent.CompletionStage)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1