In this Drool tutorial we will learn the basis of JBoss Drools Rule engine and how to run a simple application on the top of it. Before getting into a simple example, we need to clarify some concepts about Rules, Rule engines and what is Drools.

What is a Rule Engine ?

The term Rule Engine can be referred to any system that uses rules, in any form, that can be applied to data to produce outcomes; it may refer to simple systems like form validation or more complex systems like dynamic expression engines. In a few words a Rule engine allow you to say "What to do" and not "How to do it".

Why using a Rule Engine ?

Rule systems are capable of solving very, very hard problems, providing an explanation of how the solution was arrived at and why each "decision" along the way was made.
Among the main benefit of a Rule engine can be mentioned:

  • Logic and Data Separation: Breaking your domain objects from business rules can lead to a mach easier to maintain application as it can shield from changes in the future, since the logic is all laid out in rules.
  • Speed and Scalability: Many times we apply "if" conditions that we didn't really need. The Rete algorithm, as implemented by Drools, replaces all of the if ... then statements with an optimized network.
  • Centralization of Knowledge: By using rules, you create a repository of knowledge (a knowledgebase) which can be considered as a single point of truth, for business policy (for instance) - ideally rules are so readable that they can also serve as documentation
  • Tool Integration: Writing rules means also to get accustomed with Rule language, validation and debugging. Eclipse provide an excellent tool to deliver and test your Rules.
  • Understandable Rules: JBoss Drools rules can make it easy to express solutions to difficult problems and consequently have those solutions verified (rules are much easier to read then code).Often, business users are more comfortable with expressing things that they know to be true, than to express things in an if...then format. Examples of things that you might hear from a business expert are:

"We need to buy that estate if the price is not over 1000000 $ and estate agency doesn't claim more then 5000 $"
"We buy shares when the price goes over 15 Euro before next week"

By focusing on what we know to be true, rather than the mechanics of how to express it in Java code, the above statements are much more clean than exposing it with traditional "if...then" clause

What is JBoss Drools?

Now that we know what a Rule system is, we need to clarify which are the components that make up the Drools ecosystem. The Rule Engine is made up of the following components:

Drools Fusion gives the rules engine the ability to perform event processing, often referred to as complex event processing ( CEP ).

jBPM is a means of describing some process that occurs within your organization as a series of steps involved, how those steps are connected, and who is involved in performing them. jBPM, which is based on the BPMN 2.0 specification, serves as a tool for describing such processes in a flowchart
format, giving visibility, clarity, and organization to processes that might otherwise be lacking. jBPM supports the entire process lifecycle, from development to execution and management up to retirement.

Drools Guvnor provides us with a centralized repository with a layer of user authentication in which we can store and manage our rules, processes, models, and other entities related to knowledge bases.

Drools Planner 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.

Business Central Workbench: Business Central Workbench is the web application and repository to govern Rules and Business Process. Within the Business Central, you can design and deploy your assets. It was formerly known as the Kie WorkBench.

The following picture depicts the main components of Drools architecture:

drools tutorial | getting started with drools

Developing applications with JBoss Drools

In order to run a basic example of JBoss Drools you can use two main approaches:

1) Download the Drools Runtime from http://www.drools.org/download/download.html and import the libraries in your favorite IDE, like Eclipse.

2) Use a Maven project and add Drools dependencies in it.

In this tutorial we will show how to create a simple project using Eclipse with Drools Plugin. If you want to check how to install the Drools Plugin on Eclipse / JBoss Developer Studio, check this tutorial: Installing Drools plugin on Eclipse

An Hello World Drool Project

With the Drools plugin activated, you will be able to create a New Drools project from the "New..." Menu

wizarddrools 

Click Next. In the following Window, choose the initial project contents. We will just need a blank project with the correct Maven folders:

wizarddrools2

In the last screen you have to choose where Drools libraries are to be found:

drools tutorial example

As you can see from the above screen, you have two options:

1. Specify where the Drools Runtime is located

2. Specify the Maven GAV

In case you have already downloaded the Drools Distribution zip from http://www.drools.org/download/download.html you can simply choose to Add Runtime selecting the "binaries" subfolder of your Drools Distribution:

drools tutorial example

Now the project will be created so we can add two core pieces:

  1. A simple Rule which interacts with a Java instance (a fact) passed to the Rule
  2. A Java main class to execute the Rule

Let's add at first a new Rule. From the File menu choose to add a new Rule:

drools new rule

As you can see, you will be requested to enter a Rule file name and the Type of resource Rule. In our case we will create the Rule.drl file name as part of a rule package. The rule will be in the rules package name. Here is the simple Rule:

package drools

import com.sample.Message;

rule "Hello World"
dialect "mvel"
when
m : Message( status == Message.HELLO, message : message )
then

modify ( m ) { message = "Goodbye cruel world",
status = Message.GOODBYE };
System.out.println( message );
end

rule "Good Bye"
dialect "java"
when
Message( status == Message.GOODBYE, message : message )
then
System.out.println( message );

end

This example is provided with 2 Rules: the first Rule ("HelloWorld") checks the value of the field status in the class Message, if the value equals to the constant Message.HELLO then a new value for status is setted and a goodbye message is printed.

