Mindmajix

Drools Interview Questions

Drools Interview Questions

Q. What is Drool?

Drool is one of the business rule management systems or BRMS that has forward and backward chaining inference based rule engine.


Q. What is other nomenclature for Drool?

Drool is also known as production rule system that uses enhanced implementation of Rete algorithm.


Q. What is meant by Knowledge is Everything or KIE?

KIE is the new umbrella name to the systems set like drools, jBPM, optaPlanner, Guvnor, and uberFire and such other technologies.


Q. What is the standard supported by Drool?

Drool supports JSR-94 standards for the business rule engine. It also supports enterprise framework for construction, enforcement, as well as maintenance of business policies.


Q. What is JBoss Enterprise BRMS?

JBoss Enterprise BRMS is the reasoning engine for policy and rule developments for business. It also manages access and changes.


Q. What is the prodcuctized version of Drools?

JBoss Enterprise BRMS is the productized version of Drools and it has enterprise level support.


Q. What are the components of JBoss Enterprise Version?

The components of JBoss Enterprise Version are JBoss Enterprise web platform, JBoss Enterprise application of SOA platform, Business Rules Engine, and Business Rules Manager.


Q. What are the features of JBoss Enterprise Web Platform?

The JBoss Enterprise Web Platform is the software infrastructure that supports the running of BRMS components.


Q. What are the features of JBoss Enterprise Application or SOA Platform?

It is the application software structure in the system that supports running of BRMS components.


Q. Who use the Business Rules Engine?

Drools experts use the Business Rules Engine through Rete algorithm and Drools Rule Language (DLR).


Q. What is Business Rules Manager?

Business Rules Manager is a centralized repository for the Drools knowledge bases and has rich web based Graphical User Interface as well as tools and editors to manage large numbers of rules.


Q. What is meant by Drools Guvnor and Drools Expert?

Drools Guvnor is the Business Rules Manager and Drools Expert is the Business Rules Engine.


Q. What is Drools Flow?

Drools Flow or process or workflow as it is variedly called, provides the workflow as well as business processes.


Q. What is the tool for managing complex event processing in Drools?

It is the Drools Fusion that is used for event processing as well as temporal reasoning.


Q. What is meant by Drools Planner?

Drools Planner or automated planning optimizes the process including the NP-hard planning problems.


Q. What is the purpose of dialect in Drools?

Dialect or mve1 points to the Getter and Setters of the variables of plain old Java objects (POJO). Dialect “java” is used for writing Java code in the rules.


Q. What is the restriction in using Java code?

User cannot use Java code inside “when” part of the rules. However, it can be use in the “then” part.


Q. What is the reason for putting $ symbol before the variables?

The objective of putting $ symbol before the variables is to ensure the difference between variables of POJO classes and Rules.


Q. What is provided by Drools?

Drools provides core Business Rules Engine (BRE) and Web Authoring and Rules Management Application (Drools Workbench) as well as the Eclipse IDE plugin for core developments.


Q. What are Drool Workbench, Expert, and Fusion?

Drools Workbench is the web user interface for authoring and management. Drools Expert is the business rule engine and Drools Fusion is the complex event processing feature.


Q. How to halt process in DRL file?

User has to resort to drools.halt() in the consequence (then) part of the application.


Q. How to remove object from knowledge session?

Use retract method to remove the fact from the KnowledgeSession

Assume ksession is the StatefulKnowledgeSession object

List list = new ArrayList();
list.add(“One”);
list.add(“Two”);
list.add(“Three”);
ksession.insert(list);

ksession.fireAllRules();

ksession.retract(ksession.getFactHandle(list));


Q. How to fetch and play around with the rules in java code?

Rules does not exist as the Java codes. However it is possible using Guvnor REST API for downloading the DRL source code for the rules and thereafter uploads them all over again.


Q. Is it possible using round trips between rules modified in Guvnor, loade in the UI, modified and uploaded to Guvnor?

There is no such way of ensuring this. Especially newcomers should not try this to avoid complications.


Q. Is it possible working with completely custom UI instead of using Guvnor Rule?

Rules can be stored in the custom domain model in a database generating the DRL from that model. This can render Guvnor redundant in the custom environment.


Q. If there are still rules that need to be managed in Guvnor what steps user should take?

If the user still has rules that are required to manage in Guvnor then he or she should generate the DRL and upload it into Guvnor using REST API.


