Skip to main content

World of Drool Engine

 

Rule Engine

Within mission-critical applications, the process of maintaining business logic within the source code can become too complicated. Business rules can be used to ease the development and maintenance by separating business logic from the source code.

In the Java world, most of the rules engines libraries implement

JSR94 standard known as Java Rule API Engine.

 

 


The following table highlights the top five major Rule Engine based technologies:

Popularity

Rule Engine

Summary

1

Drools

A Business Rules Management System (BRMS) solution which provides a core business rules engine (BRE), a web authoring and rules management application (Drools Workbench) and an Eclipse IDE plugin for core development

2

OpenRules

A general-purpose business rules and decision management system

3

EasyRules

EasyRules provides the Rule abstraction to create rules with conditions and actions, and the RulesEngine API that runs through a set of rules to evaluate conditions and execute actions.

4

JLisa

A Clips-like Rule engine accessible from Java with the full power of Common Lisp

5

Jess

A small, light and fast rule engine and scripting environment written entirely in Java; Gives access to all Java APIs

 

Rule Engines are meant to manage complex business rules in easier way.
If we have some business case for

Example: Bank Deposit and Withdrawal

The rules on the deposit could be -
1: Account number should be valid
2: Minimum deposit is $10 & Maximum is $1000
3: Number of desposits per day <=3
etc. Instead of writing if conditions in our code, we would externalize these Rules in an XML/JSON in a defined structure. On the run time one can take this file and read the rules and apply on the given inputs. The code is written once and used for many different rules.

There are two types of Rule Engines.
General Purpose Rule Engines
- These rule Engines can be used for less complex systems to very complex systems.
- We have to follow their vocabulary
- We have to use their API to make use of it
- Mostly XML based Rules (can be used by Non technical /Product Managers)
- Eg: Jboss Drools

Special purpose Rule Engines
- Targeted to do some complex conditions / algorithm
- Much technical but easy to maintain
- Rules might be in XML/JSON/JAVA/HTML
- Mostly written by us

 

 

Drools Rule Engine

Rules are stored in a forward-chaining rule engine, which implements an execution cycle that allows the action of one rule to satisfy the condition of other rules. In this way, a cascade of rules may become activated, and each rule action executed. Such forward-chaining rule engines are suitable for problems that require drawing higher-level conclusions from simple input facts.

When should Rule Engines be used:

·       The problem at hand is too complex to be solved through traditional solutions

·       We’re aiming to inculcate greater flexibility into our code while reducing complexity

·       We wish to separate business logic from application data and code

·       We wish to create a central knowledge repository and reuse as much code as possible

When shouldn’t Rule Engines be used:

·       The logic behind the rules is quite simple

·       If the problem at hand doesn’t change too often

·       If it’s possible to divide the problem into a smaller set of conditions

Drools - Business Rule Management System

A Business Rule Management System (BRMS) is software that creates, supports, and executes decision logic and business rules. ‘Drools’ is one of the most prominent BRMSs being used by thousands of organizations currently. The object-oriented system is an augmented implementation of Forgy’s Rete algorithm tailored for the Java language. It includes both forward as well as backward chaining interference-based rules engine and it provides a framework to allow business logic externalization in a common place.

Forward Chaining

·       Bottom-up reasoning

·       Fact driven

·       Finds interference from facts

·       Useful for planning and controlling

Backward Chaining

·       Top-down reasoning

·       Goal driven

·       Finds facts supporting hypothesis

·       Useful for diagnosis

 

 

Drools is split into two main parts:

Authoring

This involves the creation of DRL files which contain the rules to be fed into a parser. The Parser checks for correct syntax of the rules and produces an intermediate structure that describes the rules.

Runtime

This involves creation of working memory and handling the activation. This means figuring out how to load the rules to the engine and how to execute them.

To use Drools, we need an Integrated Development Environment (IDE) like JBoss Rules Workbench where we can write and test rules. We may use any other tool to create and run rules provided that the following Drools libraries are included:

·       drools-core.jar – contains the core engine, the runtime component that implements both RETE and LEAPS algorithms.

·       drools-compiler.jar – contains the compiler/builder components that take a rule source file and build executable rule bases.

  • drools-jsr94.jar – contains a JSR-94-compliant implementation.
  • drools-decisiontables.jar – contains the decision tables compiler component. It has a dependency on the drools-compiler component. This supports both Excel and CSV input formats.

