Rate this page del.icio.us  Digg slashdot StumbleUpon

Introduction to Drools: Rules fall from your eyes

by

One of our long-time writers introduced us to Jaroslaw, a JBoss QA Engineer based in Poland, and mentioned that he’d been working on some documentation we might find interesting. And, boy, do we! This first piece de-mystifies the complex world of rules engines. Whether you call it Drools, or JBoss Rules, or JBoss Drools… you still might want to know what it does and how it functions in your technical environment. (Not to mention that it’s just all kinds of logical and interesting–if you like brainteaser word puzzles or abstract math questions, this qualifies as pleasure reading.)

This article is presented here in its entirety (with a trackback). The original can be found on Jaroslaw’s site. This article is also available in German and Polish.

Justification:

Either you’re a developer, architect or a business analyst, it’s worth to get familiar at least with the first chapter of this article. It contains an introduction into the world of rule engines, which increase the readability of certain applications and make them easier to manage and to maintain. It applies to apps that take decisions, which depend on events or a state of some objects.

Abstract:

This article contains an introduction to rule engines, a description of an installation of Eclipse IDE and a guide how to configure Eclipse with the Drools Workbench plug-in.

  1. A Rule Engine
  2. Drools
  3. Advantages of the Drools rule engine
  4. BRMS
  5. Production rules vs. events
  6. Let’s get started!
  7. What happened?
  8. Summary

A Rule Engine

A rule engine is a piece of software, which having some knowledge is able to perform conclusions. Knowledge and inferences are stored in rules, which are called production rules. In other words, production rules consist of conditions and actions, which are executed when their conditions are true. Besides that there’s a working memory, which stores all objects we may want to use while making a decision. The state of this memory can vary, because actions can add, delete or change existing objects. Moreover rules can get into a conflict. This happens when there are more than one rule which are true, at the same time. Then conflict resolution is provided by the agenda. It arranges the order of actions, which has been selected to be run. The agenda is an important part of a rule engine, because the execution of an action may invalidate a rule and in consequence cancel another action. To sum it up, a rule engine can be presented as follows:

fig1-1_rule_engine_en

Rule engines perfectly fits to:

  • calculate a discount of orders based on the amount or price
  • determine an insurance policy dependent on the age of the driver and the value of the car
  • make a diagnosis
  • detect imminence of failure
  • solve riddles

Drools

One of the open source implementations of a rule engine is Drools. It’s a Java library distributed under the Apache license. It’s available as as a binary and a source download. You can get it and use in your applications for free.

The heart of a rule engine is an inference engine. Its job is to match facts and rules (pattern matching) to make conclusions which ends in running actions. This matching is done by the RETE algorithm, which has been extended by object oriented concepts.

As I already mentioned, knowledge is presented in form of production rules. Knowledge representation, which is a way to provide the rule engine with data, is based on FOL – first order logic. FOL allows to evaluate expressions like 2 + 3 == 5 or customer.age > 17.

The two main parts of a production rule are its condition(s) and action(s):

when
	Customer (age > 17)
	then
	System.out.println("Customer is full age");

The rule above is going to evaluated as true for all those facts, which represents full age customers. A similar sql query would look as follows:

SELECT * from Customers c WHERE c.age > 17

There are two ways to determine the truth of a rule (condition) and run its action in consequence. Forward chaining is driven with facts. Rules are checked, which conditions are true for facts being in the working memory. The process of pattern matching finishes, when there are no more rules left, whose conditions are true. Backward chaining on the other hand is a goal
driven approach. Only those rules are checked, whose actions can be matched with a goal. If that is the case, conditions of that rule are evaluated.

Advantages of the Drools rule engine

  • separates your application from conditions which control the flow
    • rules are stored in separate files
    • rules can be modified by different groups of people
    • changing rules does not require to recompile or to redeploy the whole application
    • putting all rules into one place makes it easier to control or manage the flow of the application
  • rules can replace complex if – then statements in an easy and readable way
    • the rule language is not very difficult to learn
    • a plug-in for Eclipse IDE makes it easier to write rules and allows to have a look at the RETE tree
  • problems are not solved using a complicated algorithm, but via rules, which are easier to read and understand than
    code

    • with declarative programming you are focused on WHAT you are solving, and not HOW
    • a group of problems can be easily solved with rules, where the algorithmic approach may be unusable (too complex, too time consuming, etc)
  • access to the reasoning process allows you to understand why a particular decisions has been made

