Sunday, May 16, 2010

Globals in Drools

The Global variable in drools is a good way to return results or log info on the execution of rules. But one thing to keep in mind is to make sure the global variable that are defined are not primitive types. If you have primitive types as your global variable you will not be able to set values. Rather you will be restricted to only reading the variable.

Ex : What happen when i have a primitive global variable

Drl file :


#declare any global variables here
global String result;


rule "Eval Math"

when
$rec : StudentRecBean(math<40)
#conditions
then
result="FAIL";
System.out.println("Student "+$rec.getName()+" failed in Math");
#actions

end


Java File invoking drl :

KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
String result= "PASS";
ksession.setGlobal("result", result);

ksession.fireAllRules();
System.out.println("The Result is "+ksession.getGlobal("result")));



Output of the code when the student scored less than 40 :


The Resutl is PASS


Reason :
Pass by reference works only of object types in java and not for primitive types where it is pass by value.

Solution :



Drl file :

#declare any global variables here
global ResultBean result;




rule "Eval Math"

when
$rec : StudentRecBean(math<40)
#conditions
then
result.setResult("FAIL");
System.out.println("Student "+$rec.getName()+" failed in Math");
#actions

end



Java File invoking drl :


KnowledgeBase kbase = readKnowledgeBase();
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();
ResultBean result= new ResultBean("PASS");
ksession.setGlobal("result", result);

ksession.fireAllRules();
System.out.println("The Result is "+ksession.getGlobal("result").getResult()));



Output of the code when the student scored less than 40 :

The Resutl is FAIL

No comments:

Post a Comment