Q. What is the global variable in Drools?

The global variable in Drools is the keyword. Global is the variable used in Drool and is visible in all rules inside the DRL file.


Q. How should the global variable be used in DRL file?

Global variables can be used extremely carefully in DRL file. Changes in global variable are not modified in working memory and hence care in handling them is required.


Q. What is the use of global variable?

Global variable can be used for any type of object and there won’t be any mismatch.


Q. Where global variable should be used?

Where in the rules requirements for database connection object is necessary, global variable should be used. For instance; The DB connection object could be global variable.

Consider a scenario, where in the rules there is a requirement for database connection object. In this case, the DB Connection object can be inserted as a global variable in the working memory and the connection object will be visible to all the rules in that DRL file.

GlobalDrl.drl

global java.util.List globalList;

rule “Global implementation”

when

eval( true )

then

globalList.add( “Hello World” );

end

Java client file

List list = new ArrayList();

KnowledgeSession knowledgeSession = knowledgeBase.newStatefulSession();

knowledgeSession.setGlobal( “globalList”, list );


Q. What is not advisable in use of global variables?

Changing global value inside the rule is not advisable. Instead the value should be set from the application using the working memory interface.


Q. What is meant by accumulate in DRL Drools?

Accumulate is conditional element that was introduced in Drools version 4.0. It is used to iterate over the list of objects and help validation of data in Java operation.


Q. What is meant by Drools Recursive Rules?

A Fibonacci series is the most common example of recursion in Drools. In the Drools the implementation is carried out using the insert and modifies keywords.

The most common example of recursion is a Fibonacci series. In drools, the implementation is done using the insert and modify keywords.
There are three most important parts in this implementation, one is insert keyword that is used in then part and other is not keyword that gets used in when part to satisify the breaking condition. As in Fibnocci series example, the breaking condition would be {sequence == 1} Consider below class and DRL file :

Fibonacci.java
package com.recursion;

public class Fibonacci {

private int sequence;

private long value;

public Fibonacci(final int sequence) {

this.sequence = sequence;

this.value = -1;

}

public int getSequence() {

return sequence;

}

public void setSequence(int sequence) {

this.sequence = sequence;

}

public long getValue() {

return value;

}

public void setValue(long value) {

this.value = value;

}

}

TestRecursion.java

