Sunday, February 17, 2013

Simple Drools Example

Implementing an expert system using Drools is quiet easy. First of all create ordinary java project in Eclipse. The following image shows the project structure in Eclipse:

There are two source folders, first one is src/main/java to save java classes and second one is src/main/rules to save Drools rule files. Don't forget to include all required libraries in Drools distribution archive to this project. Two important files that need attention are Main.java and validation.drl. Let's see each of them.


The Main.java contains one method main(). In the main method we load the validation.drl file, create a Customer object, and then fire the validation rule. We also add a Map object that is used to save error messages during validation process. Next we will see the validation.drl.

The .drl file has its own format structure. First we state package name, this is used for grouping only. No same Drools file name exists in the same package. Then we import all classes just like we do in java file. Next we create a series of rules.

In the validation.drl above we have two rules, addressMandatory to validate address, and emailMandatory to validate email. In the when clause we get objects that are inserted through session in KnowledgeBase before; the HashMap object which we put inside a variable named errors for later use and also Customer object that we put inside a variable named cust. While addressMandatory rule checks whether the customer's address is null or not, emailMandatory rule checks whether the customer's email is either null or empty.

If the address or email is null we put an error message to the errors variable so that we can write it to console in the main() method. We can safely write any Java code inside the then clause as we do in ordinary java file.

When we run the main() method, the following output is displayed on console:


1 comments:

Anonymous said...

Thanks, nice post

 

©2009 Stay the Same | by TNB