Reputation: 311
I have a situation where I need to check if there are 2 EObjects of type A. For that I have written a query like:
query checkA()
$r1 : EObject(eClass().getName() == "A")
$r2 : EObject(eClass().getName() == "A",this != $r1)
end
And in the same way if 3 EObjects of type B
query checkB()
$r1 : EObject(eClass().getName() == "B" , some_more_constraints)
$r2 : EObject(eClass().getName() == "B" , some_more_constraints,this != $r1)
$r3 : EObject(eClass().getName() == "B" , some_more_constraints,this != $r1,this != $r2)
end
And I need to check if either 2 EObjects of type A OR 3 EObjects of type B is there. I have a rule for that :
Rule "checking"
when
checkA()
||
checkB()
then
... do_something...
When I am running the rule, it is giving a ClassCastException exception.
It would be really helpful if you please help me understand why this is happening and answer the below two questions. a) How can I implement this? b) What is the return type of either of checkA() or checkB() queries ?
If I remove the '||' condition from the rule, then it is running fine without any error.
Many thanks in advance.
Upvotes: 0
Views: 580
Reputation: 6322
There are 2 important things to understand here:
when
section of a rule, don't return a value.||
operator doesn't work as a usual or
operator in Drools.A query (without unbounds arguments) in Drools, when used inside a the when
section of a rule, behaves similar to having the same patterns you have in it copied into the rule.
Let's take for example the following DRL:
query strings()
$s1: String()
String(this != $s1)
end
rule "Test"
when
strings()
then
//do something...
end
When inserting 2 Strings
(s1
and s2
) in the session, we will have 2 activations of the Test
rule:
[s1, s2]
[s2, s1]
OR
between patternsWhen Drools finds an || between the patterns of a rule, it basically splits the rule into 2. The biggest difference between this behaviour and a regular or
in any other programming language is that in the case that both parts of the or
operation are true, the rule will be activated twice.
So, for example, the following rule:
rule "Test"
when
String(this == "ABC") ||
String(this == "DEF")
then
//Do something
end
will create 2 different rules in runtime:
rule "Test-1"
when
String(this == "ABC")
then
//Do something
end
rule "Test-2"
when
String(this == "DEF")
then
//Do something
end
One of the problems when using ||
is that you have to be very careful when using bound variables in your patterns, because you don't know whether they will contain a value or not.
I guess your Exception is actually caused by how are you binding your variables in the when section of your rule
I hope that now that you know a little bit more about how Drools works when using queries and the ||
operator, you will be able to trace down where and why the exception is happening.
Upvotes: 1