Drools Wellesley

From Training Material
Jump to navigation Jump to search

Basic

EX1

rule "exercise1"
when
	s : Salgrade()
then    
    System.out.println(
       s.grade + " " + 
       s.losal + "\t" + 
       s.hisal ) ;
end

EX2

rule "Exercise 2"
when 
  e : Emp(sal > 1000, sal <2000)
then    
	System.out.println(
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal + " " + 
       e.deptno );
end

EX3

rule "Exercise 3"
when 
  e : Emp(job == "CLERK", deptno == 20)
then    
	System.out.println("\n" +
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal + " " + 
       e.deptno );
end

EX4

rule "Exercise 4"
//enabled false
when 
  e : Emp(mgr != 0)
then    
	System.out.println(
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal + " " + 
       e.deptno );
end

EX5

rule "Exercise 5"
//enabled false
when 
  e : Emp(job == 'MANAGER')
then    
	System.out.println(
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal * 12 + " " + 
       e.deptno );
end

EX6

rule "Exercise 6"
//enabled false
when 
  e : Emp(name matches ".LA.*")
then
    System.out.println(
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal + " " + 
       e.deptno );
end

EX7

rule "Exercise 7"
when
	e : Emp(name matches ".*T.*N")
then
    System.out.println(
       e.id + " " + 
       e.name + "\t" + 
       e.job + "   \t" +
       e.mgr  + "\t" +
       e.hiredate + " " + 
       e.sal + " " + 
       e.deptno );
end

EX8

rule "Exercise 8"
when
	//e : Emp((job == "MANAGER" && deptno != 10) || (job != "MANAGER" && deptno == 10))
	e : Emp((job == "MANAGER" || deptno == 10) && !(job == "MANAGER" && deptno == 10))
then
    System.out.println(
       e.name + "\t" + 
       e.job + "   \t" +
       e.deptno );
end


        • ALTERNATE SOLUTION****
rule "Exercise 8"
//enabled false
when 
  e : Emp((job == "MANAGER" && deptno != 10) || (deptno == 10 && job != "MANAGER"))
then    
	System.out.println(e.name );
end
        • ALTERNATE ALTERNATE SOLUTION****
rule "Exercise 8a"
when 
  $e : Emp(job == 'MANAGER' || deptno == 10)
  not(exists(Emp($e.id == id, job == 'MANAGER', deptno == 10)))
then    
  System.out.println($e.id + " " + $e.name + " " + $e.job + " " + $e.mgr + " " + $e.hiredate + " " + $e.sal + " " + $e.deptno);  
end

Advanced

EX31

rule "Exercise 31"
when 
	$e: Emp()
	$d: Dept($e.deptno == deptno)
then    
    System.out.println( $e.name + "\t" +  $d.loc );
end

EX32

rule "Exercise 32"
when 
	$d: Dept()
	$e: Emp($d.deptno == deptno)
then    
    System.out.println( $e.name + "\t" +  $d.dname + "\t" + $d.deptno  );
end

EX33

rule "Exercise 33"
when 
	$e: Emp(sal > 2000)
	$s: Salgrade($e.sal >= losal, $e.sal <= hisal)
then    
    System.out.println( $e.name + "\t" +  $e.sal + "\t" + $s.grade  );
end

EX34

rule "Exercise 34"
when
   $d :Dept(loc == "LONDON")
   $e :Emp($d.deptno == deptno)
then    
  System.out.println($e.name + "\t" + $d.loc )
end

EX35

rule "Exercise 35"
when
   $d :Dept(loc != "LONDON")
   $e :Emp($d.deptno == deptno)
   $s :Salgrade($e.sal >= losal && $e.sal <= hisal)
then    
  System.out.println($e.name+ "\t" + $d.loc + "\t" + $s.grade )
end

EX36

rule "Exercise 36"
when
   $d :Dept()
   not (Emp(deptno == $d.deptno))
then    
  System.out.println( $d.dname )
end

EX37

rule "Exercise 37"
when
   $e :Emp()
   $m :Emp(id == $e.mgr)
then    
  System.out.println( $e.name + " boss is " + $m.name )
end

EX38

rule "Exercise 38"
when 
	$e: Emp($e.mgr == 0)
