JAM - examples

Printer-friendly versionPrinter-friendly version
How to use the JAM framework

 

That means that we should already be able to see the output of our simple text announcements in the console after being sent.   cool

To pass the output also through a logger (e.g. to write it with the logger format into a logfile or on the console again), there is a ready to use subscriber AnnouncementLogger which works same as the AnnouncementPrinter, but is not subscribed yet. The AnnouncementLogger uses the java.util.logging.Logger.

Note: we can easily employ other logger frameworks. JAM comes already with extra packages for famous logger API like Log4j and SLF4J.

To subscribe the AnnouncementLogger we must decide first for which topic(s) we want the logging. To make it simple for now, we subscribe like this:

JAM.getMediator(RootTopic.ANY).subscribe(new AnnouncementLogger());

Or for concurrently processed announcements:

JAM.getConcurrentMediator(RootTopic.ANY).subscribe(new AnnouncementLogger());

Now, all announcements of a suitable announcement type (here TextOffer, MessageOffer, ThrowableOffer) will be sent to the logger.

Note: we might need to configure the logger framework first to make it work actually.

 

For a real-world application we need our own implementations of subscribers. Even that is very simple to do:

JAM.getMediator(RootTopic.ANY).mediator.subscribe(new TextConsumer() {
    
    @Override
    public boolean acceptsSubtopics() {
        return true;
    }
    
    @Override
    public void accept(Topic topic, TextOffer offer) {
        System.out.println("Consumed: " + offer.getContent());
    }
});

Just for this example we created a new TextConsumer as anonymous class and subscribed that Consumer in one step. Consumers consume Offers. Offers are asynchronous announcements, means nothing will be returned synchronously. Accordingly, Consumers accept Offers and return nothing.

Note: synchronous announcements are represented by Demands, which are consumed by Suppliers. Suppliers return the objects (or null) demanded by a Demand synchronously.

We return true in the method acceptsSubtopics() to make sure the reception of announcements is not restricted to the topic the subscriber is subscribed for (here ANY). Remember our text announcements are sent automatically to the topics TEXT and INFO_TEXT. Returning true allows to receive announcements from these subordinated topics of ANY.

Fortunately, JAM passes the announcements to the subscribers always with their correct concrete type, so we can access all their properties type safe without any instanceof and cast! For this example we just print the content (the String) to the console.
 

Well, simple texts are probably not the reason to employ JAM. Let's continue with complex messages now and later on with more complex and generic stuff.

 

 

Pages