How to load Drools Rule From DB

3.2k views Asked by At

I am trying to load a drool rule file from database. How can I fire this rule?

kbuilder.add(
    ResourceFactory.newClassPathResource("myrule.drl"),
    ResourceType.DRL
);
2

There are 2 answers

1
Karol On

Provide content of rule from DB (jdbc etc.) and store it in a variable. Then us it (before kie drools) in kbuilder.

String ruleContent; // fill this from DB in diffrent method/aspect

KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase();
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
Resource r = ResourceFactory.newReaderResource((Reader) new StringReader(ruleContent));
kbuilder.add(dsl, ResourceType.DRL);
if (kbuilder.hasErrors()) {
    log.error(kbuilder.getErrors().toString());
}
kbase.addKnowledgePackages(kbuilder.getKnowledgePackages());
StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession();

// prepare fact object

ksession.insert(factObject);
ksession().fireAllRules()
0
Duane5000 On

I did not have formatted rules in the database; values were stored in the table such as test types, scores and date range. Formatting done programmatically. A set of processors was used to return rules of various kinds to be concatenated(not shown). But I found that table driven did not satisfy all requirements and I want my client to be able to sunset those rules in favor of flat-file. The following was used to provide both. I envision the flat-file used in a cloud environment to allow clients to each have respective S3 buckets from which to pull rules as a form of customization.

// Demonstrates table-driven and flat-file rules BOTH added to a virtual file system and consumed by drools
// tested on kie 7.74 and 7.48
// a java class, processor, is returning a valid rule string complete with package and imports.

String exemptRuleStr = exemptProcessor.buildRules(true);
StringBuffer allRules = new StringBuffer();

allRules.append(exemptRuleStr);

_logger.info("\n\n" + allRules + "\n\n");
String flatFileDrl =  "src" + File.separator + "main" + File.separator + "resources" + File.separator + "rules.drl";

//named session used to prevent redundant load
if (kieBaseCache.get("validateStudent") == null) {
    KieServices ks = KieServices.Factory.get();
    //Table driven rules constructed in processor and referenced here as in-memory
    String inMemoryDrlFileName = "src" + File.separator + "main" + File.separator + "resources" + File.separator + "stateFulSessionRule.drl";
    KieFileSystem kfs = ks.newKieFileSystem();
    // all rules added to Kie-File-System as I use both table-driven and flat-file 
    kfs.write(inMemoryDrlFileName, ks.getResources().newReaderResource(new StringReader(allRules.toString()))
            .setResourceType(ResourceType.DRL));
    File tempFile = new File(flatFileDrl);
    if (tempFile.exists() && tempFile.isFile()){
        String content = new String(Files.readAllBytes(Paths.get(flatFileDrl)),
                Charset.forName("UTF-8"));
        //flat file rules used here and added to Kie-File-System        
        kfs.write(flatFileDrl,ks.getResources().newReaderResource(new StringReader(content))
                .setResourceType(ResourceType.DRL));
    } else {
        Resource res = ResourceFactory.newClassPathResource(flatFileDrl);
        if(res.getInputStream()!= null){
            kfs.write(res);
        } 
    }


    KieBuilder kieBuilder = ks.newKieBuilder(kfs).buildAll();
    if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
        _logger.debug(kieBuilder.getResults().toString());
    }
    KieContainer kContainer = ks.newKieContainer(kieBuilder.getKieModule().getReleaseId());
    KieBaseConfiguration kbconf = ks.newKieBaseConfiguration();
    KieBase kbase = kContainer.newKieBase(kbconf);
    kieSession = kbase.newKieSession();
    _logger.debug("Put rules KieBase into Custom Cache");
    kieBaseCache.put("validateStudent", kbase);
} else {
    _logger.debug("Get existing rules KieBase from Custom Cache");
    kieSession = kieBaseCache.get("validateStudent").newKieSession();
}


// add object/facts to session
    kieSession.insert(StudentCache.getInstance().getStudent(values));


kieSession.fireAllRules();
kieSession.dispose();