Using Global variables in your rules

Global variables are variables assigned to a session. They can be used for various reasons:

  • You can use tham as constants in your session
  • You can use them as output of your rule (think about a reporting—a rule could write some message to a global report variable)
  • You can use it as entry points for some services such as logging, which are used within rules

Now let's create our global object named RiskyAccounts which is a vector containing all accounts which have money less than zero:

package com.sample;

import java.util.ArrayList;

public class RiskyAccounts {
    private ArrayList accounts = new ArrayList();
    
  public void add(Account acc) {
      accounts.add(acc);
  }
  public void listRiskyAccounts() {
      for (Account acc : accounts)
      System.out.println(acc);
  }
}

Now we need to import it as global into our rule:

import com.sample.Account;
import com.sample.RiskyAccounts;

global RiskyAccounts risky;
rule "enoughMoney"
ruleflow-group "helloworldgroup"
	when
	$account : Account( money < 0 )
	then
	  System.out.println( "Not enough money on the account!");
	  risky.add($account);

end

This rule simply adds the rule into the vector if money < 0. We will modify our main class to include in the KSession the global variable RiskyAccount:

package com.sample;

import org.kie.api.KieServices;
import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;

public class App {
	public static void main(String[] args) throws Exception {
		KieServices ks = KieServices.Factory.get();
		KieContainer kContainer = ks.getKieClasspathContainer();
		KieSession kSession = kContainer.newKieSession();
		Account account = new Account();
		account.setName("frank");
		account.setMoney(-10);
		RiskyAccounts risky = new RiskyAccounts();
		kSession.setGlobal("risky", risky);
		kSession.insert(account);
		kSession.startProcess("demo.test");
		kSession.fireAllRules();
	}

}

Now your process will use the RiskyAccounts to store all Accounts which have a negative value for money attribute. Pretty simple, isn't it ?

0
0
0
s2smodern