8

I am having difficulties in writing a rule which match with an enum value in its lhs.

For example, if I have the following enum:

public enum EStatus {
  OK,
  NOT_OK
}

I would like to use it in something like this:

rule "my rule"
dialect "java"
    when        
        status : EStatus()                      // --> this works, but I want to be more specific
        // status : EStatus(this == EStatus.OK) // --> doesn't work. How can I make it work?
    then
        // ...
end

Is this even possible in Drools? I use version 5.1.1.

Calin
  • 1,471
  • 1
  • 15
  • 22

4 Answers4

13

This works for me:

rule "my rule"
when
    Ticket(status == EStatus.OK)
then
    ...
end

so that should work too:

rule "my rule"
when
    EStatus(this == EStatus.OK)
then
    ...
end

Verify if it still occurs in Drools 5.3 and file a bug if it does in jira

Geoffrey De Smet
  • 26,223
  • 11
  • 73
  • 120
  • Thanks for pointing it out. Now it also works for me. It's strange, because I verified multiple times the issue before posting it here. Most probable something slipped out... – Calin Nov 21 '11 at 14:57
0

I tried to use Enum on LHS [ Ticket(status == EStatus.OK) ], I get compile time error something like following:

BuildError: Unable to Analyse Expression status == EStatus.OK Error: unable to resolve method using strict-mode:....

Solution:

In rule LHS, we have to compare with a Constant value... for example: user : User(age > 60) - here we are comparing age with Constant value 60.

So for using Enum, Ticket(status == EStatus.OK)... I had to use some constant in place of EStatus.OK to compare this with status. For this reason, I used one static method in Enum.

So, the LHS of rule now looks like: Ticket(status == EStatus.getEStatus(1))

and EStatus enum is like following:

public enum EStatus {

// you can use values other than int also
OK(1),
ERROR(2);

private int value;

EStatus(int number) { this.value = number; }

public int valueOf()
{
    return this.value;
}

public static EStatus getEStatus(int value){
    EStatus eStatus = null;

    for(EStatus e : EStatus.values()){
        if(e.valueOf() == value){
            eStatus = d;
            break;
        }
    }

    return eStatus;
}

}

I have tested this using jdk 1.6 and both in Linux and Windows environment.

Enjoy coding!

Shekh Akther
  • 713
  • 6
  • 13
0

Another solution. You just need to add getter in the Estatus enum as below.

public enum EStatus  {
OK,
NOT_OK;

public EStatus getValue(){
    return this;
}

}

Then you can write rule as below

rule "my rule"
when
    EStatus(value == EStatus.OK)
then
    ...
end
Himanshu Ahire
  • 677
  • 5
  • 18
0

That also should do the trick:

rule "my rule"
when
    $status : EStatus()
    eval ( $status == EStatus.OK )
then
    ...
end