Rana Sujitha
Rana Sujitha

Reputation: 1

How to compare XML with rules from DB and create custom Drools DRL Rule Engine Template

I am pretty new to Drools. So I need help with this scenario. Please ask me as many questions please if I have missed anything.

I have this XML:

<?xml version="1.0" encoding="UTF-8"?>
<SomeEvent>
    <parent-list>
        <track-code>EA</track-code>
        <special-grp>
            <handling-cd>02</handling-cd>
        </special-grp>
        <recipient-country-code>DE</recipient-country-code>
        <shipper-country-code>US</shipper-country-code>
    </parent-list>
</SomeEvent>

I have to compare this XML against DB Rules as follows:

rule_mapping_table
RuleAttribute   XmlAttribute
==============================
eventType       parentList.trackCode
originCountry   parentList.shipperCountryCode
destCountry     parentList.recipientCountryCode
splHandCd   parentList.specialGrp.handlingCd

All the ruleAttribute has to be picked and compared to the rule table:

rule_table
RuleId RuleAttribute Condition Value ParcelValue
=========================================
1  eventType      equals    EA       1000
1  originCountry  equals    US       1000
1  destCountry    equals    DE       1000
1  splHandCd      notEquals 01       1000
2  eventType      equals    AA       1105

All the matching rules/records should be returned and need to put into custom DRL file.

template "tmp1"

rule "@{id}"
  dialect "mvel"
  when
    @{ifcondition};
  then
    @{thencondition};
end

end template

For example:

rule "1"
    when
        SomeEvent(parentList.trackCode == "EA" 
            && parentList.recipientCountryCode == "DE" 
            && parentList.shipperCountryCode == "US")
    then
        System.out.println("========== Rule kicked in is No. 1 =============");
        shipment.setAmount(1000);
end

What I have tried till now:

public SomeEvent getRules(SomeEvent someEvent) {
        List<Rule> ruleAttributes = new ArrayList<>();
        rulesRepo.findAll().forEach(ruleAttributes::add);
        ObjectDataCompiler compiler = new ObjectDataCompiler();
        String generatedDRL = compiler.compile(ruleAttributes, Thread.currentThread().getContextClassLoader().getResourceAsStream(DroolsConfig.CONTRACT_EVENT_RULES_DRL));
        KieServices kieServices = KieServices.Factory.get();
        
        KieHelper kieHelper = new KieHelper();
        
        //multiple such resources/rules can be added
        byte[] b1 = generatedDRL.getBytes();
        Resource resource = kieServices.getResources().newByteArrayResource(b1);
        kieHelper.addResource(resource, ResourceType.DRL);
        
        KieBase kieBase = kieHelper.build();
        
        KieSession kieSession = kieBase.newKieSession();
        kieSession.insert(someEvent);
        
        kieSession.fireAllRules();
        kieSession.dispose();
        
    return someEvent;
    }

Upvotes: 0

Views: 15

Answers (0)

Related Questions