Search code examples
javadrools

How to access variables from a drools rule file in java without declaring them as global?


I am developing an application which uses the following rules file. Is there a way by which i can get the values of the boolean variables b1, b2 and b3 without declaring them as global?

Drools file

rule ruleone

when
$fact : AppFact( name == "abcd")

then
boolean b1= $fact.id[422] && $fact.id[423]  &&  $fact.id[372]  &&  $fact.ruleId[373];
boolean b2= b1 && $fact.id[272];
boolean b3= b1 && $fact.id[273];


end

Solution

  • From the top of my head, I can think about 2 easy solutions:

    Using a single global service

    Declare a single global service that you can use to notify these boolean values. This is convenient if your concern is having a lot of globals in your DRLs.

    global MyService service;
    
    rule ruleone
    when
        $fact : AppFact( name == "abcd")
    then
        boolean b1= $fact.id[422] && $fact.id[423]  &&  $fact.id[372]  && $fact.ruleId[373];
        boolean b2= b1 && $fact.id[272];
        boolean b3= b1 && $fact.id[273];
    
        service.notifyValues(b1, b2, b3);
    end
    

    This will make the boolean values available to whatever object you configure as service.

    Using facts and queries

    The idea of this approach is to insert your booleans as facts (wrapped in an object) and then use queries to extrac them from the session.

    rule ruleone
    when
        $fact : AppFact( name == "abcd")
    then
        boolean b1= $fact.id[422] && $fact.id[423]  &&  $fact.id[372]  && $fact.ruleId[373];
        boolean b2= b1 && $fact.id[272];
        boolean b3= b1 && $fact.id[273];
    
        insert(new Result(b1, b2, b3));
    end
    
    query getResults()
        $r: Result()
    end
    

    For a better understanding about queries, please refer to Drools' documentation.

    Hope it helps,