Rule Engine - Getting Started with Drools
- 6 minutes read - 1259 wordsThis article let you start with Rule Engine Drools, with step by step guide and series of examples. It starts with an overview and then covers in detail examples.
Rule Engine Overview
The underlying idea of a rule engine is to externalize the business or application logic. A rule engine can be viewed as a sophisticated interpreter of if-then statements. The if-then statements are the rules. A rule is composed of two parts, a condition and an action
: When the condition
is met, the action
is executed. The if portion contains conditions (such as amount >=$100), and the then portion contains actions (such as offer discount 5%). The inputs to a rule engine are a collection of rules called a rule execution set and data objects. The outputs are determined by the inputs and may include the original input data objects with modifications, new data objects, and possible side effects (such as sending email to the customer.
Rule engines should be used for applications with highly dynamic business logic and for applications that allow end users to author business rules. A rule engine is a great tool for efficient decision making because it can make decisions based on thousands of facts quickly, reliably, and repeatedly.
Rule engines are used in applications to replace and manage some of the business logic. They are best used in applications where the business logic is too dynamic to be managed at the source code level – that is, where a change in a business policy needs to be immediately reflected in the application Rules can fit into applications such as the following:
- At the application tier to manage dynamic business logic and the task flow
- At the presentation layer to customize the page flow and work flow, as well as to construct custom pages based on session state
Adopting a rule-based approach for your applications has the following advantages:
- Rules that represent policies are easily communicated and understood.
- Rules retain a higher level of independence than conventional programming languages.
- Rules separate knowledge from its implementation logic.
- Rules can be changed without changing source code; thus, there is no need to recompile the application’s code
A Standard API for Rule Engines in Java
In November, the Java Community approved the final draft of the Java Rule Engine API specification (JSR-94). This new API gives developers a standard way to access and execute rules at runtime. As implementations of this new spec ripen and are brought to the market, programming teams will be able to pull executive logic out of their applications.
A new generation of management tools will be needed to help executives define and refine the behaviour of their software systems. Instead of rushing changes in application behaviour through the development cycle and hoping it comes out correct on the other end, executives will be able to change the rules, run tests in the staging environment and roll out to production as often as becomes necessary.
Working with Drools Rule Engine
Drools is a business rule management system (BRMS) with a forward chaining inference based rules engine, using an enhanced implementation of the Rete algorithm.
Drools supports the JSR-94 standard for its business rule engine and enterprise framework for the construction, maintenance, and enforcement of business policies in an organization, application, or service.
A Simple Example
-
Create a simple Java Project.
-
Add a package
com.tk.drool
-
Create a class in this package and name it
RuleRunner.java
package com.tk.drool; import java.io.InputStreamReader; import org.drools.RuleBase; import org.drools.RuleBaseFactory; import org.drools.WorkingMemory; import org.drools.compiler.PackageBuilder; import org.drools.rule.Package; public class RuleRunner { public RuleRunner(){} public void runRules(String[] rules, Object... facts) throws Exception { RuleBase ruleBase = RuleBaseFactory.newRuleBase(); PackageBuilder builder = new PackageBuilder(); for(String ruleFile : rules) { System.out.println("Loading file: "+ruleFile); builder.addPackageFromDrl( new InputStreamReader( this.getClass().getResourceAsStream(ruleFile))); } Package pkg = builder.getPackage(); ruleBase.addPackage(pkg); WorkingMemory workingMemory = ruleBase.newStatefulSession(); for(Object fact : facts) { System.out.println("Inserting fact: "+fact); workingMemory.insert(fact); } workingMemory.fireAllRules(); } public static void simple1() throws Exception { new RuleRunner().runRules( new String[]{"/simple/rule01.drl"}); } public static void main(String[] args) throws Exception { simple1(); } }
-
Create a folder name “
simple
” and add a rule file containing rulespackage simple rule "Rule 01" when eval (1==1) then System.out.println("Rule 01 Works"); end
-
Create a folder lib and add the following jars downloaded using this link http://www.jboss.org/drools/downloads.html
- drools-api-5.0.1.jar
- drools-compiler-5.0.1.jar
- drools-core-5.0.1.jar
-
Download org.eclipse.jdt.core_3.4.4.v_894_R34x.jar from http://www.java2s.com/Code/Jar/o/Downloadorgeclipsejdtcore344v894R34xjar.htm
-
Download antlr-3.1.1-runtime.jar from http://www.java2s.com/Code/Jar/ABC/Downloadantlr311runtimejar.htm
-
Download mvel2-2.0.7.jar from http://mirrors.ibiblio.org/pub/mirrors/maven2/org/mvel/mvel2/2.0.7/mvel2-2.0.7.jar
-
Add all these jars to buildpath.
-
Run RuleRunner.java as a Java application and you will get the output as show below.
This is how you run the rule.
A More Complex Example
-
Create a simple Java Project.
-
Add a package
com.tk.drool
-
Create a class in this package and name it
RuleRunner.java
package com.tk.drool; public class RuleRunner { public RuleRunner(){} public void runRules(String[] rules, Object... facts) throws Exception { RuleBase ruleBase = RuleBaseFactory.newRuleBase(); PackageBuilder builder = new PackageBuilder(); for(String ruleFile : rules) { System.out.println("Loading file: "+ruleFile); builder.addPackageFromDrl( new InputStreamReader( this.getClass().getResourceAsStream(ruleFile))); } Package pkg = builder.getPackage(); ruleBase.addPackage(pkg); WorkingMemory workingMemory= ruleBase.newStatefulSession(); for(Object fact : facts) { System.out.println("Inserting fact: "+fact); workingMemory.insert(fact); } workingMemory.fireAllRules(); } public static void simple1() throws Exception { Object[] flows = { new Myflow(new SimpleDate("01/01/2012"), 300.00), new Myflow(new SimpleDate("05/01/2012"), 100.00), new Myflow(new SimpleDate("11/01/2012"), 500.00), new Myflow(new SimpleDate("07/01/2012"), 800.00), new Myflow(new SimpleDate("02/01/2012"), 400.00), }; new RuleRunner().runRules(new String[]{"/simple/rule01.drl"}, flows); } public static void main(String[] args) throws Exception { simple1(); } class SimpleDate extends Date { public SimpleDate(String datestr) throws Exception { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy"); this.setTime(format.parse(datestr).getTime()); } } }
-
Create a
Myflow
class in the same packagepackage com.tk.drool; import java.util.Date; public class Myflow { private Date date; private double amount; public Cashflow(){} public Cashflow(Date date, double amount) { this.date = date; this.amount = amount; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public String toString() { return "Cashflow[date="+date+",amount="+amount+"]"; } }
-
Create
rule01.drl
class containing rules in folder named “simple”.package simple import com.tk.drool.*; rule "Rule 01" when $cashflow : Myflow( $date : date, $amount : amount ) not Myflow( date < $date) then System.out.println("Cashflow: "+$date+" :: "+$amount); retract($cashflow); end
-
Run RuleRunner.java as Java application. It will print all the executed rules.
Rules UI Editor | Gunvor
Drools Guvnor is a centralized repository for Drools Knowledge Bases, with rich web based GUIs, editors, and tools to aid in the management of large numbers of rules. There is easy way to m create, manage and delete rules in Guvnor, also consuming these rules in the java client application and dynamically reading POJO models and firing rules over them is possible directly on the UI.
Eclipse also has a great UI plugin - drools eclipse GUI editor.
It is A business rules manager that allows people to manage rules in a multi user environment; it is a single point of truth for your business rules, allowing change in a controlled fashion, with user friendly interfaces.
Guvnor is the name of the web and network related components for managing rules with drools. This combined with the core drools engine and other tools form the business rules manager.
- Download Guvnor web application using the following link - http://download.jboss.org/drools/release/5.3.0.Final/drools-distribution-5.3.0.Final.zip
- Deploy the downloaded war file stored at the location
\guvnor-distribution-5.3.0.Final\binaries\guvnor-5.3.0.Final-tomcat-6.0.war in tomcat 6.0 - Run the application using following address - http://localhost:8080/guvnor-5.3.0.Final-tomcat-6.0/org.drools.guvnor.Guvnor/Guvnor.jsp
- You can now create directly UI, and can upload a jar file with fact models, that can be used to define rules.
Gunvor host the repository of rules, you can access the rule repository in Eclipse Gurvor Plugin or directly in the applications.
References
- http://www.theserverside.com/news/1365158/An-Introduction-to-the-Drools-Project
- http://www.ibm.com/developerworks/java/library/j-drools/#when
- http://java.sun.com/developer/technicalArticles/J2SE/JavaRule.html
- http://en.wikipedia.org/wiki/Drools
- http://www.packtpub.com/article/guided-rules-with-the-jboss-brms-guvnor
- http://docs.jboss.org/drools/release/5.3.0.CR1/drools-guvnor-docs/html/ch11.html#d0e3131
- http://docs.redhat.com/docs/en-US/JBoss_Enterprise_SOA_Platform/4.3/html/JBoss_Rules_Reference_Guide/chap-JBoss_Rules_Reference_Manual-The_Eclipse_based_Rule_IDE.html