Introduction to Drools

Prem Kumar Singh
Deskera Engineering
4 min readApr 27, 2020

--

Why Drools?

Drools is a Business Rule Management System (BRMS) solution. It provides a rule engine which processes facts and produces output as a result of rules and facts processing. Rules will be written in english language format which is easy to understand. It separate rules with other compilation code, which gives flexibility to change the rule without deploying the component.

What are Drools Basic?

We are going to look into Drool basic concepts

Facts — represents data that serves as input for rules
Working Memory — a storage with Facts, where they are used for pattern matching and can be modified, inserted and removed
Rule — represents a single rule which associates Facts with matching actions. It can be written in Drools Rule Language in the .drl files or as Decision Table in an excel spreadsheet.
Knowledge Session — it holds all the resources required for firing rules; all Facts are inserted into session, and then matching rules are fired
Knowledge Base — represents the knowledge in the Drools ecosystem, it has the information about the resources where Rules are found, and also it creates the Knowledge Session
Module — A module holds multiple Knowledge Bases which can hold different sessions

How to implement Drools in Spring application?

  1. Maven dependencies: In order to start with drools we need to add couple of dependencies in pom.xml

<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>7.1.0.Beta1</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>7.1.0.Beta1</version>
</dependency>

2. Java Changes

Step 1 : We need to set the KieFileSystem bean, this is an in-memory file system provided by the drool framework. Below is the code snippet to set it programatically.

public KieFileSystem kieFileSystem() throws IOException {
KieFileSystem kieFileSystem = getKieServices().newKieFileSystem();
for (Resource file : getRuleFiles()) {
kieFileSystem.write(
ResourceFactory.newClassPathResource(
RULES_PATH + file.getFilename(), "UTF-8"));
}
return kieFileSystem;
}

Note: RULES_PATH denotes the location of rule files on the file system. We can keep the rule files in classpath, typically /src/main/resources in case of a Maven project.

Step 2 : We need to set the KieContainer which is a placeholder for all the KieBases for particular KieModule. KieContainer is built with the help of other beans including KieFileSystem, KieModule, and KieBuilder. The buildAll() method invoked on KieBuilder builds all the resources and ties them to KieBase. It executes successfully only when it’s able to find and validate all of the rule files:

public KieContainer kieContainer() throws IOException {
KieRepository kieRepository = getKieServices().getRepository();
kieRepository.addKieModule(new KieModule() {
public ReleaseId getReleaseId() {
return kieRepository.getDefaultReleaseId();
}
});
KieBuilder kieBuilder = getKieServices()
.newKieBuilder(kieFileSystem())
.buildAll();
return getKieServices().newKieContainer(kieRepository.getDefaultReleaseId());
}

public KieSession kieSession() throws IOException {
return kieContainer().newKieSession();
}

All the defines rules are fired by opening a KieSession bean as mention in above code snippet.

Note: Details of Kie api docs are available at https://docs.jboss.org/drools/release/7.5.0.Final/kie-api-javadoc/

How to implement Rule ?

We’ll explore the rule implementation by an example of categorizing an applicant for a specific role, based on his current salary and number of years of experience he has. In order to create rule we have to create a rules file for Drools (.drl). This file contains the rule definition in a declarative way. In this file, we can write a set of rules that will be fired at the run time. We will keep this file in classpath (/src/main/resources) for maven project.

Syntax of Rule defined in .drl file is mention below.

Rule <Rule Name>

when

<condition>

then

<Action>

End

Below is the code snippet of RoleSuggestion.drl file for the example we took for explanation.

package com.test.drools.rules;
import com.test.drools.model.Applicant;
global com.test.drools.model.RoleSuggestion roleSuggestion;

rule “Suggest Role”
when
Applicant(experienceInYears > 10)
Applicant(currentSalary > 1000000 && currentSalary <= 2500000)
then
roleSuggestion.setRole(“Manager”);
end

This rule will be fired by inserting the Applicant and RoleSuggestion facts in KieSession.

public RoleSuggestion suggestRoleForApplicant(
Applicant applicant,RoleSuggestion roleSuggestion){
KieSession kieSession = kieContainer.newKieSession();
kieSession.insert(applicant);
kieSession.setGlobal(“roleSuggestion”,roleSuggestion);
kieSession.fireAllRules();
}

This can be verified by executing the below test.

@Test
public void whenRuleMatching_ThenSuggestManagerRole(){
Applicant applicant = new Applicant(“Prem”, 35, 1600000.0,11);
RoleSuggestion roleSuggestion = new RoleSuggestion();
applicantService.suggestRoleForApplicant(applicant, roleSuggestion);
assertEquals(“Manager”, roleSuggestion.getRole());
}

Let’s understand Drool keyword used in above example.

package — this is the package name we specify in the kmodule.xml, the rule file is located inside this package

import — this is similar to Java import statement, here we need to specify the classes which we are inserting in the KnowledgeSession

global — this is used to define a global level variable for a session; this can be used to pass input parameter or to get an output parameter to summarize the information for a session

Rule: A rule is nothing but the logic that will be applied to incoming data. It has two main parts: when and then.

When: Determines the condition on which the Rule will be fired.

Then: The action; if the rules met the condition, they defines what work this rule performs.

Conclusion:

We have explored making use of Drools as a business rule engine in our application. There are multiple way of writing rules, we can also use decision tables which provide capability of defining rule in pre-formatted Excel sheet.

--

--