 Java, Spring and Web Development tutorials  1. Introduction
In many Drools-based applications, it’s important not only to execute rules but also to understand which rules actually fired. In this article, we explore multiple approaches to track fired rules in Drools, including a custom AgendaEventListener and a RuleContext-based utility method.
2. Maven Dependency
KIE (Knowledge Is Everything) is the core framework behind Drools. It provides the infrastructure for defining and executing business rules and other knowledge assets outside of application code. Let’s start by importing the kie-ci dependency to our pom.xml:
<dependency>
<groupId>org.kie</groupId>
<artifactId>kie-ci</artifactId>
<version>10.0.1</version>
</dependency>
The kie-ci is required when using Maven-based KIE modules and dynamic rule loading, which is a common pattern in modern Drools setups.
3. Drools Example
In this section, we’ll walk through a simple example that demonstrates how to use Drools in practice.
3.1. The Person Model
To demonstrate how rule tracking works, we start with a simple Person domain model:
public class Person {
private String name;
private int age;
private boolean eligibleToVote;
private boolean priorityVoter;
public Person(String name, int age) {
this.name = name;
this.age = age;
this.eligibleToVote = false;
this.priorityVoter = false;
}
// standard getters and setters
}
This class defines a few attributes relevant to voting decisions, such as a person’s age and voter-status flags. The rules will update these fields as the conditions are evaluated.
3.2. The Rule File
Next, we define our rules inside a DRL file:
rule "Check Voting Eligibility Event"
when
$person : Person(age >= 18)
then
$person.setEligibleToVote(true);
update($person);
end
rule "Senior Priority Voting Event"
when
$person : Person(age >= 65)
then
$person.setPriorityVoter(true);
update($person);
end
Each rule evaluates a specific condition on the Person object and updates the appropriate fields:
- Check Voting Eligibility – Marks a person as eligible to vote if they meet the minimum age requirement.
- Senior Priority Voting – Assigns priority voting status to individuals who fall within the senior age group.
4. Find List of Matched Rules Using AgendaEventListener
In this section, we introduce a custom AgendaEventListener that automatically records each fired rule.
4.1. AgendaEventListener
Drools provides several built-in event listeners that allow us to react to different phases of the rule engine lifecycle. To track which rules were actually fired during a session, we can register an AgendaEventListener and listen specifically for the afterMatchFired() event. This callback is invoked immediately after a rule is successfully executed. Let’s create the TrackingAgendaEventListener class:
public class TrackingAgendaEventListener extends DefaultAgendaEventListener {
private final List<Match> matchList = new ArrayList<>();
@Override
public void afterMatchFired(AfterMatchFiredEvent event) {
matchList.add(event.getMatch());
}
public List<String> getFiredRuleNames() {
List<String> names = new ArrayList<>();
for (Match m : matchList) {
names.add(m.getRule().getName());
}
return names;
}
}
Here, the listener overrides only the afterMatchFired() method, which is sufficient for logging rule execution. Every time a rule fires, the listener extracts the rule’s name from the event and appends it to the tracker. Now, we need to attach the listener to the KieSession:
KieSession kieSession = new DroolsBeanFactory().getKieSession();
TrackingAgendaEventListener listener = new TrackingAgendaEventListener();
kieSession.addEventListener(listener);
This approach is completely decoupled from the DRL file—no modifications to the rules themselves are required—making it a clean and non-intrusive way to audit rule execution.
4.2. Test
Let’s create a test to verify that our TrackingAgendaEventListener correctly records the names of the rules that fire during the execution of the Drools session:
@Test
public void givenRuleFired_whenListenerAttached_thenRuleIsTracked() {
// Given
Person person = new Person("Bob", 65);
TrackingAgendaEventListener listener = new TrackingAgendaEventListener();
kieSession.addEventListener(listener);
// When
kieSession.insert(person);
kieSession.fireAllRules();
kieSession.dispose();
// Then
assertFalse(listener.getFiredRuleNames().isEmpty());
assertTrue(listener.getFiredRuleNames().contains("Check Voting Eligibility Event"));
assertTrue(listener.getFiredRuleNames().contains("Senior Priority Voting Event"));
}
We begin by creating a Person instance whose attributes satisfy the conditions of both rules in our rule set. In this example, a 65-year-old person triggers both the “Check Voting Eligibility Event” rule (because age ≥ 18) and the “Senior Priority Voting Event” rule (because age ≥ 65). Next, we register our custom TrackingAgendaEventListener with the KieSession. By attaching the listener before inserting the facts, we ensure that every rule fired during the session is captured. After inserting the Person fact and executing the rules, we inspect the listener to confirm the results.
5. Find List of Matched Rules Using RuleContext
In this section, we introduce a RuleContext-based method that allows manual tracking within the DRL file.
5.1. RuleContext
While an AgendaEventListener provides a non-intrusive way to observe rule execution from outside the rule base, in some cases, we may want finer control over when and how a rule is recorded. Drools exposes this capability through the RuleContext API, which provides access to the rule currently being executed from within the DRL file itself. To use this approach, we define a small utility class containing a static method that accepts both the rule context and our RuleTracker:
public class RuleUtils {
public static void track(RuleContext ctx, RuleTracker tracker) {
String ruleName = ctx.getRule().getName();
tracker.add(ruleName);
}
}
This method extracts the active rule’s name from the Drools context and appends it to the tracker. Let’s create the RuleTracker class:
public class RuleTracker {
private final List<String> firedRules = new ArrayList<>();
public void add(String ruleName) {
firedRules.add(ruleName);
}
public List<String> getFiredRules() {
return firedRules;
}
}
Unlike the listener-based approach, this mechanism allows the rule author to decide exactly where rule tracking should occur within the consequence block. To make the method available inside the .drl file, we import it at the top of the rule file and invoke the method directly inside a rule:
package com.baeldung.drools.rules
import com.baeldung.drools.matched_rules.Person;
import com.baeldung.drools.matched_rules.RuleTracker;
import static com.baeldung.drools.matched_rules.RuleUtils.track;
rule "Check Voting Eligibility"
when
$person : Person(age >= 18)
$tracker : RuleTracker()
then
track(drools, $tracker);
$person.setEligibleToVote(true);
update($person);
end
rule "Senior Priority Voting"
when
$person : Person(age >= 65)
$tracker : RuleTracker()
then
track(drools, $tracker);
$person.setPriorityVoter(true);
update($person);
end
5.2. Test
Let’s create a unit test to verify that when a Person instance satisfies the conditions of our rules, the RuleContext-based tracking correctly records all fired rules:
@Test
public void givenPerson_whenRulesFire_thenContextTracksFiredRules() {
// Given
Person person = new Person("John", 70);
RuleTracker tracker = new RuleTracker();
// When
kieSession.insert(person);
kieSession.insert(tracker);
kieSession.fireAllRules();
kieSession.dispose();
// Then
List<String> fired = tracker.getFiredRules();
assertTrue(fired.contains("Check Voting Eligibility"));
assertTrue(fired.contains("Senior Priority Voting"));
assertTrue(person.isEligibleToVote());
assertTrue(person.isPriorityVoter());
}
We create a Person aged 70, who satisfies both rules (Check Voting Eligibility and Senior Priority Voting), and a RuleTracker to capture fired rules. Then, we insert both facts into the KieSession, and call fireAllRules(), which executes the rules. Finally, we assert that both expected rules are present in the RuleTracker and the Person instance has the correct fields updated (eligibleToVote and priorityVoter).
6. Conclusion
In this article, we explored two practical techniques for determining which Drools rules were fired during a KIE session. Using an AgendaEventListener allows us to track rule executions transparently without modifying the rule files, making it a clean, non-intrusive option for most applications. On the other hand, the RuleContext approach offers explicit, rule-level control by recording rule firings directly within the DRL itself. As always, the source code is available over on GitHub. The post Find List of Matched Rules in Drools first appeared on Baeldung.
Content mobilized by FeedBlitz RSS Services, the premium FeedBurner alternative. |