2
votes

I am working on putting some business rules in drool engine.We cannot use KIE workspace UI to author rules.So that is out.

Problem Statement:Create a application(front end angular UI) back end spring boot microservice to author rules.Those authored rules needs to be dynamically refreshed without having to restart the jvm and other micro services which want to use these rules,should use them.For e.g:granting credit or interest rates based dealer credit history ,duration with bank and any new rules which might be designed as per author.I started looking on this and theoretically one could build something like this by using API of drools compiler library. There is code example here. for real time refreshing,there is something called KnowledgeAgent. https://docs.jboss.org/drools/release/5.2.0.Final/drools-guvnor-docs/html/ch09.html

What is the new accepted way of programmatically creating new drools rules in Drools 6?

My problem is I am not able to make this work.Code is running fine but I am not able to see the drl file getting written.In debug mode,I can see string object with proper drl structure.Has anyone encountered this problem before.?

I have seen some examples on github where people have done yoman job to integrate drools in spring boot.I can start with building my service,but I need to be sure that this something which is possible to do

1
This is unclear. Which code should write a DRL file where you don't "see the drl file getting written"? - laune
Where would you like to "see the drl file getting written" and how do you verify that it isn't? -- You make it quite difficult for people trying to help you. - laune
I am sorry about not being clear enough.Example given in link i gave above is not complete .When I checked original API for drool,they have given example about how to use fluent API to create rules pro grammatically.I was able to make it work and find solution.Thanks for your help - MrWayne
I still don't know what didn't work and what is better in your answer. What's the point? - laune

1 Answers

2
votes

Following code will help you create drool rule using code.It is not recommended way and most of people use kie-web interface to design and modify drool rules.Not sure about how we can modify already created .drl files.But this has given me start.Going

package com.sample.model;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;

import org.drools.compiler.lang.DrlDumper;
import org.drools.compiler.lang.api.DescrFactory;
import org.drools.compiler.lang.api.PackageDescrBuilder;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.Message;
import org.kie.api.builder.ReleaseId;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.KieContainer;

//@SuppressWarnings("restriction")
public class GenerateRule {

  public static void main(String[] args) {
    // TODO Auto-generated method stub
    KieContainer container=build(KieServices.Factory.get());
    System.out.println(container.getReleaseId());
    System.out.println(container.getKieBase());
  }

  public static KieContainer build(KieServices kieServices){

     KieFileSystem fileSystem=kieServices.newKieFileSystem();    
     ReleaseId releaseId=kieServices.newReleaseId("com.example.rulesengine", 
         "model-test", "1.0-SNAPSHOT");
     fileSystem.generateAndWritePomXML(releaseId);
     //fileSystem.write("D:/workspace/DroolSamples/src/main/resources/rules/rules.drl", getResource(kieServices, "D:/workspace/DroolSamples/src/main/resources/rules/rules.drl"));
     addRule(fileSystem);

     KieBuilder kieBuilder = kieServices.newKieBuilder(fileSystem);
     kieBuilder.buildAll();
     if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
         throw new RuntimeException("Build Errors:\n" + 
            kieBuilder.getResults().toString());
     }

     return kieServices.newKieContainer(releaseId);
  }
 @SuppressWarnings("restriction")
  private static void addRule(KieFileSystem kieFileSystem) {
    PackageDescrBuilder packageDescrBuilder = DescrFactory.newPackage();


    packageDescrBuilder
            .name("com.sample.model")
            .newRule()
            .name("Is of valid age")
            .lhs()

            .pattern("Person").constraint("age < 18")
            .id("$a", true).end()
            //.pattern().id("$a", false).end()
            .end()
            .rhs("$a.setShowBanner( false );")
            //.rhs("insert(new Person())")
            .end();


    String rules = new DrlDumper().dump(packageDescrBuilder.getDescr());

    KieFileSystem fileSystem=kieFileSystem.write("D:/newrule.drl", rules);
    try{
      // create new file
      File file = new File("src/main/resources/rules/test.drl");
      file.createNewFile();
      FileWriter fw = new FileWriter(file.getAbsoluteFile());
      BufferedWriter bw = new BufferedWriter(fw);
      bw.write(rules);
      // close connection
      bw.close();
      System.out.println("File Created Successfully");
   }catch(Exception e){
       System.out.println(e);
   }


}
  private static Resource getResource(KieServices kieServices, String resourcePath) {

    try {
     //   InputStream is = com.google.common.io.Resources.getResource(resourcePath).openStream(); //guava
        InputStream is=new FileInputStream(new File(resourcePath));
        return kieServices.getResources()
                  .newInputStreamResource(is)
                  .setResourceType(ResourceType.DRL);
    } catch (IOException e) {
        throw new RuntimeException("Failed to load drools resource file.", e);
    }
}
}