Over a million developers have joined DZone.

Rules Engines - Using Drools Expert

DZone 's Guide to

Rules Engines - Using Drools Expert

What helps make Drools special is the in-depth decision making it can do. Dive into the rules engine of Drools to see what makes it tick and how to use it.

· Java Zone ·
Free Resource

GitHub Link (Code Samples from the Article & More)

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

[Image credit: http://www.igcseict.info]

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.

[Image credit: http://www.amzi.com]

Drools Expert

Drools Expert works on the basis of the 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.

[Image credit: http://en.wikipedia.org]

Use-Case(s) Implemented Here (to Demonstrate Drools Expert)

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:

  1. Download Drools 6.1.0 distribution (include in classpath).

  2. Download the Eclipse Plugin for Drools (include in classpath) .

  3. Use JDK 1.8.0 and JEE 1.7 libraries (if required) (include in classpath) .

  4. 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, 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="http://jboss.org/kie/6.0.0/kmodule">  
   <kbase name="rules" packages="rules">  
     <ksession name="ksession-rules"/>  

4. Create the Rule Using the 'mvel' Dialect 

The creation of your first rule using the 'mvel' dialect though should not be a very difficult task for the experienced 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.

 package com.bw2015.sample.biz.re;  
 // list any import classes here.  
 import com.bw2015.sample.biz.vo.SampleEvent;  
 // 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, or else you may end up with weird issues. 

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

rules engines ,business rules ,artificial intelligence ,java ,knowledge management ,tutorial

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}