In previous post we implemented a drools project for a mobile shop to give discount according to the type of mobile model. The rules for this discount calculations we had written in a drl file. In this chapter we implement the same rules using the Drools Decision Table. Drools Decision Tables are excel based decision tables
1) Why use Drools Decision Table
We had stated in a previous chapter that the main advantage of Drools is that the logic can also be changed by a non technical person. But if we look at the .drl file, any modification will also require technical knowledge. As the .drl becomes more complicated the more difficult it will become for non technical persons like Business Analysts. Also frequent changes to the drools file is cumbersome.Hence this format, decision tables, is a very good option to use where something is going to be changed frequently by non-programmers.
2) Create Example
The only other change will be we will delete the rules.drl file and instead create a rules.xls in its place.
Download counts: 2641
- After downloading, unzip the project.
- Go to Eclipse IDE -> File -> Import -> Maven -> Existing Maven project -> Select the project.
In the pom.xml we will have to add these dependencies for drools decision table-
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-api</artifactId>
<version>7.73.0.Final</version>
</dependency>
<dependency>
<groupId>org.drools</groupId>
<artifactId>drools-decisiontables</artifactId>
<version>7.73.0.Final</version>
</dependency>
Our Rules.xls is as follows-
- RuleSet attribute- which says that this excel is a rule set. We have set this as rules.
- Import attribute-Imports all the Java classes to be used for rules. In our case the Product class.
- Notes-For giving the description of the drools decision table.
- RuleTable DiscountCalculation is name of RuleTable below
- Next row has CONDITION and ACTION columns, as the names indicate they are used for mentioning on which conditions what action is to be taken. Under condition column have specified the condition that depending on type of product set the discount which is specified under the actions column.
RunDrools.java
This is the only change required. Run the RunDrools.java class as before.
package com.hi.techpoints;
import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import com.hi.techpoints.model.Product;
public class RunDrools {
public static final void main(String[] args) {
try {
KieServices ks = KieServices.Factory.get();
KieContainer kContainer = ks.getKieClasspathContainer();
KieSession kSession = kContainer.newKieSession("ksession-rule");
Product product = new Product();
product.setModel("Pixel");
kSession.insert(product);
kSession.fireAllRules();
System.out.println("The discount for the mobile product " + product.getModel()
+ " is " + product.getDiscount());
} catch (Throwable t) {
t.printStackTrace();
}
}
}
Get the output as