DRL Drools get rule name salience agenda-group in DRL file
This post 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:
DRL file:
Output:
This post 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
No comments:
Post a Comment