Tuesday, July 28, 2015

Simple Drools using Maven


Lets create a simple Drools example using Maven

  • Open Eclipse IDE
  • File -> New maven project
  • choose the simple maven project
  • enter the Group Id and Artifact Id as below
    • Group ID    : com.droolstutorials.examples.drools
    • Artifact ID  : Drools6.2Example
  • click Finish.




A pom.xml will be created in the project .
Add the below dependencies to it.

    <dependencies>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-compiler</artifactId>
            <version>6.0.0.CR1</version>
        </dependency>
        <dependency>
            <groupId>org.drools</groupId>
            <artifactId>drools-core</artifactId>
            <version>6.0.0.CR1</version>
        </dependency>
    </dependencies>
Your final pom.xml will look like this. 


Lets create a Rule Executor file 
Lets first create a package as below 
  • src.main.java.com.droolstutorials.examples.drools.controller
and then create the java file as
  • RulesExecutor
RulesExecutor.java

package com.droolstutorials.examples.drools.controller;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieRepository;
import org.kie.api.builder.Message.Level;
import org.kie.api.io.KieResources;
import org.kie.api.io.Resource;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class RulesExecutor {
    public void runRules(String[] rules, Object[] employees) {
        KieServices kieServices = KieServices.Factory.get();
        KieResources kieResources = kieServices.getResources();
        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        KieRepository kieRepository = kieServices.getRepository();

        for (String ruleFile : rules) {
            Resource resource = kieResources.newClassPathResource(ruleFile);
            kieFileSystem.write(
                    "src/main/resources/com/droolstutorials/examples/drools/"
                            + ruleFile, resource);
        }

        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();

        if (kb.getResults().hasMessages(Level.ERROR)) {
            throw new RuntimeException("Build Errors:\n"
                    + kb.getResults().toString());
        }

        KieContainer kContainer = kieServices.newKieContainer(kieRepository
                .getDefaultReleaseId());

        KieSession kSession = kContainer.newKieSession();

        for (Object emp : employees) {
            kSession.insert(emp);
        }

        System.out.println("rules int "+kSession.fireAllRules());

    }
}

 


Lets now create a package as below 
  • src.main.java.com.droolstutorials.examples.drools.model
and then create the java file (model) as
  • Employee
Employee.java 
package com.droolstutorials.examples.drools.model;

public class Employee {
    private String name;
    private String type;

    public Employee(String name, String type) {
        this.name = name;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setAge(String type) {
        this.type = type;
    }

}
Lets now create a package as below 
  • src.main.resources
and then create the .drl file as
  • Employee.drl

import com.droolstutorials.examples.drools.model.Employee

dialect "mvel"

rule "onsite"
    when
        $employee : Employee(type.equals("onsite"))             
    then
        System.out.println("onsite :: "+$employee.name);
    end

rule "name without a"  
    when
        $employee : Employee(!name.contains("a"))  
    then
        System.out.println("name without a :: "+$employee.name);
    end
Now its time for creating the Main class to test it.
Create the main class in the below locaton
  • src.main.java.com.droolstutorials.examples.drools
Main.java
package com.droolstutorials.examples.drools;

import com.droolstutorials.examples.drools.controller.RulesExecutor;
import com.droolstutorials.examples.drools.model.Employee;
 
public class Main
{
    public static void main(String[] args)
    {
        RulesExecutor runner = new RulesExecutor();
        String valStr="";
        Employee naren = new Employee("Narendar", "onsite");
        Employee karthi = new Employee("KarthiK", "offshore");
        Employee ehfaj = new Employee("Ehfaj", "onsite");
        Employee bala = new Employee("Bala", "offshore");
        Employee pintu = new Employee("Pintu", "offshore");
               
        String[] rules = { "Employee.drl" };
        Object[] employees = {naren, karthi, ehfaj, bala, pintu};

        runner.runRules(rules,employees);
    }
Now run the Main as java application and you can see the drools rules getting executed. 
Happy Drooling... 
 

Drools Basics - Definitions


Definitions...


Documentation
https://docs.jboss.org/drools/release/6.0.1.Final/drools-docs/html_single/


  • KieBase: repository of all the application’s knowledge definitions. It will contain rules, processes, functions, type models. The KieBase itself does not contain runtime data, instead sessions are created from the KieBase in which data can be inserted and process instances started. 

  • KieModule: container of all the resources necessary to define a set of KieBases like a pom.xml defining its ReleaseId, a kmodule.xml file declaring the KieBases names and configurations together with all the KieSession that can be created from them and all the other files necessary to build the KieBases themselves.

  • KieContainer: A container for all the KieBases of a given KieModule.

  • KieFileSystem: in memory file system used to programmatically define the resources composing a KieModule.

  • KieBuilder: a builder for the resources contained in a Ki

Drools Basics


What basically is Drools.. 
Drools is an Object-Oriented Rule Engine for Java.
Its a rule based management framework, which takes care of giving you the output based on the condition you feed. simple right.. 

eg., 

Rule 1:
if you like this blog ?
read through

Rule 2:
if you dont like it?
you can Google drools :) 




Basically what happens is like we give the input as 
set of rules and
set of data
to the Drools engine. The Drools engine executes the rule (if.. then.. else) and gives the output as 
Data Objects.


Rule is basically has a condition, if it becomes true, it initiates some actions.
Ok now lets write a bit technically valid rule and here it comes

rule "checkAmount"
when
$accountNumber : Account( money < 1000 )
then
  AccountHolder.message($account.money);
end


Once the User has his balance less than 1000 bucks.. we are sending him an message. 


Advantages of Drools are 
  • they are flexible  
  • reusable 
  • easy to understand language unlike procedural languages.

http://www.drools.org/
will give the required jars and documentation.

Overall flow:







Facts           : Data to be processed 
Fact model  : the model / pojo class written in java
Rule Engine : applies the rules from .drl files / excel sheet into the facts and gives the output.