Example: Handle rulebase events with an inferencing event listener


Events are fired by the triggering of a RaiseEvent rule. They are typically used for informing the rule-based application that something important has happened that might require action.

A common use for events is checking values entered by a user. A rule could be written that tests if the applicant's date of birth is after today's date, and if so triggers an event describing the error.

Example rule:

RaiseEvent Error(“date of birth must be before today’s date”, DOB) if

             the applicant’s date of birth > the current date                                                                                                               

 

In this example “Error” is the name of the event and the parameters to the event are the error message and the public name of the attribute “the applicant’s date of birth” attribute.

Handling events is similar to handling custom functions. A class must be created that implements the InferencingListener interface. The interface declares three methods, beginInferencing(), endInferencing(), and ruleInferenced(). The ruleInferenced() method receives an InferencingEvent object through which various properties are available, including the EntityInstance in which the event occurred. Changes to the session are not allowed in the middle of the inferencing cycle, so anything that needs to change the session must be deferred until the endInferencing() method.

Like custom function handlers, event listeners are installed on a per-session basis and can be packaged up into the rulebase zip file for more convenient distribution. They can also be added or removed on demand using the Session.addInferencingListener(), Session.removeInferencingListener(), and Session.getInferencingListeners() methods. There can be any number event listeners installed on a session.

The following example is an event listener that supports the example rule above. It accepts two parameters, an error message and the public name of the attribute whose value is considered illegal. The attribute is set to unknown after the event is triggered but because this is a change to the session, it cannot take place in the ruleInferenced() method that occurs during the inferencing cycle. It must instead be done in the endInferencing() method.

Click on the appropriate link to view either the Java or the C# example:

 

Java Code Example:

 

C# Coding Example: