Prefer KieHelper over a KieContainer classpath

While testing, the use of a KieContainer classpath—the one you get from invoking KieServices.Factory.get().getKieClasspathContainer()—is not always the best approach. The thing with a KieContainer classpath is that it will scan the entire classpath looking for any META-INF/kmodule.xml file.

If we are only interested in testing a single rule or a subset of the rules present in the application's classpath, there is no need to scan the entire classpath looking for all the kmodule.xml files present.

There are different ways in Drools to create narrow containers with only the specific resources required for the specific scenario that we are testing. Probably, the easiest way is to make use of the org.kie.internal.utils.KieHelper class. The KieHelper class is a utility class that allows us to programmatically create a KIEContainer by specifying the resources that we want to include in it. We have already seen examples making use of this class in the previous chapters.

The KieHelper class provides different ways to add resources to the KIE Container that we want to build. It also contains methods to validate these resources and to, finally, create a KieContainer instance from them.

A typical use of the KieHelper class can be seen in the following code snippet:

KieHelper kieHelper = new KieHelper();
kieHelper.addResource(ResourceFactory.newClassPathResource("some/file.drl"), ResourceType.DRL);
//add more resources if needed
Results results = kieHelper.verify();
if (results.hasMessages(Message.Level.WARNING, Message.Level.ERROR)){
    //fail
}
KieBase kieBase = kieHelper.build()

There is no factory for the KieHelper class, it can be simply instantiated in our code. Once we have an instance, we can use its addResource(), addContent(), and addFromClassPath() methods to add resources to it. Once we have added all the resources we want, we can verify them by invoking the verify() method. This method will return the verification results indicating whether or not the warnings or errors are present. If everything is OK, we can build a KieBase instances by invoking the build() method.

However, KieHelper is not only useful when dealing with unit/integration tests. Applications may also use this class when a fine-grained control over the resources that should be included in a KIE Container is required. Typical scenarios could be the creation of KIE Bases containing only a certain resources based on certain conditions or the creation of a dynamic KIE Base from a string containing DRL.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.162.214