I'm new to Drools and trying to create a Drools based java app. I have decided to create a Kie Module programmatically instead of writing an XML file. In order to do that, I have below configurations
@Configuration
public class KieContainerConfig {
private static String drlFile = "com/rules/eligibility.drl";
@Bean
public StatelessKieSession kieSession() {
KieServices kieServices = KieServices.Factory.get();
KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
KieBaseModel kieBaseModel1 = kieModuleModel.newKieBaseModel("KBase1 ")
.setDefault(true)
.setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
.setEventProcessingMode(EventProcessingOption.STREAM)
.addPackage(drlFile); // adding drl file
kieBaseModel1.newKieSessionModel("KSession1")
.setDefault(true)
.setType(KieSessionModel.KieSessionType.STATELESS)
.setClockType(ClockTypeOption.get("realtime"));
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.writeKModuleXML(kieModuleModel.toXML());
KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
List<Message> messages = kieBuilder.getResults().getMessages(Message.Level.ERROR);
if (!messages.isEmpty()) {
for (Message err : messages) {
System.err.println(err);
}
}
KieContainer kieContainer = kieServices.newKieContainer(kieServices.getRepository().getDefaultReleaseId());
return kieContainer.newStatelessKieSession("KSession1");}
but when I run the code, app emit java.lang.RuntimeException: Unexpected globa
error. But when I change the code by removing .addPackage(drlFile);
and adding kfs.write(ResourceFactory.newClassPathResource(drlFile));
to the KieFileSystem, Code runs and provide the expected results.
Why I cannot mention the package when creating Kie Base Model instead of using Kie File System's write method?
Per the Javadoc for KieBaseModel
, the addPackage
method takes a pattern. Most commonly it's used like this:
KieBaseModel model = ...
.addPackage("*");
But if you have your rules organized into packages, you could add a package into the model like this:
KieBaseModel model = ...
.addPackage("org.mycompany.rules");
Your alternative, using classpath resources, is how you'd go about adding individual files.
(I recommend using the XML to configure your system. I too have built Spring and Spring-Boot apps with drools, and have never seen the need to over-complicate my life by doing these things manually that Drools does for you from a config file.)