1
votes

I am trying to create rules in java by using the Fluent Api. Actually I have successfully created rules in a way I like, however I could not find a way to create a rule without adding a package name.

Java Code:

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);

DRL File:

package org.drools.example  ---> I do not want this to be included

rule "Xyz"
    ruleflow-grou bla
when
    (
    $foo : Foo( bar==baz, x>y )  and
    not( 
    Bar( a+b==c )   ) ) 
then
System.out.println();
end

Thanks in advance.

Note: I am using Drools 7.3.0 which was installed default by eclipse

1
But what's the problem? You want your rules to have different package names?Esteban Aliverti
I'm running my java code to generate more than 10-15 rules at different times for the same package, It just looks dirty in the drl file to see the same package name for each rule over and over again. I do not know what is the best practice but I generally add package names to the start of the file. @EstebanAlivertiFerenku
I see, could you include a code snippet on how are you using the fluent API? Are you invoking DescrFactory.newPackage() for each of the rules you want to generate? How are you getting the DRL from the package that gets built?Esteban Aliverti
Yes to your question @EstebanAliverti . I am searching to find another way of creating rule rather than calling DescrFactory.newPackage() every time.Ferenku

1 Answers

0
votes

What you can do is to reuse the same PackageDescrBuilder for all your rules. After you are done with one rule, just call end().newRule() to start with your other rule:

PackageDescr pkg = DescrFactory.newPackage()
  .name("org.drools.example")
    .newRule().name("Rule 1")
      .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()
    .newRule().name("Rule 2")              // <--- Here starts the new rule
      .lhs()...end()
      .rhs()...end()
.getDescr();

Hope it helps,