Rules determine which opportunities are pursued.
The flow of projects, information, materials, and money are based on rules.
The Business Rule Engine together with a Workflow Engine, helps organize, automate, and optimize businesses.
Who use a Business Rule Engine
Insurance
- Automated underwriting
- Credit scoring
- Claims routing and management
- Fraud and money laundering detection
- Rating
- Suitability/Compliance
Financial Services
- Asset management
- Compliance
- Credit scoring
- Fraud detection
- Loan origination
- Pro-forma trading models
Ecommerce
- Content and access security
- Cross selling
- Sales configuration
Government
- Application processing
- Fee calculations
- Health and Human Services
- Retirement and Pensions
- Tax calculations
Manufacturing
- Forecasting, Planning & Scheduling
- Supply chain management
- Product configuration
Drools is a Business Rules Management System. It provides a core Business Rules Engine (BRE), a web authoring and rules management application (Drools Workbench) and an Eclipse IDE plugin for core development. It is written in Java. It is an open source project that is backed by JBoss and Red Hat, Inc.
Drools is split into two main parts:
- Authoring – Creation of Rules files (.DRL files). 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. It is the developer’s responsibility to write these rules as per business requirements.
- Runtime – Handling the activation. As a rules file contains a set of rules, the runtime creates memory load.
Drools Basic Concepts
- 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
- 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
- Knowledge Base (KieBase) – 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. KieBase is a repository of all the application’s knowledge definitions. It will contain rules, processes, functions, and type models. The KieBase itself does not contain data; instead, sessions are created from the KieBase into which data can be inserted and from which process instances may be started. Creating the KieBase can be heavy, whereas session creation is very light, so it is recommended that KieBase be cached where possible to allow for repeated session creation.
- Knowledge Session – it holds all the resources required for firing rules; all Facts are inserted into session, and then matching rules are fired. A Knowledge Session is created from the Knowledge Base. A Session is of two types:
- Stateless Knowledge Session
- Stateful Knowledge Session
- Agenda – It’s a logical concept. The agenda is the logical place where activations are waiting to be fired.
- Activations – Activations are the then part of the rule. Activations are placed in the agenda where the appropriate rule is fired.
- Module – A module holds multiple Knowledge Bases which can hold different sessions
- kmodule.xml – is the descriptor that selects resources to knowledge bases and configures those knowledge bases and sessions. kmodule.xml file defining in a declaratively way the KieBases and KieSessions that can be created from it. This file has to be placed in the resources/META-INF folder of the Maven project while all the other Kie artifacts, such as DRL or a Excel files, must be stored in the resources folder or in any other subfolder under it.
- KieContainer – reads all configuration files from the classpath; All the Java sources and the Kie resources are compiled and deployed into the KieContainer which makes its contents available for use at runtime.
Rules
Rule
A method for knowledge representation that will be applied to incoming data. Usually presented in the IF…THEN… form. It has two main parts:
- When – Determines the condition on which the Rule will be fired.
- Then – The action: if the rule met the condition, that defines what work this rule performs.
Rule syntax:
Rule [Rule Name]
when
then
End
Decision Tables
A decision table provides the capability of defining rules in a Excel spreadsheet. The advantage with Drools provided Decision Table is that they are easy to understand even for a non-technical person.
Facts
To create business rules, an appropriate fact model on which the business rules operate must be present. A fact is an instance of an application object represented as POJO.
Rules Processing Steps
- System parses all .drl rule files into the knowledge base.
- Each fact is asserted into the working memory.
- All rules and facts are evaluated by the rule engine and rule-facts pairs are created, based on which rules match against which set of facts.
- All the rule-facts combinations are queued within a data construct called an agenda.
- Finally, activations are processed one by one from the agenda, calling the rule consequences on the facts. Note that executing an activation can modify the contents of the agenda before the next activation is performed.
Example
1. Create a fact model.
Create a Plain old Java object (POJO) on which a rule will operate – Person.java:.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
public class Person { private String firstName; private String lastName; private Integer hourlyRate; private Integer wage; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Integer getHourlyRate() { return hourlyRate; } public void setHourlyRate(Integer hourlyRate) { this.hourlyRate = hourlyRate; } public Integer getWage(){ return wage; } public void setWage(Integer wage){ this.wage = wage; } } |
2. Create rule.
1 2 3 4 5 6 7 8 9 |
dialect "java" rule "Wage" when Person(hourlyRate * wage > 100) Person(name : firstName, surname : lastName) then System.out.println("Hello" + " " + name + " " + surname + "!"); System.out.println("You are rich!"); end |
Example: drools-first-example
Rules File Structure
package package-name
imports
globals
functions
queries
rules
Package and Import
We need to specify the package of the rule just the way we do it for java. Next follows the import statements.
1 2 3 4 5 6 7 8 9 10 11 |
package myfirstproject.rules import blog.zciok.bpm.model.Order; import blog.zciok.bpm.model.Order.Category; rule "Order - Mid Range" when $order: Order(200 < quantity, quantity < 300) then $order.setCategory(Category.MIDDLE); end |
Where Order.java is:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package blog.zciok.bpm.model; import java.io.Serializable; public class Order implements Serializable { public enum Category { NA, LOW, MIDDLE, HIGH }; private static final long serialVersionUID = 1L; private Integer quantity; private Category category; public Order() { } public Order(Integer quantity) { this.quantity = quantity; this.category = Category.NA; } public Integer getQuantity() { return quantity; } public void setQuantity(Integer quantity) { this.quantity = quantity; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } } |
Comments in Rules
The special characters, # or // or /* … */, can be used to mark comments.
Variables in Rules
A variable name in Drools starts with a Dollar($) symbol.
- $order: Order()
- order is the variable for Order() class
Conditions in Rules
A rule can contain many conditions and patterns such as:
- $order: Order(200 < quantity, quantity < 300)
- Account(balance == 200)
Global Variables
Global variables are variables assigned to a session. We use a global variable if we want it to be available for all the rules defined.
drl file:
1 2 3 4 5 6 7 8 |
global java.util.List globalList; rule "Global" when eval(true) then globalList.add("Hello World"); end |
1 2 3 4 5 |
List list = new ArrayList(); kSession.insert(...); kSession.setGlobal("globalList", list); |
Functions in Rules
They can be used in conditions.
1 2 3 4 5 6 7 8 9 10 |
function String pendingItemKey(CartItem cartItem) { return cartItem.getCart().getCustomer().getId() + "-"+ cartItem.getProduct().getDesc(); } rule "Is Out-Of Stock" when $cartItem : CartItem(cartStatus != CartStatus.PROCESSED && product.getAvailableQty() == 0) then $cartItem.getCart().logItemError(pendingItemKey($cartItem)); end |
Example: globals-and-functions