如何使用 j-easy easy-rules 编写条件以查找集合中的任何匹配值

how to write condition using j-easy easy-rules to find any matching value in a set

我想写一个条件来判断facts中的任何一个设定值是否满足条件

这是我的规则定义:

public void evaluateRule(Facts facts, String ruleNum) {
        SpRuleDefinition spRuleDefinition = spRuleDefinitionService.findByRuleNum(ruleNum);
        System.out.println("Invoke Action : " + spRuleDefinition.getActionNum());
        facts.put("action", "ACTION1");
        MVELRule rule = new MVELRule()
                            .name("Rule1")
                            .description("My Rule")
                            .priority(1)
                            .when("shipment.orgNum=='ORG1' && (shipment.fromAddress.country=='IN' || shipment.toAddress.country=='IN') && shipment.shipmentLines.itemDetail.active==false")
                            .then("shipment.setOutcome(action);");
        Rules rules = new Rules();
        rules.register(rule);   
        //Fire rules on known facts
        RulesEngine rulesEngine = new DefaultRulesEngine();
        rulesEngine.fire(rules, facts);
    }

我传递的输入可以是这样的:

{"orgNum": "ORG1", "fromAddress": { "country": "SGP"}, "shipmentLines": [{ "itemDetail": {"active": true, "countryOfOrigin": "IN"}, "itemNum": "I1", "quantity": 10 }, { "itemDetail":{"active":假,"countryOfOrigin":"US"},"itemNum":"I2","quantity":1}],"toAddress": { "country": "IN"}}

我想评估是否有任何一个装运行的 itemDetail 的活动标志设置为 false。 上述规则失败,出现以下异常:

org.mvel2.PropertyAccessException: [Error: could not access: itemDetail; in class: java.util.HashSet]
[Near : {... s.country=='IN') && shipment.shipmentLines.itemDet ....}
]

这是一个 MVEL 问题,而不是 EasyRules 问题。

I would like to evaluate if any one of the shipment lines has itemDetail that has the active flag set to false.

您可以定义一个函数来迭代集合并检查您的条件。这是一个例子:

@Test
public void testConditionOnSet() {
    Set<ItemDetail> itemDetailSet = new HashSet<>();
    itemDetailSet.add(new ItemDetail(false));
    itemDetailSet.add(new ItemDetail(false));
    itemDetailSet.add(new ItemDetail(true));

    String condition = "active = false;\n" +
            "foreach (itemDetail : itemDetails) {\n" +
            "   active = active && itemDetail.active;\n" +
            "}\n" +
            "System.out.println(\"Is there a non active itemDetail?: \" + !active);";
    Map facts = new HashMap();
    facts.put("itemDetails", itemDetailSet);

    Object result = MVEL.eval(condition, facts);
}

static class ItemDetail {
    private boolean active;

    public ItemDetail(boolean active) {
        this.active = active;
    }

    public boolean isActive() {
        return active;
    }
}

此示例打印:Is there a non active itemDetail? true.

希望对您有所帮助。