public class TestRecursion {

public static final void main(String[] args) {

try {

// load up the knowledge base

KnowledgeBase kbase = readKnowledgeBase();

StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, “test”);

ksession.insert(new Fibonacci(10));

ksession.fireAllRules();

ksession.dispose();

logger.close();

} catch (Throwable t) {

t.printStackTrace();

}

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“Fibonacci.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error : errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

The implementation in terms of rules in drl file has three rules as shown below:
Recurse rule: This rule checks if the sequence is not reached to 1 and value is -1 then insert new Fibonacci class object with sequence value one less than previous object. The salience of this rule is highest, because all Fibnocci class object need to be inserted into working memory before calculation the value field of the class. The not conditional element is used to stop the rule’s matching once we have all 50 Fibonacci objects in memory.
rule “Recurse”

salience 10

when

f : Fibonacci ( value == -1 )

not ( Fibonacci ( sequence == 1 ) )

then

insert( new Fibonacci( f.getSequence() – 1 ) );

System.out.println( “recurse for ” + f.getSequence() + “–” + f.getValue());

end

Bootstrap rule: Fibonacci series for 1 is 1 and for 2 is 1, 1. This rule gets activated for 2 Fibonacci class object that were inserted in the working memory in the earlier rule.
For Fibonacci object, sequence == 1 &
For Fibonacci object, sequence == 2
So when the sequence == 1 or sequence == 2, we need to update the value field in Fibonacci series to 1 as done below.
rule “Bootstrap”

dialect “mvel”

when

f : Fibonacci( sequence == 1 || == 2, value == -1 ) // multi-restriction

then

modify ( f ){ value = 1 };

System.out.println( f.getSequence()  + ” == ” + f.getValue()  );

end

Calculate rule: For the remaining 48 objects in the working memory where sequence > 2, below rule gets activated.
The “Calculate” rule uses field constraints to correctly constraint the thee Fibonacci patterns in the correct order; this technique is called cross product matching. The first pattern finds any Fibonacci with a value != -1 and binds both the pattern and the field. The second Fibonacci does this, too, but it adds an additional field constraint to ensure that its sequence is greater by one than the Fibonacci bound to f1. When this rule fires for the first time, we know that only sequences 1 and 2 have values of 1, and the two constraints ensure that f1 references sequence 1 and f2 references sequence 2. The final pattern finds the Fibonacci with a value equal to -1 and with a sequence one greater than f2. At this point, we have three Fibonacci objects correctly selected from the available cross products, and we can calculate the value for the third Fibonacci object that’s bound to f3.
rule “Calculate”

dialect “mvel”

when

// Bind f1 and s1

f1 : Fibonacci( s1 : sequence, v1 : value != -1 )

// Bind f2 and v2; refer to bound variable s1

f2 : Fibonacci( sequence == (s1 + 1), v2 : value != -1 )

// Bind f3 and s3; alternative reference of f2.sequence

f3 : Fibonacci( s3 : sequence == (f2.sequence + 1 ), value == -1 )

then

// Note the various referencing rechniques.

modify ( f3 ) { value = v1 + v2 };

System.out.println( s3 + ” == ” + f3.value );

end

The modify statement updated the value of the Fibonacci object bound to f3. This means we now have another new Fibonacci object with a value not equal to -1, which allows the “Calculate” rule to rematch and calculate the next Fibonacci number.


Q. What are the most important parts of Recursion in Drools?

The three most important parts of in the process of implementation of recursive rules in Drools are inserting keywords in ‘then’ part, not keyword used in ‘when’ part, and ‘breaking condition’.


Q. What would be the breaking condition in Fibonacci series?

The breaking condition in Fibonacci series would be (sequence==1).


Q. What is global in DRL file?

global is the keyword used in drools to define a global variable. Global variable is the one which will be visible to all the rules inside a DRL file.
Globals must be used very carefully in a DRL file, since the changes in a global variable are not notified to the working memory. For example, you are using a list variable as a global and in any rule you are adding a value in a list and in one particular rule, you are checking if list size() > 0, then in this case rule may not fire. Global variable can be used for any type of object.


Q. Accumulate in DRL drools?

Accumulate is a conditional element introduced in Drools version 4.0
Accumulate is used to iterate over the list of objects and allows to perform java operations to validate the data.

Consider an example,
HashMap object -> Employee
Key -> Employee Id
Value -> List that represents the number of leaves taken by that employee in an year

And the check need to be applied, if the leaves goes beyond 20 then deduct 2 days salary.

Structure:
ResultPattern( fieldconstraint* )

from accumulate ( SourcePattern( fieldconstraint* )

init( code )

action( code )

reverse( code )

result( code ) )

ResultPattern -> Expected result java class out of result block. For e.g. Integer() class in this case

SourcePattern -> List that needs to be iterated. For e.g. List in this example

init -> init block gets executed first. You can initialize any variable here. For e.g. Initailize variable int totalNoOfLeaves = 0;

action -> Perform java operations in this block. For e.g. Perform addition of leaves here

result -> Return the result required. For e.g. Return totalNoOfLeaves variable here

Employee.java

package com.pojo;

import java.util.List;

import java.util.Map;

public class Employee {

private Map<String, List<Integer>> employeeLeavesMap;

private boolean deductSalary;

public boolean isDeductSalary() {

return deductSalary;

}

public void setDeductSalary(boolean deductSalary) {

this.deductSalary = deductSalary;

}

public Map<String, List<Integer>> getEmployeeLeavesMap() {

return employeeLeavesMap;

}

public void setEmployeeLeavesMap(Map<String, List<Integer>> employeeLeavesMap) {

this.employeeLeavesMap = employeeLeavesMap;

}

}

EmployeeClient.java

package com.client;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.Iterator;

import java.util.List;

import java.util.Map;

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderConfiguration;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.builder.conf.PropertySpecificOption;

import org.drools.io.ResourceFactory;

import org.drools.runtime.StatefulKnowledgeSession;

import com.pojo.Customer;

import com.pojo.Employee;

import com.pojo.GroupMap;

import com.pojo.Person;

public class EmployeeClient {

public static void main(String args[]) throws Exception {

KnowledgeBase kbase = readKnowledgeBase();

Map<Integer, List<Person>> map = new HashMap<Integer, List<Person>>();

StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

Employee employee = new Employee();

Map<String, List<Integer>> employeeLeavesMap = new HashMap<String, List<Integer>>();

List<Integer> integers = new ArrayList<Integer>();

integers.add(2);

integers.add(3);

integers.add(1);

integers.add(5);

integers.add(3);

integers.add(8);

integers.add(1);

integers.add(0);

integers.add(0);

integers.add(0);

integers.add(1);

integers.add(3);

employeeLeavesMap.put(“Kumar”, integers);

employee.setEmployeeLeavesMap(employeeLeavesMap);

ksession.insert(employee);

ksession.fireAllRules();

ksession.dispose();

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“Employee.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error : errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

Employee.drl

import com.pojo.*;

import java.util.*;

rule “Rule Name”

when

employee : Employee()

employeeLeavesMap : Map() from employee.employeeLeavesMap

$deductSalary : Number(intValue > 20) from accumulate

($t:List() from employeeLeavesMap.values  , init(Integer totalNoOfLeaves = 0;),

action(

for(int i = 0 ; i < $t.size() ; i++) {

totalNoOfLeaves = totalNoOfLeaves + (Integer) $t.get(i);

}

System.out.println(“Total No Of Leaves taken : “+totalNoOfLeaves);

),

result( new Integer(totalNoOfLeaves) ) )

then

employee.setDeductSalary(true);

System.out.println(“Salary deducted for two days”);

end


Q. DRL Drools get rule name salience agenda-group in DRL file?

This answer will implement the rule in a DRL file to display the rules attributes in the when part. We may require to print the rule name if the rule gets executed successfully i.e. rule enters in then part

Rule attributes can be fetched as shown below:

1) Rule Name – drools.getRule().getName()
2) Rule Salience – drools.getRule().getSalience()
3) Rule Agenda group – drools.getRule().getAgendaGroup()

