'Drools 6.0 dynamically load rules at runtime

I want to load a drl file at runtime. The posts I've found including this one work for version 5.0 but I can't figure out how to do it for drools version 6.0.



Solution 1:[1]

In Drools 6, your rules packages are deployed to Maven. A KieScanner is provided, which you can attach to your KieContainer. This polls your repository at a defined interval to see whether a package has been updated and downloads the latest if that's the case.

A full explanation of how to define a KieScanner (including code samples) is provided in the Drools documentation here:

https://docs.jboss.org/drools/release/latest/drools-docs/html/ch04.html

Solution 2:[2]

I used info taken from those two docs:

I've came out with this snippet that loads rules defined in the /drl/file/path file into the stateful session you obtain at the last line.

    File path = new File("/drl/file/path");
    KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
    kbuilder.add(ResourceFactory.newFileResource(path), ResourceType.DRL);
    if (kbuilder.hasErrors()) {
        throw new RuntimeException("Errors: " + kbuilder.getErrors());
    }
    kbase = KnowledgeBaseFactory.newKnowledgeBase();
    kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
    StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

Some methods are deprecated, so, don't expect this solution to be valid in the following releases.

Please, double check the imports, they are all from org.kie, not from drools packages. I admit those imports are too much, but I'm pasting the code from an example I'm trying to develop, so I have more things on my code, sorry for that.

import java.io.File;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieScanner;
import org.kie.api.builder.ReleaseId;
import org.kie.api.builder.model.KieBaseModel;
import org.kie.api.builder.model.KieModuleModel;
import org.kie.api.builder.model.KieSessionModel;
import org.kie.api.conf.EqualityBehaviorOption;
import org.kie.api.conf.EventProcessingOption;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.conf.ClockTypeOption;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderFactory;
import org.kie.internal.io.ResourceFactory;
import org.kie.internal.runtime.StatefulKnowledgeSession;

Hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 danidemi