• Share this article:

Event Service

Thursday, July 17, 2008 - 14:18 by Wayne Beaton

I blogged a while back about the potential use of a bus for delivering property change notifications in place of the very common observer pattern. A reader commented that the exact service I need to implement that sort of thing is already available in the form of the OSGi Event Service. An implementation of this service is provided by the Equinox project.

I’ve updated part of the Eclipse Expense Expense Reporting Tool example to make use of the service.

I updated my business domain objects to post events detailing their changes through the EventAdmin service. This was made relatively easy owing to the fact that I had already implemented those objects with a common superclass. I added the postEvent(…) method to that common superclass:

	void postEvent(String propertyName, Object oldValue, Object newValue) {
		EventAdmin eventAdmin = getEventAdmin();
		if (eventAdmin == null) return;

		Properties properties = new Properties();
		properties.put(SOURCE, this);
		properties.put(SOURCE_TYPE, this.getClass().getName());
		properties.put(PROPERTY_NAME, propertyName);
		if (oldValue != null) properties.put(OLD_VALUE, oldValue);
		if (newValue != null) properties.put(NEW_VALUE, newValue);

		eventAdmin.postEvent(new Event(PROPERTY_CHANGE_TOPIC, properties));
	}

It’s pretty straightforward. The first thing it tries to do is obtain the service. The getEventAdmin() method uses the bundle activator (and a ServiceTracker) to find a service that implements EventAdmin. If no such service can be found, we bail out and pretend that nothing happened. If we do find an EventAdmin, we create and post an Event instance. The postEvent method posts the event to be delivered asynchronously; the sendEvent method delivers the event to waiting handlers before returning.

The Event instance is packed with properties. The nature of these properties are application-specific. In this case, I’m including properties that tell me what has changed and in what object. The event also has a "topic". The topic is used to determine how the event is delivered; only event handlers that are listening for this particular topic will be informed of the event (there’s a little more to it than this). It’s very much like the Java Messaging Service (JMS).

This is only part of the story. Publishing events through the event service is only interesting if there are subscribers on the other side. I’ll talk about what I’ve done on that side sometime next week…