Sample implementation as shown below:

package com.sample;

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;

import org.drools.logger.KnowledgeRuntimeLogger;

import org.drools.logger.KnowledgeRuntimeLoggerFactory;

import org.drools.runtime.StatefulKnowledgeSession;

public class GetRuleNameDRL {

public static final void main(String[] args) {

try {

// load up the knowledge base

KnowledgeBase kbase = readKnowledgeBase();

StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, “test”);

ksession.fireAllRules();

logger.close();

} catch (Throwable t) {

t.printStackTrace();

}

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“GetRuleName.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error: errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

DRL file:

package com.sample

rule “This rule will display name of the rule”

salience 100

when

eval(true)

then

System.out.println(“Rule Name is – ” + drools.getRule().getName());

System.out.println(“Rule Salience is – ” + drools.getRule().getSalience());

System.out.println(“Rule Agenda group is – ” + drools.getRule().getAgendaGroup());

end

Output:

Rule Name is – This rule will display name of the rule

Rule Salience is – 100

Rule Salience is – MAIN


Q. Drools clear agenda group?

When a focus is set to any agenda group all the rules of that rule enters into activation state and knowledge session will fire all the rules of that agenda group. What if we may require, if any one rule of an agenda group gets fired no other rule of that agenda group should get fired.

In order to achieve this, we need to clear that agenda group. This can be done in a DRL file as shown below.

Insert Agenda Group in following order :

knowledgeSession.getAgenda().getAgendaGroup(“Insufficient Balance”).setFocus();
knowledgeSession.getAgenda().getAgendaGroup(“Check Balance”).setFocus();

So there will be two agenda groups in the stack in the following posistion :
Insufficient Balance at position 0
Check Balance at position 1

rule “Check Bank Balance”

agenda-group “Check Balance”

salience 100

when

$loanAmount : LoanAmount(monthlyInstallment > bankBalance)

then

kcontext.getKnowledgeRuntime().getAgenda().getAgendaGroup(“Insufficient Balance”).clear();

System.out.println(“Agenda Group Cleared”);

end

rule “Rule Insufficient Balance”

agenda-group “Insufficient Balance”

when

$loanAmount : LoanAmount();

then

$loanAmount.setInsufficientBalance(true);

System.out.println(“Insufficient Funds to perform operation. Send Reminder Email”);

end

So when rule 1 fires successfully, it will clear the Insufficient Balance agenda group and rule two will not be fired since agenda is cleared, else Insufficient Balance agenda group will be taken out of stack and second rule will be activated.


Q. Drools Agenda Group setFocus?

Agenda Group in Drools is special feature in Drools which contains a set of rules or a single rule within a group and it makes the knowledge session understand the activation of rules.

At a single moment of time, only one agenda group has focus that means only the rules in that group will be activated and fired.

By default every rule is associated with the MAINagenda group.

Agenda group are useful to differentiate the set of rules from the rest of the rules in a knowledge session that apply to particular sub-process within a large process.

Agenda group can be changes using the focus either from java code or from rule API. Each time a focus is called it push that Agenda Group on top of a stack and execution starts. When the stack becomes empty, the agenda group focus shifts to MAIN. A Single agenda group can be focussed multiple times. The default Agenda Group is MAIN, all rules which do not specify an Agenda Group are placed there, it is also always the first group on the stack and given focus as default.

When the focus is set to some agenda group that is not available in the knowledge session it does not complaint anything it finishes the execution in a normally.

When the focus is set to some particular agenda group and if there exists a rule in the MAIN stack with higher salience, the activation will give preference to the agenda group’s rule only and once agenda group finishes execution and if no more agenda’s are available in the stack then the agenda MAIN will be preferred as shown below:
rule “Group One Agenda Group”
agenda-group “Group One”
salience 100

rule “Group Without Agenda Group”
salience 200
when

In this case if the agenda is set to “Group One” then this “Group One Agenda Group” will be fired first and then the agenda will shift to MAIN and “Group Without Agenda Group” will be fired.


Q. How to set focus to agenda group from Java file

knowledgeSession.getAgenda().getAgendaGroup(“Group One”).setFocus();

Q. How to set focus to agenda group from DRL file

kcontext.getKnowledgeRuntime().getAgenda().getAgendaGroup(“Insufficient Balance”).setFocus();

Sample Implementation : This implementation is to check if the account holder has already done the EMI payment for the loan amount for the month. For this the processing involves :
1) Check if bank balance is less than monthly installment. For this, the agenda group will be focussed to the rule to check this condition
2) If above rule fires successfully, set the agenda group to the rule which needs to send reminder email and halth the processing
3) If above rule fires fails, go the the rule with MAIN agenda group and fire that rule

