2

How to build Drools rules in Java dynamically instead of providing static drl file?

I have a set of matching rules defined in xml that I need to parse and be able to reload it in runtime. Is there any way to build Drools rules dynamically? Couldn't find it in the docs.

nau
  • 21
  • 1
  • 2
  • 1
    This seems like a backwards way of going. A rules engine is just a bunch of if then The whole purpose of Rules Engines was to externalize the DECISIONS and ACTIONS from the code. You want the code to generate the rules, why not code if statements of your own in the code and get rid of the rules engine ? – Romain Hippeau Jun 25 '10 at 18:20
  • have you tried using DSLs that drools provides? Seems,with a bit of effort you can get that to work. I have personal experience in this,cause I have a case where I have rules that change dynamically. I use a DB as the backend. But XML should be doable as well. – Avinash Jan 13 '14 at 07:35

2 Answers2

0

I agree with former answers and comments that rules are ment to be the "static" part. When rules are created dynamically on demand, the usage of a rules engine is questionable. However, there are cases where rules are not provided in form / format that drools can handle out of the box. In such cases programmatical creation of rules during the initialization phase is needed.

These things said, here is how you can add a rule (given as a String) to drools.

public void addRule(String myRuleStatement, String myPackage, RuleBase myRuleBase ) {
    PackageBuilder packageBuilder = new PackageBuilder(new Package(myPackage));
    packageBuilder.addPackgeFromDrl( new StringReader( myRuleStatement ) );
    myRuleBase.addPackage ( packageBuilder.getPackage() );
}
spike
  • 432
  • 1
  • 6
  • 15
0

I agree with Romain's comment - if you have the rules in some declarative form - you could just generate code directly from that - unless there is higher order logic implicit in those rules (unlikely I have found), or perhaps you want to do a one time migration to a rule language out of the XML.

Michael Neale
  • 19,248
  • 19
  • 77
  • 109
  • 1
    No, I just want to use quick and tested Rete algorithm implementation. I need to create possibly large set of rules and fire them against lots of facts. I believe that straight 'if' realization wont be optimal. Anyway, I decided to generate rules file and compile it in runtime. – nau Jun 30 '10 at 10:37