This post will explain , how to work with Jboss Drools.
Step 1: Open eclipse and install Drools plugin through Market place.
Help - Eclipse Marketplace- search for drools and install the same.
Step 2: Create a new Maven Project and add below code snippet in pom.xml
//created on: 7 Sep, 2017
package src.main.resources.rules
import com.sample.*;
//list any import classes here.
rule "We have an Best Cricketer"
salience 10
when
then
System.out.println("We have an Best Cricketer");
end
rule "Cricket Lives"
salience 10
when
then
System.out.println("Hurrah!!! Cricket Lives");
end
rule "Hello World"
when
Cricketer( name == "sachin" )
then
System.out.println( "Hello sachin" );
end
rule "Cricket Score above 50"
when
$cricketerDetails : Cricketer( score >= 50 )
then
System.out.println( "I'm best bat's man , my name is[ " + $cricketerDetails.getName() + "]and my score is["+$cricketerDetails.getScore()+"]");
end
rule "Cricket Score below 50"
when
$cricketerDetails : Cricketer( score < 50 )
then
System.out.println( "I'm not best bat's man , my name is[ " + $cricketerDetails.getName() + "]and my score is["+$cricketerDetails.getScore()+"]");
end
Step 3: Write a Simple Pojo Java class.
package com.sample;
public class Cricketer {
private String name;
private boolean honest;
private int score;
public Cricketer(){
}
public Cricketer(String name, boolean honest,int score){
this.name = name;
this.honest = honest;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isHonest() {
return honest;
}
public void setHonest(boolean honest) {
this.honest = honest;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
Step 4: Now Write a Test java class to execute the drool file.
package com.sample;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
public class BestCricketer {
public static void main(String[] args) {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession ksession = kContainer.newKieSession("ksession-rules");
Cricketer sachin = new Cricketer("sachin", true,70);
Cricketer dravid = new Cricketer("dravid", true,55);
Cricketer rohan = new Cricketer("rohan", true,100);
Cricketer ajay = new Cricketer("ajay", true,40);
ksession.insert( sachin );
ksession.insert( dravid );
ksession.insert( rohan );
ksession.insert( ajay );
ksession.fireAllRules();
}
}
Step 5: Output could be like below
We have an Best Cricketer Hurrah!!! Cricket Lives Hello sachin I'm best bat's man , my name is[ rohan]and my score is[100] I'm best bat's man , my name is[ dravid]and my score is[55] I'm best bat's man , my name is[ sachin]and my score is[70] I'm not best bat's man , my name is[ ajay]and my score is[40]More information about droolsMore Information on drools Thanks for viewing this post