Chapter 10. Sessions
10.1. Sessions in JBoss Rules
Sessions are created from the
KnowledgeBase
into which data can be inserted and from which process instances may be started. Creating the KnowledgeBase
can be resource-intensive, whereas session creation is not. For this reason, it is recommended that KnowledgeBases be cached where possible to allow for repeated session creation.
10.2. Create a StatefulKnowledgeSession From a KnowledgeBase
This is the code for creating a new StatefulKnowledgeSession from a KnowledgeBase:
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
10.3. The WorkingMemoryEntryPoint Method
The
WorkingMemoryEntryPoint
provides the methods around inserting, updating and retrieving facts. The term "entry point" is related to the fact that there are multiple partitions in a Working Memory and you can choose which one you are inserting into. Most rule based applications will work with the default entry point alone.
10.4. The KnowledgeRuntime Interface
The
KnowledgeRuntime
interface provides the main interaction with the engine. It is available in rule consequences and process actions. The KnowledgeRuntime
inherits methods from both the WorkingMemory
and the ProcessRuntime
, thereby providing a unified API to work with processes and rules. When working with rules, three interfaces form the KnowledgeRuntime
: WorkingMemoryEntryPoint
, WorkingMemory
and the KnowledgeRuntime
itself.
10.5. Fact Insertion
Insertion is the act of telling the
WorkingMemory
about a fact. You can do this by using ksession.insert(yourObject)
, for example. When you insert a fact, it is examined for matches against the rules. This means all of the work for deciding about firing or not firing a rule is done during insertion. However, no rule is executed until you call fireAllRules()
, which you call after you have finished inserting your facts.
10.6. The FactHandle Token
When an Object is inserted, it returns a
FactHandle
. This FactHandle
is the token used to represent your inserted object within the WorkingMemory
. It is also used for interactions with the WorkingMemory
when you wish to retract or modify an object.
10.7. FactHandle Example
Job accountant = new Job("accountant"); FactHandle accountantHandle = ksession.insert( accountant );
10.8. Identity and Equality
These are the two assertation nodes used by the Working Memory:
- Identity
- This means that the Working Memory uses an
IdentityHashMap
to store all asserted objects. New instance assertions always result in the return of newFactHandle
, but if an instance is asserted again then it returns the original fact handle (that is, it ignores repeated insertions for the same object). - Equality
- This means that the Working Memory uses a
HashMap
to store all asserted objects. An object instance assertion will only return a newFactHandle
if the inserted object is not equal (according to itsequal
method) to an already existing fact.
Note
New instance assertions always result in the return of new
FactHandle
, but if an instance is asserted again then it returns the original fact handle (that is, it ignores repeated insertions for the same object).
10.9. Retraction
Retraction is the removal of a fact from Working Memory. This means that it will no longer track and match that fact, and any rules that are activated and dependent on that fact will be canceled. It is possible to have rules that depend on the nonexistence of a fact, in which case retracting a fact may cause a rule to activate. Retraction may be done using the
FactHandle
that was returned by the insert call. On the right hand side of a rule the retract
statement is used, which works with a simple object reference.
10.10. Retraction Example
Job accountant = new Job("accountant"); FactHandle accountantHandle = ksession.insert( accountant ); .... ksession.retract( accountantHandle );
10.11. The update() Method
The Rule Engine must be notified of modified facts so they can be reprocessed. The
update()
method can be used to notify the WorkingMemory
of changed objects for those objects that are not able to notify the WorkingMemory
themselves. The update()
method always takes the modified object as a second parameter, which allows you to specify new instances for immutable objects.
Note
On the right hand side of a rule the
modify
statement is recommended, as it makes the changes and notifies the engine in a single statement. Alternatively, after changing a fact object's field values through calls of setter methods you must invoke update
immediately, event before changing another fact, or you will cause problems with the indexing within the rule engine. The modify statement avoids this problem.
10.12. update() Example
Job accountant = new Job("accountant"); FactHandle accountantHandle = workingMemory.insert( accountant ); ... accountant.setSalary( 45000 ); workingMemory.update( accountantHandle, accountant );
10.13. Queries
Queries are used to retrieve fact sets based on patterns, as they are used in rules. Patterns may make use of optional parameters. Queries can be defined in the Knowledge Base, from where they are called up to return the matching results. While iterating over the result collection, any identifier bound in the query can be used to access the corresponding fact or fact field by calling the
get
method with the binding variable's name as its argument. If the binding refers to a fact object, its FactHandle can be retrieved by calling getFactHandle
, again with the variable's name as the parameter.
10.14. Query Example
QueryResults results = ksession.getQueryResults( "my query", new Object[] { "string" } ); for ( QueryResultsRow row : results ) { System.out.println( row.get( "varName" ) ); }
10.15. Live Queries
Invoking queries and processing the results by iterating over the returned set is not a good way to monitor changes over time.
To alleviate this, JBoss Rules provides Live Queries, which have a listener attached instead of returning an iterable result set. These live queries stay open by creating a view and publishing change events for the contents of this view. To activate, start your query with parameters and listen to changes in the resulting view. The
dispose
method terminates the query and discontinues this reactive scenario.
10.16. ViewChangedEventListener Implementation Example
final List updated = new ArrayList(); final List removed = new ArrayList(); final List added = new ArrayList(); ViewChangedEventListener listener = new ViewChangedEventListener() { public void rowUpdated(Row row) { updated.add( row.get( "$price" ) ); } public void rowRemoved(Row row) { removed.add( row.get( "$price" ) ); } public void rowAdded(Row row) { added.add( row.get( "$price" ) ); } }; // Open the LiveQuery LiveQuery query = ksession.openLiveQuery( "cars", new Object[] { "sedan", "hatchback" }, listener ); ... ... query.dispose() // calling dispose to terminate the live query
Note
For an example of Glazed Lists integration for live queries, visit http://blog.athico.com/2010/07/glazed-lists-examples-for-drools-live.html
10.17. KnowledgeRuntime
The
KnowledgeRuntime
provides further methods that are applicable to both rules and processes, such as setting globals and registering channels. ("Exit point" is an obsolete synonym for "channel".)