Introduction to Drools Rules

This tutorial provides an introduction to JBoss Drools, covering the core concepts, how to bootstrap a Drools project, how to code a simple Drool rule file and which tools can be used to run the Drools runtime engine

Drools in a nutshell

Drools is a business-rule management system with an inference-based rules engine, which allows a fast and reliable evaluation of business rules and complex event processing. A rules engine is also a fundamental building block to create an expert system which, in artificial intelligence, is a computer system that emulates the decision-making ability of a human expert.

Drools is part of KIE (Knowledge Is Everything) which is an umbrella project that includes:

  • Drools Rule engine
  • jBPM which is a flexible Business Process Management suite
  • Business Central which is a full featured web application for the visual composition of custom business rules and processes.
  • Drools Planner which helps us to carry out automated planning, in order to optimize how we distribute and utilize resources in an organization, sometimes we need to consider multiple possible solutions and choose which works best for us.

Getting started with Drools

The Drools Rule engine is the heart of Drools. The Drools engine stores, processes, and evaluates data to execute the business rules or decision models that you define. The basic function of the Drools engine is to match incoming data, or facts, to the conditions of rules and determine whether and how to execute the rules.

The Drools engine operates using the following basic components:

  • Rules: Business rules or DMN decisions that you define. All rules must contain at a minimum the conditions that trigger the rule and the actions that the rule dictates.
  • Facts: are domain model objects (Plain Old Java Objects (POJOs)) used by Drools to evaluate conditions and execute consequences.
  • Production memory: location where rules are stored in the Drools engine.
  • Working memory: a stateful object which contains objects acted upon by business rules.
  • Agenda: location where activated rules are registered and sorted (if applicable) in preparation for execution.

When a business user or an automated system adds or updates rule-related information in Drools, that information is inserted into the Working Memory of the Drools engine in the form of one or more Facts.

The Drools engine matches those facts to the conditions of the rules that are stored in the Production Memory to determine eligible rule executions. (The process of matching facts with rules is often referred to as “pattern matching”.) When rule conditions are met, the Drools engine activates and registers rules in the Agenda, where the Drools engine then sorts prioritized or conflicting rules in preparation for execution.

Methods for authoring Drools Rules

The following methods are available for coding Drools Rules:

  • DRL files (drl and rdrl ) using the Drools Rule Language syntax.
  • Decision tables stored in an Excel/CSV spreadsheet (xsl, xslx) following a Drools template for defining Constraints and Facts.
  • Domain-Specific Language (DSL) rule files (rdslr) using a “natural” programming language that mimics the domain specific language. This provides business users more control of modeling decisions without a complex programming language.

We will provide an overview of DRL files. To see an example of Drools Decision Tables check this example: Getting started with Drools Decision Tables

Coding Drools Rules with DRL

Drools Rule Language (DRL) is a declarative language for writing rules that supports expressions written in multiple dialects. Currently, Drools supports two dialects:

  • Java
  • MVEL Expression Language

Rules are organized in the same way as Java packages and are stored in plain text DRL files. A rule is composed of:

  • A list of constraints on facts expressed as a series of WHEN statements.
  • An action executed by this rule if facts with the list of constraints are found in the working, specified as a series of THEN actions.

Taking as an example, the following Rule validates a Server configuration:

import com.sample.Server
rule "Check Server Configuration"
  when
  $server : Server( processors < 2 || memory<=1024 || diskspace <= 2048)
  then
  $server.setValid(false);
  System.out.println("Server "+ $server.getName() + " configuration does not meet requirements!");
end

How do we fire Drools Rules? we need to use an object called KIE Session.

KIE sessions

In order to insert facts in the Working Memory and fire rules, you need to reference a KIE session. The KIE session is in turn created from a KIE base or directly from a KIE container if you have defined the KIE session in the KIE module descriptor file (kmodule.xml) for your project.

For example, the following kmodule.xml file defines the following KIE Sessions for Rules, Processes and Decision Tables:

<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
    <kbase name="rules" packages="com.sample.rules">
        <ksession name="ksession-rules"/>
    </kbase>
    <kbase name="dtables" packages="com.sample.dtables">
        <ksession name="ksession-dtables"/>
    </kbase>
    <kbase name="process" packages="com.sample.process">
        <ksession name="ksession-process"/>
    </kbase>
</kmodule>

For test purposes, you can also leave an empty definition of KIE session in the kmodule.xml file. In this case, you will be using the default Kie Session:

<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://www.drools.org/xsd/kmodule">
   
</kmodule>

Stateless vs Stateful Kie Session

