Tutorial - Deduct new facts SourceForge.net Logo
 Home
 Documentation
 To do
 Download
 Project page
 JSR-94

How to use the rule engine to deduct new facts

JRuleEngine can be used to deduct new facts. Facts are org.jruleengine.Clause objects, which have two attributes:

  • name i.e. property name
  • value i.e. property value
Clause object can be added to the rule engine and these object are used by the rule engine to deduct new Clause objects.
Variables can be included in leftTerm or rightTerm of an if rule condition. Variable syntax is: ":variableName"
JRuleEngine replaces variable names with variable values in the then action rule.

Example

The following is an example of XML file which contains a simple deduction rule:

 <?xml version="1.0" encoding="UTF-8"?>
 <rule-execution-set>
   <name>RuleExecutionSet1</name>
   <description>Rule Execution Set</description>
 
   <synonymn name="prop" class="org.jruleengine.Clause" />
 
   <!--
   if :X is human then :X is mortal
   -->
   <rule name="Rule1" description="if :X is human then :X is mortal" >
    <if leftTerm=":X" op="=" rightTerm="is human" />
    <then method="prop.setClause" arg1=":X" arg2="is mortal" />
   </rule>
 
 </rule-execution-set>


This rule can be used to deduct that a specific human is mortal, as in the following sample java code:

  // create a StatefulRuleSession
  StatefulRuleSession statefulRuleSession =
   (StatefulRuleSession) ruleRuntime.createRuleSession( uri,
   new HashMap(),
   RuleRuntime.STATEFUL_SESSION_TYPE );
 
  System.out.println( "Got Stateful Rule Session: " + statefulRuleSession );
 
  // Add some clauses...
  ArrayList input = new ArrayList();
  input.add(new Clause("Socrate","is human"));
 
  // add an Object to the statefulRuleSession
  statefulRuleSession.addObjects( input );
  System.out.println( "Called addObject on Stateful Rule Session: " + statefulRuleSession );
 
  statefulRuleSession.executeRules();
  System.out.println( "Called executeRules" );
 
  // extract the Objects from the statefulRuleSession
  List results = statefulRuleSession.getObjects();
 
  System.out.println( "Result of calling getObjects: " + results.size() + " results." );
 
  // Loop over the results.
 
  Hashtable wm = ((StatefulRuleSessionImpl)statefulRuleSession).getWorkingMemory();
  Enumeration en = wm.keys();
  while(en.hasMoreElements()) {
   Object obj = en.nextElement();
   System.out.println("Clause Found: "+obj+" "+wm.get(obj));
  }
 
  // release the statefulRuleSession
  statefulRuleSession.release();


As you can see in the example above, facts can be put in the rule engine by adding Clause objects.
The added objects are used internally by the rule engine to deduct new Clause objects.


(c) 2006 by Mauro Carniel