-
Notifications
You must be signed in to change notification settings - Fork 34
Implementing Listeners
Since M3 we've implemented listeners within the API. Currently they're only available for the Database class, but they basically allow you to run standard code when an event is triggered from any context that uses the API. There are events like AFTER_UPDATE_DOCUMENT, AFTER_CREATE_DOCUMENT, BEFORE_REPLICATION, BEFORE_DELETE_DOCUMENT. Imagine, for example, being able to inform the user of how many documents they have created / saved during the current session. Or with a single piece of code ensure any deletions are logged automatically. Or being able to keep a track in applicationScope of any document saved via XPages, and so update the full text index when that gets up to a certain number. And there is the potential for this to be expanded beyond those options in the future.
In order to implement a listener you will need three things:
- A class that implements IDominoListener. This identifies what listeners are implemented and the code to run when those listeners are fired.
- A call that adds the listener to the database wherever it's used. The easiest method is to have a Utils.getCurrentDatabase() method, which gets the database and calls Database.addListener(myClassListener).
- Code that calls a method that is going to fire the listener. So for the UPDATE_DOCUMENT listeners, doc.save() or its overloaded methods. For the CREATE_DOCUMENT listeners, database.createDocument() method or its overloaded methods.
The IDominoListener interface expects code in two methods:
- getEventTypes
- eventHappened
getEventTypes does what it says on the tin: it provides a List of EnumEvents. That can be any kind of List but an ArrayList should be sufficient. The list of available event types are held in an Enum - a restricted list of options that provides typeahead and validation - called Events. It can be found in the source code in org.openntf.domino.ext.Database. (If listeners are implemented at other levels, they may be held at other levels as well).
Let's have a look at some code:
ArrayList<EnumEvent> eventList = new ArrayList<EnumEvent>();
eventList.add(Events.AFTER_CREATE_DOCUMENT);
eventList.add(Events.AFTER_UPDATE_DOCUMENT);
return eventList;
}```
So the code just creates the ArrayList and adds each event to be registered against for a database.
### eventHappened