Update managed object fragement

    "id": "43348402",
    "type": "abc",
    "name": "TestNameTesting20",
    "c8y_Rules": [
        {
            "name": "da",
            "Date": "2024-01-26T10:36:43.000Z",
            "isActive": false
        },
        {
            "name": "TestRule",
            "isActive": true
        }
    ]}```

Need to update the isActive flag to true where Date property is present in the above fragement.

Something along the lines of:

ManagedObject mo := <your MO>
AnyExtractor rulesAE :=
    AnyExtractor(mo.params.getOrDefault("c8y_Rules"));
sequence<any> rulesSeq := rulesAE.getSequenceOr("", new sequence<any>);
any rule;
for rule in rulesSeq {
    if rule.hasEntry("date") {
        rule.setEntry("isActive", true);
    } else { // If you also looking to set false when date not present.
        rule.setEntry("isActive", false);
    }
}
send mo to ManagedObject.SEND_CHANNEL;

You could also be a bit more explicit if you care about logging errors:

if mo.params.hasKey("c8y_Rules") {
    AnyExtractor rulesAE :=
        AnyExtractor(mo.params["c8y_Rules"]);
    ...
} else {
    log "c8y_Rules fragment missing from ManagedObject " + mo.id at ERROR;
}

As a further refinement you may also want to track if any items in c8y_Rules were updated so that you don’t send spurious ManagedObject updates to the REST API.

I need to write the code for java microservice

var mor = inventoryApi.get("43348402");
if (mor.hasProperty("c8y_Rules") {
  var rules = mor.get(c8y.Rules.class); // assuming you have a c8y.Rules class, but for some reason I doubt you have
  // or
  var rules = (List<Map<String, Object>>)mor.getProperty("c8y_Rules");
  rules.forEach(rule -> {
    if (rule.hasKey("Date")) {
      rule.put("isActive", true);
    }
  });
}
updatedMor = new ManagedObjectRepresentation();
updatedMor.setId(mor.getId());
updatedMor.setProperty("c8y_Rules", rules); // You just need to update that property
inventoryApi.update(updatedMor);

Just writing this directly in here, not from my IDE, so there might be some typo, but you get the idea.

1 Like