问题
A drools newbie here, Following is the java class structure.
public class Person {
List<PersonAddress> personAddress;
}
public enum AddressType {
CURRENT, PREVIOUS;
}
public class PersonAddress{
Address address;
AddressType type
Integer timeAtAddress;
}
public class Address {
String city;
String country;
String street;
}
I have to write some code to validate PersonAddress in drools. Rule 1. if person has list of PersonAddress instances, if one of them being AddressType == CURRENT and timeAtAddress < 3, then i want to find whether that list contains a address where AddressType == PREVIOUS.
Rule 2. If above condition is true, then i want to get the PersonAddress instance where AddressType == PREVIOUS,
Drools version 5.5.0.Final,
Java 1.7
Functions can be used
This is something i tried, but it doesnt work
function boolean isPreviousAddressExist(java.util.List list) {
if(list.isEmpty()) {
return false;
}
boolean validRecordFound = false;
for(int addressIndex = 0; addressIndex < list.size(); addressIndex++) {
PersonAddress pa = (PersonAddress)list.get(addressIndex);
if(AddressType.CURRENT.equals(pa.getAddressType()) && pa.getTimeAtAddress() != null && pa.getTimeAtAddress() < 3) {
validRecordFound = true;
break;
}
}
boolean previousRecordFound = false;
if(validRecordFound) {
for(int addressIndex = 0; addressIndex < list.size(); addressIndex++) {
PersonAddress pa = (PersonAddress)list.get(addressIndex);
if(AddressType.PREVIOUS.equals(pa.getAddressType())) {
previousRecordFound = true;
break;
}
}
} else {
previousRecordFound = true;
}
return previousRecordFound;
}
rule "Previous-Physical-Home Address is required for Time at Current-Physical-Home"
when
$quotation:Quotation()
eval(!isPreviousAddressExist($quotation.getApplicantList()))
then
runningResults.addRunningResult(new BusinessRuleRunningResult(null, " A Previous physical Home Address is required.", false));
end
回答1:
Here are both rules, using extends
to avoid the repetirion:
rule "brief CURRENT"
when
Person( $name: name, $pa: personAddress )
PersonAddress( type == AddressType.CURRENT, timeAtAddress < 3 ) from $pa
then
end
rule "no PREVIOUS"
extends "brief CURRENT"
when
not PersonAddress( type == AddressType.PREVIOUS ) from $pa
then
System.out.println( "invalid. " + $name );
end
rule "has PREVIOUS"
extends "brief CURRENT"
when
$ppa: PersonAddress( type == AddressType.PREVIOUS ) from $pa
then
System.out.println( "valid. " + $name +
" at " + $ppa.getAddress().getCity() );
end
This assumes that there is only one CURRENT per Person; if not, the rules might fire more than once. Use exist
to avoid.
I didn't try to find a bug in your code as "doesn't work" is too vague. Anyway, if you are using rules, what's the point in writing procedural code doing the checks?
来源:https://stackoverflow.com/questions/25717009/list-validation-in-drools