Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source
   * Copyright 2008, Red Hat, Inc., and individual contributors
   * by the @authors tag. See the copyright.txt in the distribution for a
   * full listing of individual contributors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
  * http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.jboss.weld.event;
 
 import static org.jboss.weld.util.collections.WeldCollections.immutableGuavaSet;
 
 import java.util.List;
 import java.util.Set;
 
 

Reference implementation for the ObserverMethod interface, which represents an observer method. Each observer method has an event type which is the class of the event object being observed, and event binding types that are annotations applied to the event parameter to narrow the event notifications delivered.

Author(s):
David Allen
Jozef Hartinger
Marko Luksa
 
 public class ObserverMethodImpl<T, X> implements ObserverMethod<T> {
 
     public static final String ID_PREFIX = ObserverMethodImpl.class.getPackage().getName();
 
     public static final String ID_SEPARATOR = "-";
 
     private final Set<Annotationbindings;
     private final Type eventType;
     protected final BeanManagerImpl beanManager;
     private final Reception reception;
     protected final RIBean<X> declaringBean;
     protected final MethodInjectionPoint<T, ? super X> observerMethod;
     protected TransactionPhase transactionPhase;
     private final String id;
 
     private final Set<WeldInjectionPointAttributes<?, ?>> injectionPoints;
     private final Set<WeldInjectionPointAttributes<?, ?>> newInjectionPoints;

    
Creates an Observer which describes and encapsulates an observer method (8.5).

Parameters:
observer The observer
declaringBean The observer bean
manager The Bean manager
 
     protected ObserverMethodImpl(final EnhancedAnnotatedMethod<T, ? super X> observerfinal RIBean<X> declaringBeanfinal BeanManagerImpl manager) {
         this. = manager;
         this. = declaringBean;
         this. = initMethodInjectionPoint(observerdeclaringBeanmanager);
        EnhancedAnnotatedParameter<?, ? super X> eventParameter = observer.getEnhancedParameters(Observes.class).get(0);
        this. = new HierarchyDiscovery(declaringBean.getBeanClass()).resolveType(eventParameter.getBaseType());
        this. = createId(observerdeclaringBean);
        this. = manager.getServices().get(SharedObjectCache.class)
                .getSharedSet(observer.getEnhancedParameters(Observes.class).get(0).getMetaAnnotations(Qualifier.class));
        Observes observesAnnotation = observer.getEnhancedParameters(Observes.class).get(0).getAnnotation(Observes.class);
        this. = observesAnnotation.notifyObserver();
         = ObserverFactory.getTransactionalPhase(observer);
        Set<WeldInjectionPointAttributes<?, ?>> injectionPoints = new HashSet<WeldInjectionPointAttributes<?, ?>>();
        Set<WeldInjectionPointAttributes<?, ?>> newInjectionPoints = new HashSet<WeldInjectionPointAttributes<?, ?>>();
        for (ParameterInjectionPoint<?, ?> injectionPoint : .getParameterInjectionPoints()) {
            if (injectionPoint instanceof SpecialParameterInjectionPoint) {
                continue;
            }
            if (injectionPoint.getQualifier(New.class) != null) {
                newInjectionPoints.add(injectionPoint);
            }
            injectionPoints.add(injectionPoint);
        }
        this. = immutableGuavaSet(injectionPoints);
        this. = immutableGuavaSet(newInjectionPoints);
    }
    protected static String createId(final EnhancedAnnotatedMethod<?, ?> observerfinal RIBean<?> declaringBean) {
        String typeId = null;
        if (declaringBean instanceof AbstractClassBean<?>) {
            AbstractClassBean<?> classBean = (AbstractClassBean<?>) declaringBean;
            typeId = classBean.getAnnotated().getIdentifier().asString();
        } else {
            typeId = declaringBean.getBeanClass().getName();
        }
                .append(".").append(observer.getSignature()).toString();
    }
    protected MethodInjectionPoint<T, ? super X> initMethodInjectionPoint(EnhancedAnnotatedMethod<T, ? super X> observerRIBean<X> declaringBean,
            BeanManagerImpl manager) {
        return InjectionPointFactory.instance().createMethodInjectionPoint(observerdeclaringBeandeclaringBean.getBeanClass(), truemanager);
    }
        return Collections.unmodifiableSet();
    }
        return Collections.unmodifiableSet();
    }

    
