Search code examples
droolsrule-engine

how to fire selected rules in Drool


1- Is it possible to fire only selected rules for a particular customer in Drool. Suppose I have 100 rules these are rules from different customers. So when a particular customer opens up the application I want to fire only those rules which belong to him. It can be possible that a rule can belong to more than one customer.

2 - I want to get a list of rules which needed to be fired for a particular customer and a list of facts to fire those rules so that I can fetch only that particular facts from my db. And after fetching them, fire those rules which are specific to that customer


Solution

  • You'll have to identify the owning customers along with the rules, or maintain data associating a customer with rules. I think that the latter is to be preferred, but I'll outline both solutions. In any case, the Customer has to be identified by a fact.

    rule "some rule"
    when
        Customer( id in ("Smith&Co", "Brown&Sons", "Jones Inc." ) )
        ...
    then ... end
    

    To associcate a Customer with rules you need:

    class Customer {
        private String name;
        private List<String> rules;
        //...
    }
    

    and write an AgendaFilter

    class RuleFilter implements AgendaFilter {
        static List<Customer> customers = new ArrayList<>();
        static {
            customers.add(...);
            ...
        }
        static RuleFilter getFilterFor( String custname ){
             for( Customer cust: customers ){
                 if( cust.getName().equals( custname ) ){
                     return cust;
                 }
             }
             throw IllegalArgumentException( "no customer: " + custname );
        }
        Customer current;
        RuleFilter( Customer current ){
            this.current = current;
        }
        // ... getters & setters
        boolean accept( Match match ){
            return current.getRules().contains( match.getRule().getName() );
        }
    }
    

    And run the session for a customer by providing a filter instance:

     AgendaFilter currFilter = RuleFilter( getFilterFor( customername ) ); 
     fireAllRules( currFilter );