Saturday, March 7, 2015

How to get the LHS/condition/constraint of Drool's rules file?

Below is the codes to extract rule information from drl file. Although Drools was not designed to parse drl files, there are special cases that I need get the LHS of all rules. In my case, these are unit testing rules files and converting rules file to other format.
KieServices kieServices = KieServices.Factory.get();                     
KieResources kieResources = kieServices.getResources();                  
Resource resource = kieResources.newClassPathResource("Simple.drl");     

DrlParser parser = new DrlParser();                                      
PackageDescr packageDescr = parser.parse(resource);                      
List rules = packageDescr.getRules();                         
for (RuleDescr rule : rules) {                                           
   if (rule.isRule()) {                                                 
      for (BaseDescr desc : rule.getLhs().getDescrs()) {               
         PatternDescr p = (PatternDescr) desc;                        
         System.out.println("id = " + p.getIdentifier()               
            + ", ObjectType = " + p.getObjectType()              
            + ", Constraint = " + p.getConstraint().getDescrs());
      }                                                                
   }                                                                    
}
Simple.drl file:
import com.bunchofcodes.Drools.ExtractRules.Message;

rule "Hello World"
when
    m : Message( status == Message.HELLO )
then
    System.out.println("Hello");
end

rule "GoodBye"
when
    m : Message( status == Message.GOODBYE )
then
    System.out.println("Good bye");
end
Here is the output:
id = m, ObjectType = Message, Constraint = [status == Message.HELLO]
id = m, ObjectType = Message, Constraint = [status == Message.GOODBYE]

No comments:

Post a Comment