AgendaGroupClient.java
package com.client;

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;

import org.drools.runtime.StatefulKnowledgeSession;

import com.pojo.LoanAmount;

public class AgendaGroupClient {

public static void main(String args[]) throws Exception {

KnowledgeBase kbase = readKnowledgeBase();

StatefulKnowledgeSession knowledgeSession = kbase.newStatefulKnowledgeSession();

try {

LoanAmount loanAmount = new LoanAmount();

loanAmount.setBankBalance(10000);

loanAmount.setMonthlyInstallment(8000);

loanAmount.setAccountId(“ACC013867”);

knowledgeSession.insert(loanAmount);

knowledgeSession.getAgenda().getAgendaGroup(“Check Balance”).setFocus();

knowledgeSession.fireAllRules();

} finally {

knowledgeSession.dispose();

}

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“AgendaGroup.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error : errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

LoanAmount.java – Pojo File

package com.pojo;

public class LoanAmount {

private String accountId;

private Integer bankBalance;

private Integer monthlyInstallment;

private boolean insufficientBalance;

public String getAccountId() {

return accountId;

}

public void setAccountId(String accountId) {

this.accountId = accountId;

}

public Integer getBankBalance() {

return bankBalance;

}

public void setBankBalance(Integer bankBalance) {

this.bankBalance = bankBalance;

}

public Integer getMonthlyInstallment() {

return monthlyInstallment;

}

public void setMonthlyInstallment(Integer monthlyInstallment) {

this.monthlyInstallment = monthlyInstallment;

}

public boolean isInsufficientBalance() {

return insufficientBalance;

}

public void setInsufficientBalance(boolean insufficientBalance) {

this.insufficientBalance = insufficientBalance;

}

}

AgendaGroup.drl

import com.pojo.*;

rule “Check Bank Balance”

agenda-group “Check Balance”

salience 100

when

$loanAmount : LoanAmount(monthlyInstallment > bankBalance)

then

System.out.println(drools.getRule().getName());

kcontext.getKnowledgeRuntime().getAgenda().getAgendaGroup(“Insufficient Balance”).setFocus();

end

rule “Rule Insufficient Balance”

agenda-group “Insufficient Balance”

when

$loanAmount : LoanAmount();

then

$loanAmount.setInsufficientBalance(true);

System.out.println(“Insufficient Funds to perform operation. Send Reminder Email”);

drools.halt();

end

rule “Send Thanks Email”

salience 200

when

$loanAmount : LoanAmount()

then

System.out.println(“EMI payment already done for account – ” +$loanAmount.getAccountId());

end


Q. Check if Object does not exists in Working Memory in DRL Drools?

In a Drools rule language, an object when inserted into the working memory, is checked in a DRL file as shown below

When

$object : Object_Name()

Then

System.out.println(“Object Exists”);

What if there arise a case, where it is required to check if the object does not exists in the working memory. If so, insert a new object of that type and then proceed further.

This check can be performed using the not operator in drools in a DRL file.

Refer a below example
DRLNoObject.java – Client File

package com.sample;

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;

import org.drools.logger.KnowledgeRuntimeLogger;

import org.drools.logger.KnowledgeRuntimeLoggerFactory;

import org.drools.runtime.StatefulKnowledgeSession;

public class DRLNoObject {

public static final void main(String[] args) {

try {

// load up the knowledge base

KnowledgeBase kbase = readKnowledgeBase();

StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newFileLogger(ksession, “test”);

ksession.fireAllRules();

logger.close();

} catch (Throwable t) {

t.printStackTrace();

}

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“DRLNoObject.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error: errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

DRLNoObject.drl – DRL File 

package com.sample

rule “Rule To Check If Object Does Not Exists”

lock-on-active

salience 90

when

not Pojo()

then

System.out.println(drools.getRule().getName());

end


Q. Drools DRL Create Knowledge Session and Knowledge Base?

To fire a rules in a DRL, we need to create the knowledge base and knowledge session. The facts are inserted in a session and rules are fired on them. Before moving to how to create knowledge base and session let us first understand the basic terms

1) KnowledgeBuilder – This class belongs to org.drools.builder.KnowledgeBuilder package. KnowledgeBuilder class is responsible for compilation of the rules. The rules can be loaded into Knowledge Builder in the following formats :

a) DRL
b) BRL
c) DSL
d) PKG