A stateless KIE session is a session that does not use inference to make iterative changes to facts over time. In a stateless KIE session, data from a previous invocation of the KIE session (the previous session state) is discarded between session invocations, whereas in a stateful KIE session, that data is retained.

In a stateless KIE session configuration, the execute() call acts as a combination method that instantiates the KieSession object, adds all the user data and executes user commands, calls fireAllRules(), and then calls dispose(). See the following example, which inserts some Server objects in the KieSession and then fires the Rules loaded:

KieServices kieServices = KieServices.Factory.get();

KieContainer kContainer = kieServices.getKieClasspathContainer();

KieBase kieBase = kContainer.getKieBase();

LOG.info("There should be rules: ");
for ( KiePackage kp : kieBase.getKiePackages() ) {
    for (Rule rule : kp.getRules()) {
        LOG.info("kp " + kp + " rule " + rule.getName());
    }
}

KieSession session = kieBase.newKieSession();

Server s1 = new Server("rhel7",2,1024,2048);
session.insert(s1);
session.fireAllRules();
assertTrue(s1.isValid());

Server s2 = new Server("rhel8",2,2048,4096);
session.insert(s2);
session.fireAllRules();
assertTrue(s2.isValid());

Building Drools projects

When using Maven, the recommended way to build Drools project is to include the Drools BOM in your dependencyManagement section, and the drools-compiler and kie-api as a dependency:

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-bom</artifactId>
        <type>pom</type>
        <version>${drools-version}</version>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.kie</groupId>
      <artifactId>kie-api</artifactId>
    </dependency>
    <dependency>
      <groupId>org.drools</groupId>
      <artifactId>drools-compiler</artifactId>
      <scope>runtime</scope>
    </dependency>
    ...
  <dependencies>

The Maven project for this example is available here: https://github.com/fmarchioni/mastertheboss/tree/master/drools/helloworld

Tools for writing Drools Rules

There are mainly two options for authoring Drools Rules:

  • Using JBoss Tooling for Eclipse: this option requires installing some tooling on the top of your Eclipse IDE. That’s the ideal option for developers and tester to get started.
  • Using the Business Central: this is an advanced Web application, which is part of the Process Automation Manager (PAM) suite, which includes a guided Rules authoring interface that will let you write your Rules from Business models without programming expertise.

Creating Rules with Drools Eclipse plugin

Drools provides an Eclipse-based IDE which requires to download and install the JBoss Tools Eclipse plug-in. This will provide you with all the dependencies you need to get going: you can simply create a new rule project and everything will be set in place for you. Then, it’s just a matter of adding a Business Rule Task to your Process, with the Rule definition:

drools introduction

Refer to the following tutorials for learning how to install and use the JBoss Tools plugin for Eclipse: Installing Drools plugin on Eclipse

Using the Eclipse plug-in for coding your Rules is not required though. Rule files are just textual input (or spreadsheets as the case may be) and the IDE (also known as Business Central) is just a convenience. In real-world scenario, where Rule developers don’t have deep developer’s experitse, it is recommended to use the Business Central and its guided Process and Rule designer.

Creating Rules with the Business Central

The Process Automation Manager (PAM) is a middleware platform for creating cloud-native business automation applications and microservices. It includes the following core components:

  • Business Central: provides a graphical environment for authoring Drool Rules (Business Rule Management System) and jBPM processes (Business Process Management System) and manage their deployments. It includes an embedded Maven repository that stores all the artifacts generated, and a Git repository that manages the updates made to the artifacts.
  • Kie Execution Server: is the runtime component of the PAM and can be deployed on any environment that supports Java EE application servers. It is in charge to execute the processes, rules, and planning execution from OptaPlanner.
  • KIE Controller: accessible from the Business Central web UI, the KIE Controller manages each application deployed on Process Automation Manager.

The following is an high level overview of the Business Central:

drools introduction

When editing Rules with the BRMS, maven is fully supported in both direction :

1. The BRMS can retrieve maven artifact from its local repository as well as from remote maven repositories.

2. The BRMS can act as a remote Maven repository and can be access from external maven builds.

To learn more about the Business Central, we recommend reading the following tutorial: Getting started with jBPM Business Central

Drools Community version and Enterprise version

Drools is available in two versions: a Community version and an Enterprise version, called Red Hat Decision Manager, which is supported by Red Hat

You can download the Community version of Drools from: https://www.drools.org/download/download.html

https://www.drools.org/

If you have an active subscription with Red Hat, you can access Red Hat Decision Manager from: https://access.redhat.com/products/red-hat-decision-manager/

Found the article helpful? if so please follow us on Socials