Drools Service

Paragyte specializes in delivering state-of-the-art Drools services to its esteemed client base spanning across various geographies and industries. Some of our services include

Rules Engine Development

Use the best capabilities of Drools to develop custom rule engines for our business. Simplify and quicken application development by applying business rules implemented within the rules engine we build.

Rules Engine Integration

Bridge the gaps between our new rules engine implementation and existing business processes through efficient integrations put in place by Paragyte.

 

 

Rules Definition & Configuration

Drools specialists at Paragyte guide and help we to define and configure business rules so we can complete milestones and achieve our goals faster and better. The business rules we define can then be used for custom rule engine development for our business.

Administration & Support

Need a little hand with Drools BRMS queries? Hire Drools administrators from Paragyte who can provide on-premise and remote assistance for all our Rule Engine needs. We also offer training programs so we can get our staff accustomed to Drools.

Drools Use Case

The Drools Rules Engine helps businesses with in-depth decision making. Typical scenarios where it proves to be extremely useful are:


Timesheet Validation & Payroll Processing

·       Validates employee timesheets and processes payroll as per number of hours billed.

Claims Settlement

·       Evaluates the amount of claim to be paid to seeker at the time of settlement

Mortgage Processing

·       Verifies applicant information and accordingly approve or disapprove mortgage loans

Sales Pipeline Management

·       Manages all stage of business sales pipeline from first contact to sale closing

 

Key Advantage of Using Drools

Simplified Understanding

·       As compared to core code, rules are simpler to understand. Thus, they can help bridge the gap between developers and business analysts.

Improved Maintainability

·       Adding, modifying, or removing existing rules is much easier that changing a program. Their impact on other rules is also quite low as compared to imperative-style implementation.

Flexibility

·       Rewriting an application owing to requirement changes can be a nightmare. But with rules and the formalism they bring, incorporating changes becomes much easier.

Enhanced Performance

·       Drools works on the Rete algorithm which means in theory, the performance of the system doesn't depend on the number of rules. Thus, every new release adds various optimizations to the performance of Drools.

Reusability

·       All rules are kept at one place, so they can be reused as often as needed.

Speed & Scalability

·       The Rete algorithm, the powerhouse behind Drools, replaces unnecessary if – then statements with an optimized network.

Logic & Data Separation

·       The biggest advantage of Drools is that it decouples application code and business logic making code easier to maintain and adapt to changes.

Centralized Knowledge

·       Drools lets we create a repository of knowledge or a knowledgebase which can be considered as a single point of truth for all business policies.

Technical Advantage

·       Drools is open source.

·       It provides forward and backward chaining of rules execution

·       It provides template base rule definitions

·       It is implemented using JSR-94

·       It has decision table facility

·       Its rules are human readable

·       It is integrated with Spring

 

 

 

 

 

 

 

 

 

Practicals of Drools:

Consider a Jewellery shop which needs to maintain business logic of calculating discount based on the type of Jewellery. This can be done in our Java Code. But such rules may change daily and need to be updated regularly in our code which is not good. Also, we will always require a Developer for making such changes. So, its a good practice to define this logic as rules in a Business Rule Management System. If tomorrow the discount is to be changed this can be done even by a non-technical person.

Using drools, we must define the discounts offered on various jewellery products depending on the type.

 

For example, if the product is jewellery item offer a discount of 25% and so on.

 

We will create Eclipse Maven project as follows-

The POM defined is as follows- Only a single dependency of Drools-compiler is required.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.droolspoc</groupId>

<artifactId>drools-hello-world</artifactId>

<version>0.0.1-SNAPSHOT</version>

                  <dependencies>

                                     <dependency>

                                     <groupId>org.drools</groupId>

                                     <artifactId>drools-compiler</artifactId>

                                     <version>6.0.1.Final</version>

                                     </dependency>

                  </dependencies>

</project>

 

 

 

 

Next define the Model class Product which defines the type of jewellery item.

package com.droolspoc.model;

public class Product {

                  private String type;

                  private int discount;

                  public String getType() {

                                     return type;

                  }

                  public void setType(String type) {

                                     this.type = type;

                  }

