01: Drools tutorial with Maven and Eclipse

Drools is an open source rules engine that allows you to externalize the business rules.

This tutorial assumes that you have gone through “Setting up Java, Maven, and Eclipse.” Once you have gone through the following steps, you should have a project structure as shown below.

drools-tut-1

Step 1: Create a new Maven project

Note: press “enter” through all prompts. The project will be created under C:\Temp\Java\projects\simpleDrools with a default pom.xml file.

Step 2: Import it into eclipse as a Maven project. File –> Import –> Existing Maven Projects, and select the folder where the pom.xml file is.

Step 3: Update the pom.xml file as shown below.

drools-tut-2

Step 4: The OrderItem domain object class with getter and setter methods.

Step 5: The RuleMap class, which is Map extension to store rules.

Step 6: The TemplateExpander utility class.

Step 7: The KnowledgeBaseBuilder that binds the classes defined above.

Step 8: The “product.drl” contains the rules to calculate the discounts and apply to each item. The extension “drl” stands for Drools Rule Language. For example, different products have different bulk discount in addition to the normal discount.

Read this along with Step: 9 which supplies the rule data “id, normalDiscountRate, productType, bulkDiscountQty, and bulkDiscountRate ” via the values created from the createDummyRuleMap() method. In commercial projects, these rule map or data is supplied via database tables or a excel spreadsheets. The business users maintain this rule data. They could modify the bulk discount quantity from time to time. The whole beauty of drools is that rules are maintained separately. These values are referred within the drl file with “@“. Each item from the “getOrderItems()” is validated against the rule map. The items are prefixed with “$

Step 9: Finally the “App” class with the main method to run. In commercial applications, the actual rules will be stored in a database server table or a an Excel spreadsheet. This allows the business to view and maintain the rules. If the rules change, the database table or spreadsheet can be modified. In this tutorial, for simplicity supplied as dummy rules via createDummyRuleMap() method.

When you run the above “App.java”

Output:


Java Interview FAQs

800+ Java Interview Q&As

Top