Nipun
Nipun

Reputation: 4319

using global variable in matches in drools rules

I have this rule set in drools.

global String ipv4regex;

rule "Initialize global"
  salience 1000
when        
then
   drools.getWorkingMemory().setGlobal( "ipv4regex", "\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b");
end

rule "Router"
when
    r : Router( Ipaddress matches ipv4regex)
then
    System.out.println("Valid ip address");
end

Here I am checking for valid ip address, but my rule "Router" is not showing "valid ip address" even if my router ip address is valid. What can be the issue here and how to use global variable in the matches?

Upvotes: 1

Views: 7959

Answers (1)

laune
laune

Reputation: 31300

The setting of the global variable happens too late. You must do this prior to inserting any facts.

This is due to global variables not being monitored by the rule engine - as opposed to facts, where (announced via modify or update) changes are reconsidered, resulting in a reevaluation.

  • Set the global up front in your Java code.
  • Use a static final visible in a Java class
  • Use another fact containing a String with the regec.
  • Use a string literal for the regex.

Later

You can declare a fact type for this purpose in DRL:

declare Const
   pattern: String
end

rule initConst
salience 1000
when
then
    insert( new Const( "\\b(25[0-5]|2..." ) );
end

rule "Router"
when
    Const( $pat: pattern )
    r : Router( Ipaddress matches $pat )
then
    System.out.println("Valid ip address");
end

Upvotes: 3

Related Questions