                  public int getDiscount() {

                                     return discount;

                  }

                  public void setDiscount(int discount) {

                                     this.discount = discount;

                  }

 

}

Now define the rules in the drl file. We will use the type property of the Product class for defining the rules for defining what action needs to be taken if a particular condition is met. The .drl file should be place in resources/com.rule folder.

package com.rule

 

import com.droolspoc.model.Product

 

rule "Offer for Diamond"

                  when

                                     productObject: Product(type=="diamond")

                  then

                                     productObject.setDiscount(15);

                  end

rule "Offer for Gold"

                  when

                                     productObject: Product(type=="gold")

                  then

                                     productObject.setDiscount(25);

                  end

Drools employs a concept called Working Memory. Finally we define DroolsTest class to load the facts and the rules in the drools working memory and firing all the rules.

package com.droolspoc.main;

 

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.Reader;

 

import org.drools.compiler.compiler.DroolsParserException;

import org.drools.compiler.compiler.PackageBuilder;

import org.drools.core.RuleBase;

import org.drools.core.RuleBaseFactory;

import org.drools.core.WorkingMemory;

 

import com.droolspoc.model.Product;

 

public class DroolsTest {

 

                  public static void main(String[] args) throws DroolsParserException,

                                                       IOException {

                                     DroolsTest droolsTest = new DroolsTest();

                                     droolsTest.executeDrools();

                  }

 

                  public void executeDrools() throws DroolsParserException, IOException {

 

                                     PackageBuilder packageBuilder = new PackageBuilder();

 

                                     String ruleFile = "/com/rule/Rules.drl";

                                     InputStream resourceAsStream = getClass().getResourceAsStream(ruleFile);

 

                                     Reader reader = new InputStreamReader(resourceAsStream);

                                     packageBuilder.addPackageFromDrl(reader);

                                     org.drools.core.rule.Package rulesPackage = packageBuilder.getPackage();

                                     RuleBase ruleBase = RuleBaseFactory.newRuleBase();

                                     ruleBase.addPackage(rulesPackage);

 

                                     WorkingMemory workingMemory = ruleBase.newStatefulSession();

 

                                     Product product = new Product();

                                     product.setType("gold");

 

                                     workingMemory.insert(product);

                                     workingMemory.fireAllRules();

 

                                     System.out.println("The discount for the product " + product.getType()

                                                                         + " is " + product.getDiscount());

                  }

 

}

On running get the output as-

The discount of the jewellery product gold is 25

 

Drools allow users to define rules that specify what action needs to be done when a particular condition is met.

 

A Simple Rule is a combination of When and Then condition

rule "Customer is a NEW Customer With Birthday as Today"
    when
        newCustomer && customerBirthDayToday && totalSpending >= 100
    then
        discount = 20%;
     end

Drools Terminologies

·       Rule Base : It contains the information about the resources where rules are found

·       Facts: It is the Data that is input to the Rules.

·       Working Memory: Place where facts are stored. Facts can be inserted/updated/removed from working memory.

·       Inference Engine: It matches the Rules in Rule Base with the Facts in Working Memory . Drool uses Rete Algorithm to perform this matching.

·       Salience: Salience is used to define the priority of the rules in the order they are fired.

·       Stateful: In a StateFul Session, any change in the facts in working memory will trigger all the rules associated with that particular fact.

·       Stateless: In a Stateless Session, any change in the facts while executing rules is not made aware to the rule engine and will not trigger all rules by default.

·       Forward Chaining: Forward chaining is data-driven. Facts in working memory is applied to rules, which results in one or more rules being concurrently true and scheduled for execution by the Agenda.

·       Backward chaining: Backward Chaining is goal-driven. means we start with a result which the engine tries to satisfy. There can be more than 1 possible solution in case of backward chaining.


Drools in IntelliJ add JBoss Drool Support Plugin.

 

    

 

Create a simple maven project and add below dependency

 

<dependency>
    <groupId>org.drools</groupId>
    <artifactId>drools-compiler</artifactId>
    <version>6.0.1.Final</version>
</dependency>

 

 

 

In the src Folder create a Customer POJO with 4 below properties and getter/setters.

public boolean newCustomer;
public float totalSpending;
public boolean customerBirthDayToday;
public int discount;

