Drools Sample Drools Program - Drools

How to create a Drools project?

This chapter explains about how to create a Drools project for the following problem statement:
Depending upon the city and the kind of product (Combination of City and Product), find out the local tax related to that city.
To create a drools project we will have two DRL files for our Drools project. The two DRL files will signify two cities in consideration (Pune and Nagpur) and four types of products (groceries, medicines, watches, and luxury goods).
  • The tax on medicines in both the cities is considered as zero.
  • For groceries, we have assumed a tax of Rs 2 in Pune and Rs 1 in Nagpur.
You can use the same selling price to demonstrate different outputs. Note that all the rules are getting fired in the application.
Here is the model to hold each itemType:

DRL Files

As discussed earlier, we have used two DRL files here: Pune.drl and Nagpur.drl.

Pune.drl

This is the DRL file that executes rules for Pune city.

Nagpur.drl

This is the DRL file that executes rules for Nagpur city.
Here we’ve written the DRL files based on city, as it gives us extensibility to add any number of rule files later if new cities are being added.
To explain this scenario that all the rules are getting triggered from our rule files. Here we have used two item types (medicines and groceries); and medicine is tax-free and groceries are taxed as per the city.
Our test class loads the rule files, inserts the facts into the session, and produces the output.

Droolstest.java

If you run this program, its output would be as follows:
For both Pune and Nagpur, when the item is a medicine, the local tax is zero; whereas when the item is a grocery product, the tax is as per the city. More rules can be added in the DRL files for other products. This is just a sample program.

Call an External Function form a DRL File

Let’s explain about how to call a static function from a Java file within your DRL file.
First of all, create a class HelloCity.java in the same package com.sample.
After that add the import statement in the DRL file to call the writeHello method from the DRL file. Following code explains about the changes in the DRL file Pune.drl are highlighted in yellow.
Run the program again and its output would be as follows:
Here the major difference is that the output is marked in yellow which shows the output of the static method in the Java class.
The main advantage is to call a Java method is that we can write any utility/helper function in Java and call the same from a DRL file.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Drools Topics