Performs validation of the observer method for compliance with the specifications.
    private <Y> void checkObserverMethod(EnhancedAnnotatedMethod<T, Y> annotated) {
        // Make sure exactly one and only one parameter is annotated with Observes
        List<EnhancedAnnotatedParameter<?, Y>> eventObjects = annotated.getEnhancedParameters(Observes.class);
        if (this..equals(.) && .getScope().equals(Dependent.class)) {
            throw ..invalidScopedConditionalObserver(this);
        }
        if (eventObjects.size() > 1) {
            throw ..multipleEventParameters(this);
        }
        EnhancedAnnotatedParameter<?, Y> eventParameter = eventObjects.iterator().next();
        checkRequiredTypeAnnotations(eventParameter);
        // Check for parameters annotated with @Disposes
        List<?> disposeParams = annotated.getEnhancedParameters(Disposes.class);
        if (disposeParams.size() > 0) {
            throw ..invalidDisposesParameter(this);
        }
        // Check annotations on the method to make sure this is not a producer
        // method, initializer method, or destructor method.
        if (this..getAnnotated().isAnnotationPresent(Produces.class)) {
            throw ..invalidProducer(this);
        }
        if (this..getAnnotated().isAnnotationPresent(Inject.class)) {
            throw ..invalidInitializer(this);
        }
        boolean containerLifecycleObserverMethod = Observers.isContainerLifecycleObserverMethod(this);
        for (EnhancedAnnotatedParameter<?, ?> parameter : annotated.getEnhancedParameters()) {
            // if this is an observer method for container lifecycle event, it must not inject anything besides BeanManager
            if (containerLifecycleObserverMethod && !parameter.isAnnotationPresent(Observes.class) && !BeanManager.class.equals(parameter.getBaseType())) {
                throw ..invalidInjectionPoint(this);
            }
        }
    }
    protected void checkRequiredTypeAnnotations(EnhancedAnnotatedParameter<?, ?> eventParameter) {
        if (eventParameter.isAnnotationPresent(WithAnnotations.class)) {
            throw ..invalidWithAnnotations(this);
        }
    }
    @Override
    public Class<X> getBeanClass() {
        return .getType();
    }
    public RIBean<X> getDeclaringBean() {
        return ;
    }
    @Override
    public Reception getReception() {
        return ;
    }
    @Override
    public Set<AnnotationgetObservedQualifiers() {
        return ;
    }
    @Override
    public Type getObservedType() {
        return ;
    }
    @Override
        return ;
    }

    

Returns:
the observerMethod
    public MethodInjectionPoint<T, ? super X> getMethod() {
        return ;
    }

    
Completes initialization of the observer and allows derived types to override behavior.
    public void initialize(EnhancedAnnotatedMethod<T, ? super X> annotated) {
        checkObserverMethod(annotated);
    }
    @Override
    public void notify(final T event) {
        sendEvent(event);
    }

    
Invokes the observer method immediately passing the event.

Parameters:
event The event to notify observer with
    protected void sendEvent(final T event) {
        if (.getAnnotated().isStatic()) {
            sendEvent(eventnull.createCreationalContext());
        } else {
            CreationalContext<X> creationalContext;
            if (.equals(.)) {
                creationalContext = null;
            } else {
                creationalContext = .createCreationalContext();
            }
            Object receiver = getReceiverIfExists(creationalContext);
            if (receiver != null) {
                sendEvent(eventreceivercreationalContext);
            }
        }
    }
    protected void sendEvent(T eventObject receiverCreationalContext<?> creationalContext) {
        try {
            preNotify(eventreceiver);
            if (receiver == null) {
                .invokeWithSpecialValue(nullObserves.classeventcreationalContextObserverException.class);
            } else {
                // As we are working with the contextual instance, we may not have the
                // actual object, but a container proxy (e.g. EJB)
                .invokeOnInstanceWithSpecialValue(receiverObserves.classeventcreationalContextObserverException.class);
            }
        } finally {
            postNotify(eventreceiver);
            if (creationalContext != null) {
                creationalContext.release();
            }
        }
    }

    
Hooks allowing subclasses to perform additional logic just before and just after an event is delivered to an observer method.
    protected void preNotify(T eventObject receiver) {
    }
    protected void postNotify(T eventObject receiver) {
    }
    private Object getReceiverIfExists(CreationalContext<X> creationalContext) {
        try {
            return getReceiver(creationalContext);
        } catch (ContextNotActiveException e) {
            return null;
        }
    }
    protected Object getReceiver(CreationalContext<X> creationalContext) {
        Context context = .getContext(.getScope());
        if (creationalContext != null) {
            if (creationalContext instanceof CreationalContextImpl<?>) {
                // Create child creational context so that a dependent observer may be destroyed after the observer method completes
                creationalContext = ((CreationalContextImpl<?>) creationalContext).getCreationalContext();
            }
            return context.get(creationalContext);
        }
        // Conditional observer - no creational context is required
        return context.get();
    }
    @Override
    public String toString() {
        return .toString();
    }
    public String getId() {
        return ;
    }
    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        ObserverMethodImpl<?, ?> that = (ObserverMethodImpl<?, ?>) obj;
        return this.getId().equals(that.getId());
    }
    @Override
    public int hashCode() {
        return getId().hashCode();
    }
New to GrepCode? Check out our FAQ X