Summing up a rule engine should be considered when the solution of a problem seems complex or simply the algorithm contains a lot of it – then or switch statements. Rules should be also taken into account, when logic that drives your application often changes or has to be managed by people who don’t (or shouldn’t) have access to the application itself (to recompile/redeploy it).

BRMS

Drools is not just a rule engine. It provides also an application for managing rules, called Business Rules Management System. It allows to create, modify, delete, branch and persist rules. Moreover it’s possible to assign roles to users and a login mechanism and LDAP integration makes it easy to introduce security. So for example, a business analyst may have access to modify a rule, a developer on the other hand may be able only to read it. A BRMS is a single point of truth.

Production rules vs. events

Production rules consists mainly of conditions (when) and actions (then), e.g. when there’s a customer, who has a driving license for less than 5 years, then offer her an expensive insurance. Other type of rules are events (event condition action). In that case a rule engine looks for event patterns to match registered events. An event may be selling the last item or a breakdown of traffic lights. Another difference is the moment, when actions are executed. In the production rules environment, it’s the developer, who decides, when the rule engine is going to fire all actions. However, when working with events, an action is fired, when the associated event did happen.

Let’s get started!

… and install an IDE. I’ve chosen Eclipse, because it’s good enough and Drools provides a plug-in for writing rules.

Eclipse IDE, Eclipse IDE for Java EE Developers (eclipse-jee-europa-winter-linux-gtk.tar.gz)

After you’ve downloaded it, extract and start Eclipse. From the menu click on Help -> Software Updates -> Find and install… -> Search for new features to install -> New Remote Site…

fig1-2_install1

You can find the URL on the Drools downloads page under “Drools IDE Update Site”. It’s a link to the plug-in. For Drools 4.0.7 Eclipse Workbench for Europa 3.3 it is http://downloads.jboss.com/drools/updatesite3.3/

We choose OK and Finish. Eclipse will show the search results:

fig1-3_install2

Click on Next, accept the license and choose Finish, to start to download the plug-in. After that Eclipse will show another window, where we click on “Install all”. When asked for a restart we click on “Yes”. To verify a successful installation of the plug-in, make sure a new Drools icon showed up in the toolbar.

fig1-4_symbol

Let’s have a look at our first Drools application. Click on the Drools “head” and choose “New Rule Project”.

fig1-6_step0

Type a name for the project and click Finish. The Drools plug-in creates a standard layout and provides all the necessary libraries to get started. To run this application click on com.sample.DroolsTest and press “Shift + Alt + X” and then “J”. The console will show th following:

Hello World
	Goodbye cruel world

What happened?

This example has been described in the Drools documentation. I’m not going into detail what’s happening in DroolsTest.java, where the rule engine is initialized and rules are read. The more interesting part is the rule file itself, Sample.drl.

This file has two rules. At the beginning, the working memory contains one object of the class Message, whose fields message and status are set to “Hello World” and “0”. When fireAllRules() is called, all actions are going to be executed. It’s worth to note that conditions of rules are evaluated when an object is added into the working memory. The condition of the rule called “Hello World” is true, because there is an object in the working memory, which is a Message and has a status equal to “0”. Hence actions of this rule are going to be run. As a result, the status and message fields of that Message object are going to be modified. The update() command forces the rule engine to evaluate its rules again. This time the second rule’s condition is true and appropriate actions are executed.

Summary

This short introduction into the world of rule engines and the chosen implementation Drools showed their main characteristics and some potential fields of use. To get more familiar with this software I would suggest to read the Drools documentation.

All images and content copyright © 2008 Jaroslaw Kianowski. All rights reserved. Used with permission.

Related articles

2 responses to “Introduction to Drools: Rules fall from your eyes”

  1. rascunho » Blog Archive » links for 2008-07-23 says:

    […] Red Hat Magazine | Introduction to Drools: Rules fall from your eyes Either you’re a developer, architect or a business analyst, it’s worth to get familiar at least with the first chapter of this article. (tags: http://www.redhatmagazine.com 2008 mes6 dia23 at_tecp Drools explicação_introdutória article) […]

  2. Red Hat Magazine | Rules and Drools Rundown says:

    […] Two articles on Drools were published in Red Hat Magazine, Introduction to Drools: Rules fall from your eyes and JBoss Drools meets Hibernate. Both pieces are a good introduction to working with Drools. […]