then    
    System.out.println( $e.name );
end
rule "Exercise 38"
when
   $e :Emp()
   not (Emp(id == $e.mgr))
then    
  System.out.println( $e.name)
end

EX39

rule "Exercise 39"
when 
	$e: Emp()
	not Emp( $e.id == mgr)
then    
    System.out.println( $e.name );
end

EX41

rule "Exercise 41"
when
   $m :Emp()
   $e :Emp($m.id == mgr, hiredate < $m.hiredate)
then    
  System.out.println( $e.name + " was hired in " + $e.hiredate + ", their boss " + $m.name + " was hired in " + $m.hiredate )
end

EX44

rule "Exercise 44"
when
   $e :Emp(deptno == 10)
   not Emp($e.job == job, deptno == 20)
then
  System.out.println( $e.job )
end

EX23

rule "Exercise 23"
//enabled false
when 
  accumulate (e :Emp(hiredate == 1981), 
  	$avg : average(e.sal),
  	$min : min(e.sal),
  	$max : max(e.sal)
  	) 
 
then    
	 System.out.println(
   "Average salary: " + $avg + "\n" +
  "Min salary: " + $min + "\n" +
  "Max salary: " + $max + "\n"
  )
end

EX24

rule "Exercise 24"
//enabled false
when 
  accumulate (e :Emp(), 
  	$min : min(e.sal),
  	$max : max(e.sal)
  	) 
 
then    
	 System.out.println($max - $min )
end
rule "Exercise 25"
//enabled false
when 
  accumulate (e :Emp(e.job == "MANAGER"), 
  	$count : count(e)
  	) 
 
then    
	 System.out.println($count)
end

Look at this beautiful examples:

rule "Exercise 26"
when
  $s : Integer() from accumulate (
    Emp(job == 'MANAGER'),
    init(int s = 0),
    action(s += 1),
    result(s) 
  )
then    
  System.out.println("Sum of Managers: " + $s);  
end

rule "Exercise 26b"
when
  accumulate (Emp(job == 'MANAGER'), $s: sum(1))
then    
  System.out.println("Sum of Managers: " + $s);  
end

EX25

declare SalByJob
   job : String
   avgSal : Double
end

rule "Exercise 25"
when
   Emp($j: job) and
   not SalByJob($j == job)
   accumulate ($e :Emp(job == $j), 	$avg : average($e.sal)   	) 
then    
   System.out.println($j + " " + $avg )
   insert(new SalByJob($j,$avg))
end


------------ other solution -------------------

declare CountedJob
	job: String
end

rule "Exercise 25"
when
	$e: Emp()
	not CountedJob(job == $e.job)
	accumulate (e1: Emp(job == $e.job),		$avg: average(e1.sal) )
then
  System.out.println( $e.job + "\t" + $avg)
  insert(new CountedJob($e.job))
end

EX27

declare SalByDep
   dep : int
   avgSal : Double
end

rule "Exercise 27"
when
   Emp($d: deptno) and
   not SalByDep($d == dep)
   accumulate ($e :Emp(deptno == $d), 	$avg : average($e.sal*12)   	) 
then    
   System.out.println($d + " " + $avg )
   insert(new SalByDep($d,$avg))
end

EX43

declare Jobs
   job : String
end

rule "Exercise 43"
// INCORRECT
when
   Emp($j: job, hiredate in (1982,1983)) and
   not Jobs($j == job) 
then    
   System.out.println($j )
   insert(new Jobs($j))
end
rule "43+"
when
	e1 : Emp(hiredate == 1982)
	e2 : Emp(hiredate == 1983)
	exists (Emp(e1.job == job, e2.job == job))
then
   System.out.println( e1.job)
end
declare xJob
   name : String
end

rule "Exercise 43" enabled true
when
  $e1:Emp($job:job && hiredate == 1982)
  $e2:Emp(job == $job && hiredate == 1983)
  not(xJob(name == $job))
then
  System.out.println($job)
  insert(new xJob($job));
end

EX28

rule "28 Find departments with more than 3 workers. "
when
  x: Dept(d: deptno) 
  accumulate (e :Emp(deptno == d), 
  	$count : count()
   	) 
  Number(doubleValue > 3) from $count
