droolsdrools-flow

drools how to fire specified group dynamically


i am using drools 7.x.

my logic looks like following:

if(variableA == 1) {

    if(variableA1 == 2) {
        ....
    } else if(variableA1 == 3) {
        ....
    }
}else {

    if(variableB1 == 1) {
        ....
    }else if(variableB1 == 2) {

        if(variableN == 1) {

        }else if(variableN == 2) {

        }
    }
}

by the way, these variables not in the same class, i intend to insert them as fact in drl.

how can i define the rules? or how can i define rules like :

rule 1
    when
    then
end

rule 2
    when
    then
end

rule 1-1
    when
    then
end

rule 1-2
    when
    then
end

rule 2-1
    when
    then
end

rule 2-2
    when
    then
end

wherein, only one of rules will be fired in rule 1 and rule 2, rule 1-1 and rule 1-2 is group1, rule 2-1 and rule 2-2 is group2.

if rule 1 is fired, then only one of rules is fired in group1, there is no need to test group2. While if rule 2 is fired, then only one of rules is fired in group2, there is no need to test group1.


Solution


  • rule "1"
      salience 1
      activation-group "group 0"
      when
        $model : Model(a == 1)
      then
        insertLogical(new GroupActivation("group 1", $model));
        System.out.println("rule 1");
    end
    
    rule "2"
      salience 1
      activation-group "group 0"
      when
        $model : Model(b == 1)
      then
        insertLogical(new GroupActivation("group 2", $model));
        System.out.println("rule 2");
    end
    
    rule "1-1"
      activation-group "group 1"
      when
        GroupActivation(name == "group 1", $model : model)
        Model(this == $model, a1 == 1)
      then
        System.out.println("rule 1-1");
    end
    
    rule "1-2"
      activation-group "group 1"
      when
        GroupActivation(name == "group 1", $model : model)
        Model(this == $model, a2 == 1)
      then
        System.out.println("rule 1-2");
    end
    
    rule "2-1"
      activation-group "group 2"
      when
        GroupActivation(name == "group 2", $model : model)
        Model(this == $model, b1 == 1)
      then
        System.out.println("rule 2-1");
    end
    
    rule "2-2"
      activation-group "group 2"
      when
        GroupActivation(name == "group 2", $model : model)
        Model(this == $model, b2 == 1)
      then
        System.out.println("rule 2-2");
    end
    

    Model.java

    public class Model {
        
        private int a;
        private int a1;
        private int a2;
        private int b;
        private int b1;
        private int b2;
    ...
    

    GroupActivation.java

    public class GroupActivation {
        
        private String name;
        private Model model;
    ...