KnowledgeBuilder takes the input rules and perform compilation. In case errors are found, getErrors() method of this class returns the list of org.drools.builder.KnowledgeBuilderError class. If no errors are found, the size of the list is 0.

2) KnowledgeBase – This class belongs to org.drools.KnowledgeBase package. Once the KnowledgeBuilder perform its task and if no errors are found, we load the Knowledge Packages from the builder and add them to KnowledgeBase. KnowledgeBase consists of all the rules, functions and other components of a rules file. KnowledgeBase allows the creation of KnowledgeSession either StatefulKnowledgeSession or StatelessKnowledgeSession.

Once the Knowledge Session gets created, the facts or java objects are inserted into the session and rules are fired on them. In case of StatefulKnowledgeSession, dispose() method needs to be called in order to flush and release the session object.

Below implementation shows what all components are there to run a rules.

1) DRL File – This file holds the rules
2) Fact – Java POJO to hold the bean properties
2) DroolsStatefulSession.java – Client File to load the Drl file, create knowledge base, load the session and fire rules on them.

DroolsStatefulSession.java

package com.client;

import org.drools.KnowledgeBase;

import org.drools.KnowledgeBaseFactory;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

import org.drools.builder.ResourceType;

import org.drools.io.ResourceFactory;

import org.drools.runtime.StatefulKnowledgeSession;

import com.pojo.Fact;

public class DroolsStatefulSession {

public static void main(String args[]) throws Exception {

StatefulKnowledgeSession knowledgeSession = readKnowledgeBase().newStatefulKnowledgeSession();

try {

Fact fact = new Fact();

fact.setName(“First Name”);

// Insert a fact in the session

knowledgeSession.insert(fact);

System.out.println(“Fact Inserted into Knowledge Session”);

knowledgeSession.fireAllRules();

System.out.println(“Rules Fired”);

} finally {

knowledgeSession.dispose();

System.out.println(“Knowledge Session Disposed”);

}

}

private static KnowledgeBase readKnowledgeBase() throws Exception {

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

kbuilder.add(ResourceFactory.newClassPathResource(“DroolsStatefulSession.drl”), ResourceType.DRL);

KnowledgeBuilderErrors errors = kbuilder.getErrors();

if (errors.size() > 0) {

for (KnowledgeBuilderError error : errors) {

System.err.println(error);

}

throw new IllegalArgumentException(“Could not parse knowledge.”);

}

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();

kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());

return kbase;

}

}

