user506069 user506069 - 16 days ago 5
Java Question

Loading and updating rules from a database in Drools 6

How would one go about loading rules from a database table at startup and updating them from the same table in Drools 6.2.0? I've found an example using Drools 5 that I could probably convert from Scala to Java but it looks like the API has changed pretty drastically... I don't see the RuleBaseFactory class, for example.

Any sample or documentation would be appreciated.

Answer

I'm not sure from where that org.dools.RuleBaseFactory was taken. Below is how it was done in Drools 5.3 (and possibly earlier) up to 5.6:

KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ..., ResourceType.DRL);
if( kbuilder.hasErrors() ){
    System.err.println( "### compilation errors ###" );
    KnowledgeBuilderErrors errors = kbuilder.getErrors();
    for( KnowledgeBuilderError err: errors ){
        System.err.println( err.toString() );
    }
    throw new IllegalStateException( "compile errors" );
}
KnowledgeBase kbase = kbuilder.newKnowledgeBase();
StatelessKnowledgeSession ksession = kbase.newStatelessKnowledgeSession();

The ellipsis indicates the place for inserting the data holding the rule text. Check the API for suitable types; a java.lang.String should be acceptable.

This is the way I use for 6.2:

KieServices kieServices = KieServices.Factory.get();
KieFileSystem kfs = kieServices.newKieFileSystem();
kfs.write( "src/main/resources/simple.drl", ... );
KieBuilder kieBuilder = kieServices.newKieBuilder( kfs ).buildAll();
Results results = kieBuilder.getResults();
if( results.hasMessages( Message.Level.ERROR ) ){
    System.out.println( results.getMessages() );
    throw new IllegalStateException( "### errors ###" );
}
KieContainer kieContainer =
    kieServices.newKieContainer( kieServices.getRepository().getDefaultReleaseId() );
KieBase kieBase = kieContainer.getKieBase();
kieSession = kieContainer.newKieSession();