On the other hand the "Good bye" Rule will check as well the value of field status. If it's equal to Message.GOODBYE then we've reached the bottom of our Rules and we exit printing a message.

Everything clear ? maybe not. Let's see closer a few pieces of this Rule:

m : Message( status == Message.HELLO, message : message )

What does this mean ?

This is the Pattern element: the most important Conditional Element. It consists of zero or more constraints and has an optional pattern binding. A constraint can be either a Field Constraint, Preducate or a Constraint Group. Constraints can be separated by the following symbols ',', '&&' or '||'.

So this simply says that the Rule will be activated for each Message object inserted into the working memory whose status is Message.HELLO. Besides that, two variable binds are created: "message" variable is bound to the message attribute and "m" variable is bound to the object matched pattern itself.

And the dialect "mvel" keyword ?

When writing Rules you have the option to use Java Language and MVEL sytnax to modify objects passed to the Working memory. MVEL's syntax allows you to apply a block of setters in one statement, with the engine being automatically notified of the changes at the end of the block.

modify ( m ) {

message = "Goodbye cruel world",
status = Message.GOODBYE

};

Ok, so we've our Rule. We will need to add the Message class which will be our "fact" transferred to the Drools Runtime:

package com.sample;

public class Message {

	public static final int HELLO = 0;
	public static final int GOODBYE = 1;

	private String message;
	private int status;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

}

In order to execute them we'll create a Java Class named App:

package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class App {
	public static void main( String[] args ) {
		System.out.println( "Bootstrapping the Rule Engine ..." );
 
		KieServices ks = KieServices.Factory.get();
		KieContainer kContainer = ks.getKieClasspathContainer();
		KieSession kSession =  kContainer.newKieSession("ksession-rules");

		Message message = new Message();   
		message.setMessage( "Hello World" );   
		message.setStatus( Message.HELLO );
		kSession.insert(message);
 
		int fired = kSession.fireAllRules();
		System.out.println( "Number of Rules executed = " + fired );
		System.out.println( "Message Status: " + message.getStatus());
	}
}

This class does the following actions:

  1. Bootstraps the Rule Engine session: The KieSession represents a running instance of the Rule Engine with a specific configuration and set of rules. It holds the evaluation algorithm used to match the rules against our domain objects.
  2. Lets the Rule Engine to know about our data: We are responsible for providing all the information to the engine so that it can operate on it. This is done through the insert() method on KieSession.
  3. Next, if the information that we provided matches with one or more available rules, we will get Matches. Calling the fireAllRules() method will execute these matches.

The last thing we need to do in order to complete our project, is a file in the src/main/resources/META-INF/ directory called kmodule.xml. This file is used to configure how to load the rules defined in the project in the rule engine. For now, the content of kmodule.xml will be quite simple as we will be using all the default configurations. Here is a sample content of it:

<?xml version="1.0" encoding="UTF-8"?>
<kmodule xmlns="http://jboss.org/kie/6.0.0/kmodule">
    <kbase name="rules" packages="rules">
        <ksession name="ksession-rules"/>
    </kbase>
    <kbase name="dtables" packages="dtables">
        <ksession name="ksession-dtables"/>
    </kbase>
    <kbase name="process" packages="process">
        <ksession name="ksession-process"/>
    </kbase>
</kmodule>

Here is how your project should look like:

drools project

You can run the App class from the IDE with "Run as Java Application". Otherwise, you can reach the root folder from the command line and build the project with:

$ mvn clean install

And you can run it with:

$ mvn exec:java -Dexec.mainClass="com.sample.App"

When executed the output will be:

Hello World
Goodbye cruel world
Number of Rules executed = 2
Message Status: 1

This is a very trivial example just to get accustomed with JBoss Drools environment: in the following articles we'll see how a rules engine can significantly reduce the complexity of components that implement the business-rules logic in your Java applications. By expressing your rules using JBoss Drools declarative approach your application has higher chance of being more maintainable and extensible than one that doesn't.

Continue Learning Drools

Continue Learning Drools through the following tutorials:

1) Creating a Drools project with Maven

If you are not using JBoss Developer Studio or Eclipse to develop your project, as simple environment Maven based will work.  The following tutorial shows how to create a minimal Drools project using Maven: Drools and Maven Hello World example

The project can be then imported into your development environment and managed from there.

2) Coding Rules in Decision Tables

In Drools, Decision Tables are a way to generate rules from the data entered into a spreadsheet. The spreadsheet can be a standard Excel (XLS) or a CSV File.

Drools decision tables example

If you want to learn how to code your Rules into an excel Spread Sheet, keep reading this tutorial: Getting started with Decision Tables in Drools

3) Getting started with the Kie Execution Server

The Kie Server is a Java web application that allow us to expose rules and business process to be executed remotely using REST and JMS interfaces. The following tutorial shows how to install it on the top of WildFly: Configure Kie Execution Server on WildFly

4) Deploy your assets on the Business Central

Once that you are familiar with the Kie Execution Server, you can learn how install also the Business Central where you can design, build and deploy your assets. Here is the tutorial for you: Getting started with Business Central Workbench

0
0
0
s2smodern