Is there any API in drools to create the drl files dynamically by just passing values?

bhadram picture bhadram · Dec 17, 2014 · Viewed 7.7k times · Source

I know how to create DRL files inside KIE workbench by using all the methods. But what my problem is without using the KIE workbench, can we create the .drl file by using our required values.If any possibility is there please suggest me. Same way suggest me any API is regarding to that. Thanks in advance.

Answer

Abhishek picture Abhishek · Oct 6, 2016

You can use Drools Fluent API. Try below sample code :

package com.sample;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.drools.lang.DrlDumper;
import org.drools.lang.api.DescrFactory;
import org.drools.lang.descr.PackageDescr;

@SuppressWarnings("restriction")
public class Drl_Creator {
    public static void main(String str[]){
        PackageDescr pkg = DescrFactory.newPackage()
                   .name("org.drools.example")
                   .newRule().name("Xyz")
                       .attribute("ruleflow-grou","bla")
                   .lhs()
                       .and()
                           .pattern("Foo").id( "$foo", false ).constraint("bar==baz").constraint("x>y").end()
                           .not().pattern("Bar").constraint("a+b==c").end().end()
                       .end()
                   .end()
                   .rhs( "System.out.println();" ).end()
                   .getDescr();
        DrlDumper dumper=new DrlDumper();
        String drl=dumper.dump(pkg);
        System.out.print(drl);
        try{
            // create new file
            File file = new File("src/main/rules/test.drl");
            file.createNewFile();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(drl);
            // close connection
            bw.close();
            System.out.println("File Created Successfully");
         }catch(Exception e){
             System.out.println(e);
         }
    }
}