then    
   System.out.println(x.deptno + "  " + $count
)
end

EX45

EX46

EX51

EX55

inserLogical

rule

import com.nobleprog.FactModel.*
dialect "mvel" 

declare AccessToSecretFile
    emp : Emp
end

rule "Grant access to employees of Dept. 10"
when 
    e : Emp( deptno == 10 )
then    
    insertLogical( new AccessToSecretFile(e) )
end

jUnit

Shopping Example

Fact Model

package com.nobleprog;

public class FactModel{
	
	   public static class Customer {
		   private String name;
		   private int    discount;

	        public Customer(String name,
	                        int discount) {
	            this.name = name;
	            this.discount = discount;
	        }

	        public String getName() {
	            return name;
	        }

	        public int getDiscount() {
	            return discount;
	        }

	        public void setDiscount(int discount) {
	            this.discount = discount;
	        }

	    }

	    public static class Discount {
	        private Customer customer;
	        private int      amount;

	        public Discount(Customer customer,
	                        int amount) {
	            this.customer = customer;
	            this.amount = amount;
	        }

	        public Customer getCustomer() {
	            return customer;
	        }

	        public int getAmount() {
	            return amount;
	        }

	    }

	    public static class Product {
	        private String name;
	        private float  price;

	        public Product(String name,
	                       float price) {
	            this.name = name;
	            this.price = price;
	        }

	        public String getName() {
	            return name;
	        }

	        public float getPrice() {
	            return price;
	        }

	    }

	    public static class Purchase {
	        private Customer customer;
	        private Product  product;

	        public Purchase(Customer customer,
	                        Product product) {
	            this.customer = customer;
	            this.product = product;
	        }

	        public Customer getCustomer() {
	            return customer;
	        }

	        public Product getProduct() {
	            return product;
	        }
	    }

}

rules

package _30_mvel
import com.nobleprog.FactModel.*
import java.lang.Math
import java.util.ArrayList
dialect "mvel" 

rule "Purchase notification"
    //salience 10

    when
        $c : Customer()
        $p : Purchase( customer == $c )
    then
        System.out.println( "Customer " + $c.name + " just purchased " + $p.product.name );
end
 
rule "Discount removed notification"
    when
        $c : Customer()
        not Discount( customer == $c )
    then
        $c.discount = 0;
        System.out.println( "Customer " + $c.name + " now has a discount of " + $c.discount );
end

rule "Discount awarded notification"
    when
        $c : Customer()
        $d : Discount( customer == $c )
    then
        System.out.println( "Customer " + $c.name + " now has a discount of " + $d.amount );
end

rule "Apply 10% discount if total purchases is over 100"
    no-loop true
    dialect "java"
    when
        $c : Customer()
        $i : Double(doubleValue > 100) from accumulate (
                Purchase( customer == $c, $price : product.price ),
                sum( $price )
        )
    then
        $c.setDiscount( 10 );
		insertLogical( new Discount( $c, 10 ) );
        System.out.println( "Customer " + $c.getName() + " now has a shopping total of " + $i );
end

jUnit

package com.nobleprog;

import com.nobleprog.*;
import org.junit.Test;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;

import com.nobleprog.FactModel.*;

public class Test01 {
	@Test
	public void test1() {
		KieServices ks = KieServices.Factory.get();
		KieContainer kContainer = ks.getKieClasspathContainer();
		KieSession ksession = kContainer.newKieSession("ksession-rules");
        
		//KieSession ksession = kc.newKieSession("ShoppingKS");

        Customer mark = new Customer( "mark",
                                      0 );
        ksession.insert( mark );

        Product shoes = new Product( "shoes",
                                     60 );
        ksession.insert( shoes );

        Product hat = new Product( "hat",
                                   60 );
        ksession.insert( hat );

        ksession.insert( new Purchase( mark,
                                       shoes ) );

        FactHandle hatPurchaseHandle = ksession.insert( new Purchase( mark,
                                                                      hat ) );

        ksession.fireAllRules();

        ksession.delete( hatPurchaseHandle );
        System.out.println( "Customer mark has returned the hat" );
        ksession.fireAllRules();
	}
}