in Resources Folder create a .DRL file with Sample Rule as

rule "Customer is a NEW Customer With Birthday as Today"
    when
        offerIs: Customer(newCustomer && customerBirthDayToday && totalSpending >= 100 )
    then
        offerIs.setDiscount(20);
        System.out.println("Rule1");
     end

THEN part of above rule can consist of JAVA language syntax

To test the above rule file create a Test file in src folder with below code

PackageBuilder builder = new PackageBuilder();
// Path to the Drool File
String ruleFile = "/discount.drl";
InputStream inputStream = getClass().getResourceAsStream(ruleFile);

Reader ruleReader = new InputStreamReader(inputStream);
builder.addPackageFromDrl(ruleReader);
org.drools.core.rule.Package rulePackage = builder.getPackage();
RuleBase ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(rulePackage);

WorkingMemory workingMemory = ruleBase.newStatefulSession();

Customer customer = new Customer();

customer.setCustomerBirthDayToday(true);
customer.setNewCustomer(true);
customer.setTotalSpending(200);
workingMemory.insert(customer);

workingMemory.fireAllRules();
System.out.println("Discount is " + customer.getDiscount());String ruleFile = "/discount.drl";
InputStream inputStream = getClass().getResourceAsStream(ruleFile);

Reader ruleReader = new InputStreamReader(inputStream);
builder.addPackageFromDrl(ruleReader);
org.drools.core.rule.Package rulePackage = builder.getPackage();
RuleBase ruleBase = RuleBaseFactory.newRuleBase();
ruleBase.addPackage(rulePackage);

WorkingMemory workingMemory = ruleBase.newStatefulSession();

Customer customer = new Customer();

customer.setCustomerBirthDayToday(true);
customer.setNewCustomer(true);
customer.setTotalSpending(200);
workingMemory.insert(customer);

workingMemory.fireAllRules();
System.out.println("Discount is " + customer.getDiscount());

 

 

 

 

 

 

 


 

Comments

Popular posts from this blog

SmartEdit & its Personalization in Hybris

SmartEdit introduced  in 6.0 Hybris version and  Personalization (based on SmartEdit)  enabled in 6.1 Hybris version Onwards . SAP Commerce SmartEdit allows content managers to easily create and manage their website content on-the-fly in different inflection points and make it available to their customers with the click of a button. Personalization (based on SmartEdit) provides an integrated, user-friendly way of building experiences that are relevant to your customers, which is key to driving engagement and conversion.  Personalization encompasses modules and extensions that facilitate using Personalization Mode in SmartEdit to create a fully customized user experience. Personalization capabilities work across both content and commerce in an integrated way, so that you can build customer experiences consistently across channels and functionality. Using SmartEdit for Customer Experience, you can see the end-customer experience as...

Performance Improvement in Hybris eCommerce

Below points will specially help   grocery   based projects where adding   50-60 products per cart   is a common trend and where   complex promotions   are used using   drools   engine. Add/Update to cart     à   In OOB Hybris whenever any new product is added to cart or quantity of existing product is updated in cart (from PLP, PDP, Search page etc) then calculateCart() method is called in order to calculate total price of the cart. This call can be prevented (to increase   performance ) in case the business requirement is to just show notification of add to cart without total price in minicart. View Cart   à   In case 50-60 products are added in cart and approx. 30% of the products have promotions applied then OOB Hybris view cart can take between 10-15 seconds to load (based on complexity of promotion). In order to avoid custom waiting 10-15 sec to see view cart this operation of can be split into below ...

Use of PartOf in Hybris

Definition PartOf modifier is used to define the aggregation relationship between Parent and Child objects. To explain it better I would say PartOf is used to defining cascade delete.  When we delete a Parent object then all its child objects(partOf) will be deleted automatically. Why or When to use PartOf? PartOf may make sense when the relationship involves "is part of" description. For example, an OrderEntry record(AbstractOrderEntry) is part of its parent Order(AbstractOrder), and older entries will never be shared between multiple orders. If the Order were to vanish, the OrderEntry should as well, and an order entry without an Order would be a problem. How to use PartOf? Looking into the following items.xml snippet we can able to understand the importance of PartOf This also can be defined at the attribute level. Like <itemtype code="User" extends="Principal" jaloclass="de.hybris.platform.jalo...