Home > Drools, J2EE > Drools Tutorial by Examples

Drools Tutorial by Examples

November 13th, 2010 Leave a comment Go to comments

Drools Tutorial
This post will show a simple example using  Drools 5.

Any Drools initialization process  involves Creation of KnowledgeBuilder, KnowledgePackage(s), KnowledgeBase and a session (statefull or stateless) created by KnowledgeBase.

In this example the rules are defined in basicRules.drl file(a simple text file).

At this example Account instances are validated against the rules during a statefull session while few facts are inserted in some points of the example. Firing rules also invoked few times.

It’s Important to understand that when a fact is inserted into the session it is validated against rules. If a rule is matched then it is added to the Agenda. Only when the fireAllRules is invoked the rules at the Agenda are executed.

Basic Drools Example

Facts: Account, Bonus

Rules : BasicRules.drl

package com.comp.drools;

import function com.comp.drools.DroolsHelper.error;
import function com.comp.drools.DroolsHelper.ok;

dialect "mvel" 

rule "Account balance is less than 100"
	no-loop
 when
  $account : Account( balance < 100 ) // condition
 then
  error(kcontext, $account); // consequence 
                                       //NOTE the kcontext is provided by drools
end

rule "Account balance is More than 100"
no-loop
 when
   $account :Account( balance > 100 ) // condition
 then
  ok(kcontext, $account); // consequence
                                    //NOTE the kcontext is provided by drools
end

rule "Bonus OK"
	no-loop
	dialect "java"
	when
		$account : Account(balance > 10)
		$b : Bonus()
	then
		modify($account){
			 setBalance((long)($account.getBalance() + $b.getAmmount()))
		};
end

rule "Bonus Exception"
	when
		$b : Bonus( ammount > 90)
	then
		System.out.println("Bonus Exception: " + $b.getAmmount());
end

SimpleRule.java
package com.comp.drools;

import java.io.File;
import java.util.Collection;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.runtime.StatelessKnowledgeSession;
import org.drools.runtime.rule.WorkingMemoryEntryPoint;

public class SimpleRule {

	/**
	 * @param args
	 */
	public static void main(String[] args)
               //Create KnowledgeBase...
                KnowledgeBase knowledgeBase = createKnowledgeBase();
                //Create a statefull session
		StatefulKnowledgeSession session = knowledgeBase.newStatefulKnowledgeSession();
		try {
                        //Create Facts and insert them
			Account account = new Account();
			account.setBalance(10);
			account.setName("N1");

			Account account2 = new Account();
			account2.setBalance(20);
			account2.setName("N2");

                        //Insert fact
			session.insert(account);
			session.insert(account2);

                        //Fire rules
			session.fireAllRules();

                        //Insert new bonus fact
			Bonus b = new Bonus();
			b.setAmmount(90);

                        //insert fact
			session.insert(b);
                        //Fire rules
			session.fireAllRules();

                       //Create new fact
			b = new Bonus();
			b.setAmmount(100);
                        //insert new fact
			session.insert(b);

			b = new Bonus();
			b.setAmmount(200);
			session.insert(b);

                        //Fire rules
			session.fireAllRules();

		} finally {
			session.dispose();
		}

	}

        /**
        * Create new knowledge base
        */
	private static KnowledgeBase createKnowledgeBase() {
		KnowledgeBuilder builder = KnowledgeBuilderFactory.newKnowledgeBuilder();
                //Add drl file into builder
		File drl = new File("C:\\basicRule.drl");
		builder.add(ResourceFactory.newFileResource(drl), ResourceType.DRL);
		if (builder.hasErrors()) {
			throw new RuntimeException(builder.getErrors().toString());
		}

		KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase();
                //Add to Knowledge Base packages from the builder which are actually the rules from the drl file.
		knowledgeBase.addKnowledgePackages(builder.getKnowledgePackages());
		return knowledgeBase;
	}

}

In order to execute the example just run the SimpleRule.java relevant messages will pop up to the statndard output after fireAllRules method invoked.

DroolsHelper.java

   public class DroolsHelper{
       
        public static void ok(RuleContext rc, Account c){
              System.out.println("Rule: " + rc.getRule().getName());
        }

        public static void ok(RuleContext rc, Account c){
              System.out.println("Rule: " + rc.getRule().getName());
        }
   }
Categories: Drools, J2EE Tags: ,
  1. Sury
    March 6th, 2011 at 20:17 | #1

    Looks like its an incomplete example.
    import function com.comp.drools.DroolsHelper.error; MISSING
    import function com.comp.drools.DroolsHelper.ok; MISSING

    Where do you set kcontext global variable, etc.

    Can you also elaborate internal working of drools for multiple fireAllRules()?

    Its good example otherwise. Thanks.

  2. Sury
    March 7th, 2011 at 00:04 | #2

    Can you also write similar simple example for more advanced usage of Drools?

    I am interested in KnowledgeAgent, ResourceFactory.getResourceChangeNotifierService(), ResourceFactory.getResourceChangeScannerService()

    Thanks for your effort.

  3. March 9th, 2011 at 15:36 | #3

    Hi,
    Thanks for your comments.

    I added the missing methods. Its just a class with two static methods.
    Regarding kcontext, it’s an instance provided by Drools something like a session in jsp.

    Regarding more advanced examples I will soon load some.

    Rod

  4. xdyl
    January 18th, 2012 at 01:25 | #4

    can drools import a function that defined by a drools keywords “function”?
    i try it but i find it only worked in the same package.

    if a common function not in the same package with the caller drools.
    i cant use import function .

  5. Maganti Suryanarayana Murthy
    April 12th, 2012 at 08:05 | #5

    Few Mistakes are there in rule file. Few of them are
    1) getAmmount (correct one is getAmount)
    2) Here Account bean class is not given. When declaring balance declare it as long since in rule file its set as long.

  6. August 31st, 2012 at 01:45 | #6

    Thanks for your grateful Java Tutorial informations.

  7. September 26th, 2012 at 13:08 | #7

    is guvnor good to manage drools?

  1. No trackbacks yet.
You must be logged in to post a comment.