Over a million developers have joined DZone.

CDI-JSF: Using the CDI @Observes

See the CDI @Observes annotation in action for your JSF projects — in this case, setting up fire alarms for various neighborhoods.

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

In this post, we will discuss using the CDI @Observes in a JSF application.

Basically, we will exploit the fact that Java EE provides an easier implementation of the observer design pattern via the @Observes annotation and javax.enterprise.event.Event<T> interface.

Note In the bellow examples, we will use CDI managed beans, but you can use EJB 3 beans also. Basically, the observer pattern is based on a subject and some observers:

  • Subject: an object that changes its state.

  • Observers: objects notified when the subject has changed its state.

This time, the subject is a CDI managed bean named, MainFireStationBean:

@Named
@RequestScoped
public class MainFireStationBean {

    @Inject
    Event<String> evt;

    public void fireStarted(String address) {
        evt.fire(address);
    }
}


The container injects an Event object of type String into the evt instance variable of the   MainFireStationBean class (practically, this String represents the fire address). To activate an event, call the javax.enterprise.event.Event.fire() method. This method fires an event and notifies any observer methods (observers). Now the observable part is completed, so it is time to create the observers that listens for our String events.

In Java EE, the observers are marked with the @Observes annotation. The addition of the @Observes annotation to the method signature instructs the container that this method should act as an observer of events of the type it precedes. 

We have three observers, ViningsFireStationBean, BrookhavenFireStationBean, and   DecaturFireStationBean:

@Named
@Dependent
public class ViningsFireStationBean {

    public void update(@Observes String arg) {
         System.out.println("Vinings fire department will go to " + arg);
    }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

    public void update(@Observes String arg) {
        System.out.println("Brookhaven fire department will go to " + arg);
    }
}

@Named
@Dependent
public class DecaturFireStationBean {

    public void update(@Observes String arg) {
        System.out.println("Decatur fire department will go to " + arg);
    }
}


So, the @Observes annotation precedes the type String and thus listens for events of that type. The @Observes annotation followed by an object type instruct the container with all the needed information.

In order to test it, we just need to report some fires. We can do this in several ways, but let's do it quickly via two JSF buttons:
<h:form>
    <h:commandButton value="Report Fire at Home Park Atlanta" 
                     action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA')}"/>
    <h:commandButton value="Report Fire at High Museum of Art" 
                     action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309')}"/>
</h:form>


If we suppose that the Report Fire at Home Park Atlanta button was pressed then the output will be:

Decatur fire department will go to Home Park Atlanta, GA

Vinings fire department will go to Home Park Atlanta, GA

Brookhaven fire department will go to Home Park Atlanta, GA


So, everything works as expected. The complete example is available here.

One step further and we will want to differentiate between the same object types of objects and set up different observers to listen for them. For example, we may need to distinguish between small fires and big fires. Depending on this aspect, a local fire station may send to the fire address one fire truck or multiple fire trucks. We can model this case via a qualifier:
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface FireType {

    Type value();

    enum Type {
        SMALL, BIG
    }
}


The two enum types (SMALL and BIG) will be used to act as annotation to mark the strings to be fired by the event instances. So, the MainFireStationBean will be:
@Named
@RequestScoped
public class MainFireStationBean {

    @Inject
    @FireType(Type.SMALL)
    Event<String> small;

    @Inject
    @FireType(Type.BIG)
    Event<String> big;

    public void fireStarted(String address, boolean t) {
        if (t) {
            small.fire(address);
        } else {
            big.fire(address);
        }
    }
}


Finally, add the annotations to the observer part:
@Named
@Dependent
public class ViningsFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Vinings fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
        System.out.println("Vinings fire department will go to a big fire at " + arg);
    }
}

@Named
@Dependent
public class BrookhavenFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Brookhaven fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
         System.out.println("Brookhaven fire department will go to a big fire at " + arg);
    }
}

@Named
@Dependent
public class DecaturFireStationBean {

    public void updateSmallFire(@Observes @FireType(FireType.Type.SMALL) String arg) {
        System.out.println("Decatur fire department will go to a small fire at " + arg);
    }

    public void updateBigFire(@Observes @FireType(FireType.Type.BIG) String arg) {
        System.out.println("Decatur fire department will go to a big fire at " + arg);
    }
}



Now, let's report a big fire and a small fire:
<h:form>
    <h:commandButton value="Report a Small Fire at Home Park Atlanta" 
                     action="#{mainFireStationBean.fireStarted('Home Park Atlanta, GA', true)}"/>
    <h:commandButton value="Report a Big Fire at High Museum of Art" 
                     action="#{mainFireStationBean.fireStarted('High Museum of Art 1280 Peachtree St NE Atlanta, GA 30309', false)}"/>
</h:form>  


In case of a small fire, the output will be:

Brookhaven fire department will go to a small fire at Home Park Atlanta, GA

Vinings fire department will go to a small fire at Home Park Atlanta, GA

Decatur fire department will go to a small fire at Home Park Atlanta, GA


Note that in case of your own object types, you don't need qualifiers. Since the object type is unique, you can fire/observe your own object types by using the object.

The complete example is available here.

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:
query string ,character encoding ,jsf ,java

Published at DZone with permission of Anghel Leonard, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}