Search code examples
javadrools

Drools : Setting a flag from within the drl file


I am testing for some conditions within a Drools drl file, and if any of these conditions is true, I want to set a flag in the calling program.

I tried doing this in the following manner :

--- drl file ----

//created on: 28 Aug, 2013
package flowManagers

import flowHelper.OrderRelatedQueriesFlowHelper;
import entity.Order;
import org.apache.log4j.Logger;

global Logger logger;
global Boolean isValid;

rule "isValid"
no-loop
salience -1
activation-group "AC1" 

when
        $o : Order( OrderRelatedQueriesFlowHelper.isValid($o))
then 
        isValid=Boolean.TRUE;
        logger.info("Valid order..." );
end

--- calling program bit ----

    Boolean isValid=Boolean.FALSE;
    String[] noHappyOrderFileList={"NoHappyOrder.drl"};
    StatefulKnowledgeSession ksession = createKnowledgeSession( noHappyOrderFileList );
    ksession.setGlobal("logger", logger);
    ksession.setGlobal( "isValid", isValid);
    for( Order fo : coll )
    {           
        ksession.insert(fo);
    }
    ksession.fireAllRules();

    logger.info("Valid?? : " + isValid );

But even when the logger prints "Valid order..." within the drl file, the calling program still prints isValid as false.

Could someone please tell me what I am doing wrong ?

Thank you :)


Solution

  • Drools works with "Facts" not objects. A fact is an object but every object is not a fact. Please think about what Boolean.TRUE represents.

    Then think about the following code:

    when
      $orderstatus : OrderStatus(...)
    then
      modify ($orderstatus) {
         valid = Boolean.TRUE
      }
    

    Validity of an OrderStatus fact can only mean one thing, but Boolean.TRUE have a too broad meaning to be used as a fact.