TechAlpine – The Technology world

How to use drools decision table in spreadsheet format to execute rules?

The following example code will describe the process of using decision table to execute rules.There are two ways

a) Use the spread sheet APIs directly to execute the rules.
b) Convert the excel spread sheet into a drl file and then execute the rules.

I will describe the second process (b).

** The main java class is ‘DroolExcelDemo.java’.First it will convert the excel sheet into a (.drl) file and then execute the rules.

package DROOLS;

import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.decisiontable.InputType;
import org.drools.decisiontable.SpreadsheetCompiler;
import org.drools.definition.KnowledgePackage;
import org.drools.event.rule.DebugAgendaEventListener;
import org.drools.event.rule.DebugWorkingMemoryEventListener;
import org.drools.io.ResourceFactory;
import org.drools.runtime.StatefulKnowledgeSession;

/**
* This class will create a drl file from excel sheet
* and then execute the rules.
*/
public class DroolExcelDemo {
public static final void main(final String[] args) {
// Create knowledge builder
final KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

// Create drl file from excel sheet
InputStream is =null;
try {
is= new FileInputStream(“D:/Workspace/DroolsDemo/src/DROOLS/DroolExcel.xls”);

} catch (FileNotFoundException e) {
e.printStackTrace();
}
// Create compiler class instance
SpreadsheetCompiler sc = new SpreadsheetCompiler();

// Compile the excel to generate the (.drl) file
StringBuffer drl=new StringBuffer(sc.compile(is, InputType.XLS));

// Insert dialect value into drl file
drl.insert(drl.indexOf(“DROOLS”)+40,”dialect \”mvel\””+”\n”);

// Check the generated drl file
System.out.println(“Generate DRL file is showing below–: “);
System.out.println(drl);

// writing string into a drl file
try {
BufferedWriter out = new BufferedWriter(new FileWriter(“D:/Workspace/DroolsDemo/src/DROOLS/RuleFile.drl”));
out.write(drl.toString());
out.close();
}
catch (IOException e){
System.out.println(“Exception “);
}
// Wait before using the drl file in the next section.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// End creation of drl file from excel sheet

// Using DRL file
kbuilder.add(ResourceFactory.newClassPathResource(“RuleFile.drl”, DroolMessage.class ), ResourceType.DRL );

// Check the builder for errors
if ( kbuilder.hasErrors() ) {
System.out.println(“kbuilder has errors”);
System.out.println( kbuilder.getErrors().toString());
}
// get the compiled packages (which are serializable)
final Collection pkgs = kbuilder.getKnowledgePackages();

// add the packages to a knowledgebase (deploy the knowledge packages).
final KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
kbase.addKnowledgePackages(pkgs);

// Create stateful session
final StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

// Set event listeners
ksession.addEventListener(new DebugAgendaEventListener());
ksession.addEventListener(new DebugWorkingMemoryEventListener());

// Create message text
DroolMessage messagetxt = new DroolMessage();
messagetxt.setMessage(“FlightNumber”);

DroolMessage messagetxt1 = new DroolMessage();
messagetxt1.setMessage(“FlightCode”);

// Insert into session and fire rules
System.out.println(“insert into session”);
ksession.insert(messagetxt);
ksession.insert(messagetxt1);
System.out.println(“before firing rules”);
ksession.fireAllRules();
System.out.println(“after firing rules”);
ksession.dispose();
System.out.println(“after dispose”);
}
}

* *The second file is a ‘DroolMessage.java’ pojo class. It holds the values set by the main java class described above.

package DROOLS;
/**
* This is a POJO for messages.It will be used by the drl file.
* The message values will be set from the DroolExcelDemo class
*/
public class DroolMessage {
// Create variable
private String message;

// Constructor
public DroolMessage() {
System.out.println(“initializing Message”);
}
// Setter and getter methods
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
// test method to test the rule execution
public void test(String test) {
System.out.println(“Parsing start and end position: “+test);
}
}

** Following is a rule file generated by the ‘DroolExcelDemo.java’ class.

package DROOLS;
//generated from Decision Table
dialect "mvel"
import DroolMessage;
// rule values at B12, header at B7
rule "DroolExcelRule_12"
when
msg:DroolMessage(message == "FlightNumber")
then
msg.test("1,6");
end

// rule values at B13, header at B7
rule “DroolExcelRule_13”
when
msg:DroolMessage(message == “FlightCode”)
then
msg.test(“7,8”);
end

** Following is the input excel based rule file to the ‘DroolExcelDemo.java’ class above.

15 thoughts on “How to use drools decision table in spreadsheet format to execute rules?

    1. kaushik Post author

      Hi Daniel,

      Thanks for your interest. Please let me know your exact requirement. I will send you the excel sheet.

      Cheers
      /KP

    1. kaushik Post author

      Hi Aakash,

      Please send me your exact requirement. I will try my best to help you out.

      Thanks,
      Techalpine

  1. kaushik Post author

    Hi Manideepa,

    The excel sample is already shown in the post. You can use it as it is. If you have some other requirement, do let me know. I would love to help you sort the issues.

    Thanks
    /KP

  2. Shekhar Shaw

    Hello,
    While I am trying to execute, it is raising a file not found error while processing below line.

    // Using DRL file
    kbuilder.add(ResourceFactory.newClassPathResource(“RuleFile.drl”, DroolMessage.class ), ResourceType.DRL );

    Could you please suggest what else I need to do.

    Regards,
    Shekhar Shaw

Leave a Reply

Your email address will not be published. Required fields are marked *


1 + = 6

TechAlpine Books
-----------------------------------------------------------