How to code rules in Drools

I work for Davinci on the Skydoo project where the business rules are implemented in Groovy, which is an object oriented, dynamic and scripting Java platform language. I got a task to write rules in DSL (Domain specific language) MVEL for a new project. I went through many pages about the MVEL language and most of them were about the rules platform named Drools, so I dived in.

Drools is used everywhere and it grows rapidly, it is almost a standard. It is easy to find someone with Drools experience since it is frequently used by students and developers. There are many conferences, books and blogs about it. It is integrated in Spring, Camel (see Blog chapter 6), but it is also used in commercial products like Security Identity and Governance from IBM.

Drools was developed by companies JBoss and RedHat on Java platform. It is available under free ASL 2 license which allows developers to do any changes or fixes. Development environment is available as an open source plug-in for Eclipse. RedHat provides professional support in many countries.

Drools Guvnor is a centralized storage for the Drools Knowledge Base (see Blog chapter 2). It contains editors and tools for execution of many rules. Guvnor development environment is open source and integrated in Eclipse. Drools and Guvnor can also be integrated in application servers such as Oracle Weblogic or IBM Websphere and not only in JBoss.

Another development tool for rules is Corticon. Its development environment is open source as well and integrated in Eclipse. Engine is written in Java and .NET. Corticon uses SOA services. Big companies such as IBM, Oracle, SAP, TIBCO use Corticon in their products. Corticon is however not an expert system, its decision table is only a simple sequence engine. The decision table is described in this Blog, chapter 5. It means that rules aren't coded, they are written in the decision table. It is not a problem, but it hasn't got so many options as Drools, which I have chosen to look at. 

1. What to use Drools for? 

Example 1. Imagine that you apply for a mortgage. The bank, which evaluates your application, also controls whether you are at least 18 years old and whether your income is high enough to pay back the money, etc. If you meet these requirements you get the mortgage. If you don't, your application will be canceled. 

Example 2. Imagine that you own an e-shop. You want to prefer regular and registered customers. The new and registered customers get the discount of 2% and regular and registered customers get the discount of 5%. The next example describes this situation.

2. What is Drools?

Drools is an expert system based on knowledge. Gained knowledge is processed to create a Knowledge Base, which is then used to infer the solution. Rule engine processes unambiguous rules against a set of facts given as input. Rules are basically knowledge described as "When condition is true Then take the desired action".

Rules in Drools are usually defined in the MVEL expression language. At the beginning of the rule use the keyword rule and specify the rule name. After naming the rule you can list rule attributes and their values and then define the actual rule logic with the condition and action. Variables start with dollar symbol $ by convention.

Rule attributes:

  1. salience - it defines the order of running rules
  2. no-loop - it defines the number of runs. Rule doesn’t loop unless the running conditions have changed.
  3. dialect - MVEL or Java can be used for defining the rule action
  4. date-active - set the rules start date (valid from)
  5. date-expires - set the rules end date (valid to) 

 

Knowledge base is an interface that manages a set of rules and processes. The main task of the knowledge base is to store and re-use rules because creation of rules is very expensive.

Knowledge base provides methods for creating a Session. A session keeps the rules, facts and other resources. Data (facts) and rules are separated. Facts are rules data, from Java perspective they are implemented as POJO (Plain Old Java Object).

There are two types of knowledge sessions:

  • Stateless session takes some data and returns result. This session is used for validation and calculation.
  • Stateful session has longer life cycle and it allows iterative changes in time. This session is used for monitoring and diagnostic. 

3. Let's start to code.

We use development environment Eclipse with open source Drools plug-in. It allows for editing and managing of rules and getting prompt feedback in debug mode.

Let's code an example of an e-shop from the chapter 1. The customer adds items to the card. These products (items) are of a certain quantity (qty). If the customer is new, isNew == true.

 

public class Customer {
    private Cart cart;
    private String coupon;
    private boolean isNew;
      
    public static Customer newCustomer() {
        Customer customer = new Customer();
        customer.isNew = true;
        return customer;
    }
    public void addItem(Product product, int qty) {
        if (cart == null) {
            cart = new Cart(this);        
        }
        cart.addItem(product, qty);
    }
    //getters and setters for all variables
}

 

How to call the rules: 

//create session - compare below "Session_For_DRL_File.java" and Session_For_DecisionTable.java
KieSession kSession = createKieSession();
Customer newCustomer = Customer.newCustomer(); // isNew == true
Product p1 = new Product("Laptop", 15000);
Product p2 = new Product("Mobile", 5000);
newCustomer.addItem(p1, 1);
newCustomer.addItem(p2, 2);
kSession.insert(newCustomer);
kSession.fireAllRules();
kSession.dispose();

There are two options how to store rules:

  1. In rule files (see Blog chapter 4)
  2. In decision table (see Blog chapter 5)

For each of these options a new session must be created, this is described in next two chapters. 

4. Rules defined in rule file.

package com.javacodegeeks.drools
import com.javacodegeeks.drools.model.Customer;
import com.javacodegeeks.drools.model.Product;
rule "Discount for registred customer"
    when
        $customer:Customer($coupon: coupon == "DISC01")
    then
        $customer.getCart().addDiscount(((double)$customer.getCart().getTotalPrice())*0.05);
end
rule "Discount for new customer"
    when
        $customer:Customer($coupon: isNew == true)
    then
        $customer.getCart().addDiscount(((double)$customer.getCart().getTotalPrice())*0.02);
end

Configuration file kmodule.xml defines the rules folder.

How to create a session in drools file: 

KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
kSession = kContainer.newKieSession("ksession-rules"); 

5. The rules defined in Decision table.

 

How to create session for Decision table:

KieServices kieServices = KieServices.Factory.get();
KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
Resource resource = kieServices.getResources().newClassPathResource("shopping_cart_customer.xls");
kieFileSystem.write(resource);
KieBuilder kbuilder = kieServices.newKieBuilder(kieFileSystem);
kbuilder.buildAll();
KieRepository kieRepository = kieServices.getRepository();
KieContainer kContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId());
KieSession kieSession = kContainer.newKieSession(); 


6. Rules called via REST web services.

The simplest way to call Drools rules via REST web services is probably to use Spring Boot. Create a singleton bean with knowledge base. When a validation request is received, create new knowledge session, insert facts and execute the rules. If Spring is not used make sure the knowledge base is created only once. See this link for more info. The Guvnor rules can be called via REST web services as well. 

 

7. Sources to download and interesting links.

The source files of the above examples for Eclipse: Dools_DecisionTable.zip. To run rules in rules files use DroolsDrlFileExample.java.  To run rules in Decision Table use DroolsDecisionTableExample.java.

Java 8 was used in this example.

DSL in Drools & recommended and related post

Drools 5 tutorial

Drools 5 examples

Drools 6 tutorial

Drools 6 documentation

 

Publikované: 26. nov 2015 14:56 | Počet prečítaní: 9228
  • Marián Koleják

    Application Specialist & Tester

    Marián pracuje v Davinci na pozícii Application Specialist & Tester. Do kontaktu so svetom Javy prišiel relatívne neskoro po kontaktoch s konštrukciou strojov. Má rád všetko čo je jedinečné a originálne, no nepohrdne ani starou dobrou klasickou hudbou, slovenskou výtvarnou modernou, volejbalom, stolným tenisom, bedmintonom a turistikou.

We want you

Do you see yourself working with us? Check out our vacancies. Is your ideal vacancy not in the list? Please send an open application. We are interested in new talents, both young and experienced.

Join us