droolskie-workbench

Drools workbench: How to make use of global variables inside rule file


I am using Drools workbench 7.17 integrated with Kie execution server. I have created project using workbench which consists of data models, rule file and global definitions.

I want to use global variable to set some value in it if rule is executed and retrieve global variable value. I can achieve this using spring boot application where we add global variable inside session using kieSession.setGlobal("response", response); and retrieves it using kieSession.getGlobal("response"). I tried replicating same with workbench but I am getting null pointer exception when I am trying to set value in global variable. Below is my rule file:

package com.myspace.drools_ruleengine;
import com.myspace.drools_ruleengine.Person;
global com.myspace.drools_ruleengine.Response response;
dialect "mvel"
rule "If person age >= 18 then person is adult"
no-loop
when
    $p: Person(age >= 18)
then
    response.setMessage("Adult");  // throwing error- null pointer exception
end

I have created global definition and added response as a alias for Response class. Is there anything required apart from this ? I am using Kie Server Rest API to insert facts.


Solution

  • You need to initialize global variable while sending requests for rule execution, like as:

    <batch-execution>
    <set-global identifier="obj">
      <com.sample.Test/>
    </set-global>
    <insert>
      <com.Person>
         <name>abc</name>
       </com.Person>
    </insert>
    <fire-all-rules/>
    </batch-execution>
    

    Try with this approach