Sunday, 17 February 2008

jServiceRules (I). The Semantic Core.

The first package of the jServiceRules framework is the jSemanticCore, that contains all the interfaces, abstract factories, helpers so a Semantic Session could be implemented.

The Semantic Session is a core concept within the jServiceRules framework and is just a Working Memory object "on steroids". Essentially it offers a focused interface, improves the communication of the WM with the execution enviroment (internal/external) and hides all the complexity behind the backed rules engine. Also helps to manage some external knowledge we could need through the Knowledge Database.

Let's say that you want to execute some business stateless rules. To produce this is as simple as:
  • Creating a Semantic Session Factory associated to the rules file.
  • Getting an instance of the Semantic Session (stateless by default), produced by the factory.
  • Passing some facts to the session (related to the rules you want to evaluate).
  • The rules will be automatically evaluated and some results will be returned.
  • The session could be disposed.
SemanticSessionFactory factory = new SemanticSessionFactoryImpl("org/jservicerules/rules/test.drl");

SemanticSession session = factory.getInstance();

Collection results = session.execute(new Integer(10));

session.dispose();

A template to produce the rules files is provided with the package:

package org.jsemantic.templates
global org.jsemantic.core.context.SemanticContext ctx;

rule "rule_one"
when
then
end
.........
rule "rule_n"
when
then
end

For example, we'd like to know if a number it's even:

rule "even"
when
number:Integer()
eval(number.intValue() % 2 == 0)
then
ctx.addObject(number, "Number: " + number + " is even");
end

The Semantic Context is the object that allows to interact with the enviroment. One way is returning results of the rules evaluation through the addObject(id, value) method. There are other ways of interacting as using the ExternalContext or the Session Variables. I'll explain this in future posts.

No comments: