Thursday, September 17, 2015

Introduction to Rules Engine using Drools Expert

Rules Engine 
Business Rules Engines are required to execute one or more rules in an Enterprise or Software System. The ability to maintain and execute rules as separate from the application code is the greatest advantage of such engines. Business Rules Engine are a form of Expert System. Expert System in the most simple terms, allows human expert-like decision making abilities.


Business Rules Engine are, primarily, of two types and classified on the basis of how rules are scheduled for execution.

Forward Chaining (Data-Driven)
1. Inference Engine: These are based on a set of 'If-Then' kind of behaviors or evaluations.
2. Reaction Rules: These are used to process event patterns and perform actions.  
Backward Chaining (Goal-Driven)
1. It tries to resolve facts based on particular goals.


Drools Expert
Drools Expert works on the basis of Rete/Rete-OO Algorithm. Drools is an open-source project that has the following major components
  • Drools Guvnor (Business Rules Manager) [A Centralized Repository for Drools Knowledge Bases]
  • Drools Expert (Rules Engine) – [Uses the rules to Perform Reasoning]
  • Drools Flow (Process/Workflow), or jBPM 5 – [Provides for Workflow and Business Processes]
  • Drools Fusion (Event Processing/Temporal Reasoning) – [Provides for Complex Event Processing]
  • Drools Planner/OptaPlanner (Automated Planning) – [Optimizes Automated Planning, including NP-Hard Planning Problems]
A block diagram of the Rete/Rete-OO is given below. The Rete Algorithm requires an extensive discussion, which I am not scoping into this blog entry.


Use-Case(s) Implement Here [To Demonstrate Drools Expert]
1. If the 'Source IP' is a Specific IP and the 'Source Port' is a Specific Number, then mark the 'Event' as 'Blacklisted' [Unsafe Event Detection]
I will demonstrate only this particular use-case in this blog entry (including how to run the 'Intelligent Data Loader') to understand rules engine processing. You may need to do the following before you can download and run the code:

A. Download Drools 6.1.0 Distribution (Include in Classpath)
B. Download the Eclipse Plugin for Drools (Include in Classpath)
C. Use JDK 1.8.0 and JEE 1.7 Libraries (If Required) (Include in Classpath)
D. Brief Read on MVEL Dialect and Drools Expert (Above/Official)   

1. Start a Java Project in Eclipse [Classpath]
You may choose to start a 'Java' project only as opposed to a 'Drools' project. Then include the following JARs in the classpath:

2. The Directory / Folder Structure should Include a 'resources' as Source Folder 

3. Create the Drools Expert Configuration File (kmodule.xml)
 <?xml version="1.0" encoding="UTF-8"?>  
 <kmodule xmlns="">  
   <kbase name="rules" packages="rules">  
     <ksession name="ksession-rules"/>  

4. Create the Rule using 'mvel' Dialect
The creation of your first rule using 'mvel' dialect though should not be a very difficult task for the experience Java developer. I am not explaining the use-case implementation detail, except that it checks if the source ip and source port are equal to a specific number.

 // list any import classes here.  
 // use case 01  
 // detect if we can blacklist a specific ip and port access  
 rule "Port and IP Blacklist Rule"  
 dialect "mvel"  
    $sampleEvent:SampleEvent(eventSourceIp=="", eventSourcePort=="8080")   
       System.out.println("***** Blacklisted IP and Port Detected in Event with Remarks - " + $sampleEvent.getEventRemarks());  

5. Develop the Core Rules Engine Processing Class
Instantiate the important Drools Runtime objects as shown below. You may also understand from the below code, how to include and refer the rules file (.drl) from the classpath.

      private static SampleRulesEngine reService = null;  
      // Drools Expert Runtime Configuration  
      private KieServices ks;  
      private KieContainer kContainer;  
      private KieSession kSession;  
      public static SampleRulesEngine getInstance() {  
           if(reService==null) {  
                reService = new SampleRulesEngine();  
           return reService;  
      public void init() {  
           try {  
                System.out.println("initializing kie runtime for drools expert...");  
                ks = KieServices.Factory.get();  
                kContainer = ks.getKieClasspathContainer();  
                KieSessionConfiguration sessionConfiguration = KnowledgeBaseFactory.newKnowledgeSessionConfiguration();  
                kSession = kContainer.newKieSession("ksession-rules", sessionConfiguration);  
                System.out.println("initialized the kie runtime for drools expert...");  
           } catch (Exception e) {  

6. Build a Data Loader (To Inject Positive Test Cases and Load Test) 
There is a data loader that starts internally a threaded loading mechanism for sending multiple events to the Drools Expert Runtime. You have to make sure that you 'Inject' a positive test case at every interval, to test out the functionality of Drools Expert. The Java Event Object in our example is "SampleEvent".

7. Output of Running the SampleDataLoaderDriver [Rules Engine Output]

There are other rule forms that you may use such as Decision Tables. It is only a matter of configuration, classpath, regular expressions and a straightforward understanding of .xls files to create Decision Tables. Also, I recommend that you make sure that you use Microsoft Excel to edition the Decision Table Spreadsheet, else you may end up with weird issues. 

 Download the entire Sample Rules Engine Code in Drools 6.1.0 as a Eclipse Project (.ZIP)

No comments: