Search code examples
javadrools

How to avoid NullPointerException in Drools if in the 'when' clause are managed values that might be null?


I've the following Drools rule code:

rule "S001_EVENT_Date 2023-02-02 03:01:01.901 +02"
    when 
        // EventRequest(info.timeStamp.equals("2023-02-02 03:01:01.901 +02"));
    
        EventRequest(info.timeStamp != null)  
        && 
        EventRequest(info.timeStamp.equals("2023-02-02 03:01:01.901 +02"));
    then
        // set("S001",15);
        // log(drools,"1st Event rule!");

        System.out.println("1st event rule!");
end

The first commented out line issues, obviously, a java.lang.NullPointerException when info.timeStamp, that is of class String, is null.

I've tried the solution in the lines following the commented out, but the same exception still occurs.

How I've to solve this problem?

I'm understanding that drools doesn't manage conditions as Java do or I've misunderstood the drools syntax.


Solution

  • Instead of using the method equals you can use == to do the string comparison. In Drools, this will do an implicit null check. I'm presuming, of course, that info.timestamp is a String.

    eg.

    EventRequest( info.timestamp == "2023-02-02 03:01:01.901 +02")
    

    Obviously if this were Java you shouldn't be comparing strings with ==, but this is Drools.

    That being said, you can always do a null check like you showed in your example. Your example isn't the best because it won't work as you expect it should should there be multiple EventRequest instances in working memory; the following would be the more appropriate constructions:

    EventRequest( info.timestamp != null,
                  info.timestamp =="2023-02-02 03:01:01.901 +02" )
    

    This requires that both conditions (the null check and the equality) happen on the same EventRequest instance; the , is an "and".

    Alternatively, if the issue is that info is what is actually null, you can clearly check for that as well.

    EventRequest( $info: info != null )
    Info( timestamp != null,
          timestamp =="2023-02-02 03:01:01.901 +02" ) from $info
    

    How many null checks are actually needed depends greatly on what the model actually looks like, but there's no real penalty in defensive coding on the left hand side ("when" clause), which the Drools engine will optimize anyway.