Overview
The OSGi Event Admin service dispatches events to the registered event handlers. An event handler is a routine allowing a developer to write code to be executed when an event occurs. There is no defined mechanism to inspect the events, that were sent before a handler was registered. The Event Collector service catches the dispatched events and makes them available to applications installed later.
This functionality is optional and configured with proper event limit, discarding the oldest events. It is enabled by setting mbs.events.collector.enabled to true. Then, the OSGi Event Admin bundle registers a com.prosyst.mbs.services.event.tracker.EventCollector service, which provides two options of accessing already dispatched events:
Configuring the Service
Using the Service
The examples below show the couple of ways to collect cached events.
ServiceReference<EventCollector> ref = bundleContext.getServiceReference(EventCollector.class);
EventCollector collector = null;
if (ref != null) {
collector = bundleContext.getService(ref);
}
collector.getEvents(); // returns all cached events(or limited to the specified count)
collector.getEvents(null, "(test=publishEvents)"); // returns all events which match the provided filter
collector.getEvents(topicClass, "(test=publishEvents)"); // returns all events with the specified topic which match the provided filter
collector.getEvents(topicClass, null); // returns all events with the specified topic
class EventCollectorHandler implements EventHandler {
EventCollectorHandler(BundleContext context) {
Dictionary<String, Object> props = new Hashtable<String, Object>(3);
props.put(EventConstants.EVENT_TOPIC, topic); // optional
props.put(EventConstants.EVENT_FILTER, filter); // optional
props.put(EventCollector.USES_COLLECTED_EVENTS, Boolean.TRUE); // mandatory
context.registerService(EventHandler.class, this, props);
}
public void handleEvent(Event event) {
// This method will be called for all events(or limited to the specified count), collected before registration of this handler.
// All callbacks will be made in a different thread, than registering one.
}
}