Search code examples
javadrools

Can Drools be configured to apply rules to the objects contained in the inserted objects fields?


I have a complex set of rules to implement in Drools and I am trying to avoid duplicate rules. For example, I have a ForeignPerson class that is used by two other classes.

public class ForeignPerson {
  private String name;
  private String country;
}

public class Owner {
  private Individual individual;
  private ForeignPerson foreignPerson;
}

public class Beneficiary {
  private Individual individual;
  private ForeignPerson foreignPerson;
}

In every instance of ForeignPerson the country field must be "USA". I would like to be able to do kieSession.insert(owner); and if the ForeignPerson field is not null have it check the ForeignPerson rules as well as the owner rules.

ForeignPerson.drl rules file like:

rule "R001: Country must == USA"
  when 
    ForeignPerson(country != "USA")
  then 
    System.out.println("Country must be USA");
end

Owner.drl rules file like:

rule "R001: Foreign Person must exist"
  when 
    Owner(foreignPerson == null)
  then 
    System.out.println("foreignPerson must not be null");
end

I don't want to write the Owner.drl file like follows because it would result in a lot of duplicate rules.

rule "R001: Foreign Person must exist"
  when 
    Owner(foreignPerson == null)
  then 
    System.out.println("foreignPerson must not be null");
end

rule "R002: Foreign Person country must be USA"
  when 
    Owner(foreignPerson != null, foreignPerson.getCountry() != "USA")
  then 
    System.out.println("foreignPerson must have country USA");
end

Is this possible or is the only way to inject the objects individually?


Solution

  • The short answer is no. Each object to be checked directly must be inserted separately. The extends key word can be used to validate that the object has the correct parent object though (see this question is it possible to extend a rule using a specified set of parameters or pass parameters into a rule in Drools? ).