Fact.java

package com.pojo;

public class Fact {

private String name;

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

}

DroolsStatefulSession.drl

import com.pojo.Fact;

rule “This is a rule”

when

fact : Fact()

then

System.out.println(“In DRL Rule Name – ” + drools.getRule().getName());

end

Output:

Fact Inserted into Knowledge Session
In DRL Rule Name – This is a rule
Rules Fired
Knowledge Session Disposed


Q. Drools Stateful vs Stateless Knowledge Session?

Knowledge Session in Drools is the core component to fire the rules. Its the knowledge session that holds all the rules and other recources.

Knowledge Session is created from the KnowledgeBase which includes all the rules.

Knowledge Session in Drools is of 2 types :
1) Stateful Knowledge Session
2) Stateless Knowledge Session

Difference between the 2 :

1) In case of Stateless Knowledge Session, while rules execution i.e. once fireRules method is called, and modification in the inserted facts (in the then part) is not available to the rules engine. In case of Stateful Knowledge Session, any changes in the facts is available to the rule engine.

2) Once rules are fired, Stateful Knowledge Session object must call the method dispose() to release the session and avoid memory leaks.

3) In case of Stateful Knowledge Session, any changes to facts is available to the rule engine. So the rules are called iteratively. If Fact A is modified in last rule of DRL, then this change will re-activate all the rules and fire the rules that are build on Fact A. This is not the case with Stateless Knowledge Session.

The hidden fact is Stateless session uses a Stateful session behind it


Q. How to create a Drools Knowledge Base as Singleton?

Running a drools application in a web application would be similar to the one while running in a standalone java application.

It is advisable to create a Knowledge Base within an application as a Singleton class. For each client request, a new StatefulKnowledgeSession or StatelessKnowledgeSession is created based on the requirement.

Advantages of creating a KnowledgeBase as Singleton class :

1) There will be only 1 instance of KnowledgeBase across the whole application
2) Different requests will use the same instance to create knowledge session
3) Loading of all the DRL files happens at once saving a lot of time
4) KnowledgeBase initialization can be eagerly loaded. Thus as soon as the application starts in the server, KnowledgeBase is created. So on first client request for rule firing, processing time will be saved as the KnowledgeBase is already in place, just to create a Session out of it.

Sample singleton class for KnowledgeBase

Spring Bean Entry configuration : In a spring configuration XML, following entry helps in eager initialization of the KnowledgeBase.

<bean id=”knowledgeBase” class=”com.sample.DroolsSingletonKnowledgeBase” init-method=”getKnowledgeBase()”>

package com.sample;

import org.drools.KnowledgeBase;

import org.drools.builder.KnowledgeBuilder;

import org.drools.builder.KnowledgeBuilderError;

import org.drools.builder.KnowledgeBuilderErrors;

import org.drools.builder.KnowledgeBuilderFactory;

public class DroolsSingletonKnowledgeBase {

private static KnowledgeBase knowledgeBase;

private DroolsSingletonKnowledgeBase() {

}

public static KnowledgeBase getKnowledgeBase() {

if(knowledgeBase == null) {

knowledgeBase = createKnowledgeBase();

}

return knowledgeBase;

}

private static KnowledgeBase createKnowledgeBase() {

KnowledgeBuilder knowledgeBuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();

// Add Drools Files

// knowledgeBuilder.add(arg0, arg1);

KnowledgeBuilderErrors knowledgeBuilderErrors = knowledgeBuilder.getErrors();

if(knowledgeBuilderErrors.size() > 0) {

for(KnowledgeBuilderError knowledgeBuilderError : knowledgeBuilderErrors) {

System.out.println(“Error : ” + knowledgeBuilderError);

}

throw new RuntimeException(“Could not parse Knowledge Base”);

}

KnowledgeBase knowledgeBase = knowledgeBuilder.newKnowledgeBase();

knowledgeBase.addKnowledgePackages(knowledgeBuilder.getKnowledgePackages());

return knowledgeBase;

}

}


0 Responses on Drools Interview Questions"

Leave a Message

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

Copy Rights Reserved © Mindmajix.com All rights reserved. Disclaimer.
Course Adviser

Fill your details, course adviser will reach you.