Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Rules deployment updates

Rich Turner49c5e9cd54a6
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
index 72c9d8475..6746258a6 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
@@ -379,13 +379,19 @@ public class RulesDeployment<T extends RulesDefinition> {
FactHandle factHandle = update != null ? facts.get(update) : null;
- if (factHandle != null && knowledgeSession != null) try {
- // ... retract it from working memory ...
- LOG.finest("Removed stale attribute fact: " + update);
- knowledgeSession.delete(factHandle);
- } finally {
- // ... and make sure we don't keep a reference to the stale fact
+ if (factHandle != null) {
facts.remove(update);
+
+ if (knowledgeSession != null) {
+ try {
+ // ... retract it from working memory ...
+ LOG.finest("Removed stale attribute fact: " + update);
+ knowledgeSession.delete(factHandle);
+ int fireCount = knowledgeSession.fireAllRules();
+ } catch (Exception e) {
+ LOG.fine("Failed to retract fact:" + update);
+ }
+ }
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index f3c80695b..c0d6648ad 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -29,7 +29,6 @@ import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.util.Pair;
import org.openremote.container.util.Util;
import org.openremote.manager.server.asset.AssetStorageService;
-import org.openremote.model.asset.AssetUpdate;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.shared.rules.AssetRulesDefinition;
@@ -37,11 +36,13 @@ import org.openremote.manager.shared.rules.GlobalRulesDefinition;
import org.openremote.manager.shared.rules.RulesDefinition;
import org.openremote.manager.shared.rules.TenantRulesDefinition;
import org.openremote.manager.shared.security.Tenant;
+import org.openremote.model.AbstractValueTimestampHolder;
import org.openremote.model.Attribute;
import org.openremote.model.Attributes;
-import org.openremote.model.MetaItem;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetMeta;
+import org.openremote.model.asset.AssetQuery;
+import org.openremote.model.asset.AssetUpdate;
import org.openremote.model.util.JsonUtil;
import java.util.*;
@@ -110,79 +111,86 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);
ServerAsset asset = (ServerAsset) persistenceEvent.getEntity();
- // If there are any
+ switch (persistenceEvent.getCause()) {
+ case INSERT:
+ // TODO: Need to populate asset path rather than refetch the entire asset
+ ServerAsset insertedAsset = assetStorageService.find(asset.getId(), true, false);
+
+ // New asset has been created so get attributes that have RULES_FACT meta
+ Attributes addedAttributes = new Attributes(asset.getAttributes());
+
+ Arrays.stream(addedAttributes.get())
+ .filter(Attribute::isRulesFact)
+ .forEach(attribute -> {
+ AssetUpdate update = new AssetUpdate(insertedAsset, attribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ insertFact(update, true);
+ });
+ break;
+ case UPDATE:
+ // TODO: Need to populate asset path rather than refetch the entire asset
+ ServerAsset updatedAsset = assetStorageService.find(asset.getId(), true, false);
+
+ int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
+ if (attributesIndex >= 0) {
+ // Attributes have possibly changed so need to compare old and new state to determine
+ // which facts to retract and which to insert
+ Attributes oldAttributes = new Attributes((JsonObject)persistenceEvent.getPreviousState()[attributesIndex]);
+ Attributes newAttributes = new Attributes((JsonObject)persistenceEvent.getCurrentState()[attributesIndex]);
+
+ List<Attribute> oldFactAttributes = Arrays.stream(oldAttributes.get())
+ .filter(Attribute::isRulesFact)
+ .collect(Collectors.toList());
- switch (persistenceEvent.getCause()) {
- case INSERT:
- // New asset has been created so get attributes that have RULES_FACT meta
- Attributes addedAttributes = new Attributes(asset.getAttributes());
- Arrays.stream(addedAttributes.get())
+ List<Attribute> newFactAttributes = Arrays.stream(newAttributes.get())
.filter(Attribute::isRulesFact)
- .forEach(attribute -> {
- AssetUpdate update = new AssetUpdate(asset, attribute);
+ .collect(Collectors.toList());
+
+ // Compare attributes by JSON value
+ // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
+
+ oldFactAttributes
+ .stream()
+ .filter(oldFactAttribute -> newFactAttributes
+ .stream()
+ .noneMatch(newFactAttribute ->
+ JsonUtil.equals(oldFactAttribute.getJsonObject(), newFactAttribute.getJsonObject(), Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
+ )
+ .forEach(obsoleteFactAttribute -> {
+ AssetUpdate update = new AssetUpdate(updatedAsset, obsoleteFactAttribute);
+ retractFact(update);
+ });
+
+ // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
+ newFactAttributes
+ .stream()
+ .filter(newFactAttribute -> oldFactAttributes
+ .stream()
+ .noneMatch(oldFactAttribute ->
+ JsonUtil.equals(oldFactAttribute.getJsonObject(), newFactAttribute.getJsonObject(), Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))
+ )
+ )
+ .forEach(newFactAttribute -> {
+ AssetUpdate update = new AssetUpdate(updatedAsset, newFactAttribute);
// Set the status to completed already so rules cannot interfere with this initial insert
update.setStatus(AssetUpdate.Status.COMPLETED);
insertFact(update, true);
});
- break;
- case UPDATE:
- int attributesIndex = Arrays.asList(persistenceEvent.getPropertyNames()).indexOf("attributes");
- if (attributesIndex >= 0) {
- // Attributes have possibly changed so need to compare old and new state to determine
- // which facts to retract and which to insert
- Attributes oldAttributes = new Attributes((JsonObject)persistenceEvent.getPreviousState()[attributesIndex]);
- Attributes newAttributes = new Attributes((JsonObject)persistenceEvent.getCurrentState()[attributesIndex]);
-
- List<Attribute> oldFactAttributes = Arrays.stream(oldAttributes.get())
- .filter(Attribute::isRulesFact)
- .collect(Collectors.toList());
-
- List<Attribute> newFactAttributes = Arrays.stream(newAttributes.get())
- .filter(Attribute::isRulesFact)
- .collect(Collectors.toList());
-
- // Compare attributes by JSON value
- // Retract facts for attributes that are in oldFactAttributes but not in newFactAttributes
- oldFactAttributes
- .stream()
- .filter(oldFactAttribute -> newFactAttributes
- .stream()
- .noneMatch(newFactAttribute ->
- JsonUtil.equals(oldFactAttribute.getJsonObject(), newFactAttribute.getJsonObject())
- )
- )
- .forEach(obsoleteFactAttribute -> {
- AssetUpdate update = new AssetUpdate(asset, obsoleteFactAttribute);
- retractFact(update);
- });
-
- // Insert facts for attributes that are in newFactAttributes but not in oldFactAttributes
- newFactAttributes
- .stream()
- .filter(newFactAttribute -> oldFactAttributes
- .stream()
- .noneMatch(oldFactAttribute ->
- JsonUtil.equals(newFactAttribute.getJsonObject(), newFactAttribute.getJsonObject())
- )
- )
- .forEach(newFactAttribute -> {
- AssetUpdate update = new AssetUpdate(asset, newFactAttribute);
- // Set the status to completed already so rules cannot interfere with this initial insert
- insertFact(update, true);
- });
- }
- break;
- case DELETE:
- // Retract any facts that were associated with this asset
- Attributes removedAttributes = new Attributes(asset.getAttributes());
- Arrays.stream(removedAttributes.get())
- .filter(Attribute::isRulesFact)
- .forEach(attribute -> {
- AssetUpdate update = new AssetUpdate(asset, attribute);
- retractFact(update);
- });
- break;
- }
+ }
+ break;
+ case DELETE:
+ // Retract any facts that were associated with this asset
+ Attributes removedAttributes = new Attributes(asset.getAttributes());
+ Arrays.stream(removedAttributes.get())
+ .filter(Attribute::isRulesFact)
+ .forEach(attribute -> {
+ AssetUpdate update = new AssetUpdate(asset, attribute);
+ retractFact(update);
+ });
+ break;
+ }
});
}
@@ -203,8 +211,28 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Deploy asset rules - group by asset ID then tenant and check tenant is enabled
deployAssetRulesDefinitions(rulesStorageService.findEnabledAssetDefinitions());
- // TODO: Look for attributes that contain RULES_FACT meta and push Attribute Events for them
+ // Get all attributes that contain RULES_FACT = true meta and push Attribute Events for them
// into the rule engines.
+ List<ServerAsset> assets = assetStorageService.findAll(
+ new AssetQuery()
+ .attributeMeta(
+ new AssetQuery.AttributeMetaPredicate(
+ AssetMeta.RULES_FACT,
+ new AssetQuery.BooleanPredicate(true))
+ ));
+
+ assets.forEach(asset -> {
+ Attributes attributes = new Attributes(asset.getAttributes());
+ Arrays
+ .stream(attributes.get())
+ .filter(Attribute::isRulesFact)
+ .forEach(attribute -> {
+ AssetUpdate update = new AssetUpdate(asset, attribute);
+ // Set the status to completed already so rules cannot interfere with this initial insert
+ update.setStatus(AssetUpdate.Status.COMPLETED);
+ insertFact(update, true);
+ });
+ });
}
@Override
diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
index 10bb078bb..7c09903f5 100644
--- a/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
+++ b/manager/test/src/test/groovy/org/openremote/test/rules/RulesDeploymentTest.groovy
@@ -4,9 +4,18 @@ import elemental.json.Json
import org.kie.api.event.rule.AfterMatchFiredEvent
import org.kie.api.event.rule.DefaultAgendaEventListener
import org.openremote.manager.server.asset.AssetProcessingService
+import org.openremote.manager.server.asset.ServerAsset
import org.openremote.manager.server.rules.RulesDeployment
import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesStorageService
+import org.openremote.manager.server.asset.AssetStorageService
+import org.openremote.model.Attribute
+import org.openremote.model.Attributes
+import org.openremote.model.AttributeType
+import org.openremote.model.Meta
+import org.openremote.model.MetaItem
+import org.openremote.model.asset.AssetType
+import org.openremote.model.asset.AssetMeta
import org.openremote.manager.server.security.ManagerIdentityService
import org.openremote.manager.server.setup.SetupService
import org.openremote.manager.server.setup.builtin.KeycloakDemoSetup
@@ -28,6 +37,7 @@ import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KE
import static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
+// TODO: Add start/end processing flag to Rules Service that can be used here rather than using pollingConditions initialDelay for testing rules not fired
class RulesDeploymentTest extends Specification implements ManagerContainerTrait {
def customerBRulesDefinitionId
@@ -308,7 +318,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
)
rulesDefinition = rulesStorageService.merge(rulesDefinition)
- then: "the global rules engine should not run and the rule deployment status status should indicate the issue"
+ then: "the global rules engine should not run and the rule deployment status should indicate the issue"
conditions.eventually {
assert rulesService.globalDeployment.allRulesDefinitions.length == 3
assert rulesService.globalDeployment.running == false
@@ -397,6 +407,8 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert apartment3Engine.allRulesDefinitions[0].deploymentStatus == DeploymentStatus.DEPLOYED
}
+ then: "a new fact should be inserted into the engines in scope for the new RULES_FACT attribute which will cause the rules to fire"
+
//TODO: Reinstate the tenant delete test once tenant delete mechanism is finalised
// when: "a tenant is deleted"
// identityService.deleteTenant(accessToken, customerATenant.getRealm())
@@ -442,6 +454,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
def rulesService = container.getService(RulesService.class)
def rulesStorageService = container.getService(RulesStorageService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
RulesDeployment globalEngine, masterEngine, customerAEngine, smartHomeEngine, apartment1Engine, apartment3Engine
List<String> globalEngineFiredRules = []
List<String> masterEngineFiredRules = []
@@ -476,6 +489,11 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
}
//endregion
+ and: "the demo attributes marked with RULES_FACT = true meta should be inserted into the engines"
+ conditions.eventually {
+ globalEngine.facts.size() == 6
+ }
+
//region when: "rule execution loggers are attached to the engines"
when: "rule execution loggers are attached to the engines"
attachRuleExecutionLogger(globalEngine, globalEngineFiredRules)
@@ -573,6 +591,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
customerAEngineFiredRules.clear();
smartHomeEngineFiredRules.clear();
apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
//endregion
//region and: "an attribute event with the same value as current value is pushed into the system"
@@ -627,6 +646,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
customerAEngineFiredRules.clear();
smartHomeEngineFiredRules.clear();
apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
attachRuleExecutionLogger(smartHomeEngine, smartHomeEngineFiredRules)
//endregion
@@ -720,6 +740,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
customerAEngineFiredRules.clear();
smartHomeEngineFiredRules.clear();
apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
attachRuleExecutionLogger(globalEngine, globalEngineFiredRules)
//endregion
@@ -749,6 +770,7 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
customerAEngineFiredRules.clear();
smartHomeEngineFiredRules.clear();
apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
//endregion
//region and: "an apartment 3 living room attribute event occurs"
@@ -773,6 +795,143 @@ class RulesDeploymentTest extends Specification implements ManagerContainerTrait
assert apartment1EngineFiredRules.size() == 0
}
//endregion
+
+ //region when: "the engine counters are reset"
+ when: "the engine counters are reset"
+ globalEngineFiredRules.clear();
+ customerAEngineFiredRules.clear();
+ smartHomeEngineFiredRules.clear();
+ apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
+ //endregion
+
+ and: "a Kitchen room asset is inserted into apartment 1 that contains a RULES_FACT = true meta flag"
+ def apartment1 = assetStorageService.find(managerDemoSetup.apartment1Id)
+ def asset = new ServerAsset(apartment1)
+ asset.setRealmId(keycloakDemoSetup.customerATenant.getId())
+ asset.setType(AssetType.ROOM)
+ asset.setName("Kitchen")
+ Attributes attributes = new Attributes()
+ attributes.put(
+ new Attribute("testString", AttributeType.STRING, Json.create("test"))
+ .setMeta(
+ new Meta()
+ .add(new MetaItem(AssetMeta.RULES_FACT, Json.create(true)))
+ )
+ )
+ asset.setAttributes(attributes.getJsonObject())
+ asset = assetStorageService.merge(asset)
+
+ then: "the engines in scope should have fired the matched rules (Kitchen All should fire)"
+ conditions.eventually {
+ assert globalEngineFiredRules.size() == 2
+ assert globalEngineFiredRules.containsAll(["All", "All changed"])
+ assert customerAEngineFiredRules.size() == 2
+ assert customerAEngineFiredRules.containsAll(["All", "All changed"])
+ assert smartHomeEngineFiredRules.size() == 4
+ assert smartHomeEngineFiredRules.containsAll(["Kitchen All", "Parent Type Residence", "Asset Type Room", "String Attributes"])
+ assert apartment1EngineFiredRules.size() == 2
+ assert apartment1EngineFiredRules.containsAll(["All", "All changed"])
+ assert apartment3EngineFiredRules.size() == 0
+ }
+
+ //region when: "the engine counters are reset"
+ when: "the engine counters are reset"
+ globalEngineFiredRules.clear();
+ customerAEngineFiredRules.clear();
+ smartHomeEngineFiredRules.clear();
+ apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
+ //endregion
+
+ and: "the Kitchen room asset is modified to add a new attribute but RULES_FACT = true meta is not changed"
+ attributes = new Attributes()
+ attributes.put(
+ new Attribute("testString", AttributeType.STRING, Json.create("test"))
+ .setMeta(
+ new Meta()
+ .add(new MetaItem(AssetMeta.RULES_FACT, Json.create(true)))
+ ),
+ new Attribute("testInteger", AttributeType.INTEGER, Json.create(0))
+ );
+ asset.setAttributes(attributes.getJsonObject())
+ def factCount = smartHomeEngine.facts.size()
+ asset = assetStorageService.merge(asset)
+
+ then: "after a few seconds the fact count shouldn't change"
+ new PollingConditions(initialDelay: 3, timeout: 5).eventually {
+ assert smartHomeEngine.facts.size() == factCount
+ }
+
+ when: "the Kitchen room asset is modified to set the RULES_FACT to false"
+ attributes = new Attributes()
+ attributes.put(
+ new Attribute("testString", AttributeType.STRING, Json.create("test"))
+ .setMeta(
+ new Meta()
+ .add(new MetaItem(AssetMeta.RULES_FACT, Json.create(false)))
+ ),
+ new Attribute("testInteger", AttributeType.INTEGER, Json.create(0))
+ );
+ asset.setAttributes(attributes.getJsonObject())
+ factCount = smartHomeEngine.facts.size()
+ asset = assetStorageService.merge(asset)
+
+ then: "after a few seconds the facts should be removed from the rule engines"
+ conditions.eventually {
+ assert smartHomeEngine.facts.size() == factCount - 1
+ }
+
+ when: "the Kitchen room asset is modified to set all attributes to RULES_FACT = true"
+ attributes = new Attributes()
+ attributes.put(
+ new Attribute("testString", AttributeType.STRING, Json.create("test"))
+ .setMeta(
+ new Meta()
+ .add(new MetaItem(AssetMeta.RULES_FACT, Json.create(true)))
+ ),
+ new Attribute("testInteger", AttributeType.INTEGER, Json.create(0))
+ .setMeta(
+ new Meta()
+ .add(new MetaItem(AssetMeta.RULES_FACT, Json.create(true)))
+ )
+ );
+ asset.setAttributes(attributes.getJsonObject())
+ asset = assetStorageService.merge(asset)
+
+ then: "the engines in scope should have fired the matched rules twice (Kitchen All should fire twice Kitchen Integer should have fired once)"
+ conditions.eventually {
+ assert globalEngineFiredRules.size() == 4
+ assert globalEngineFiredRules.containsAll(["All", "All changed"])
+ assert customerAEngineFiredRules.size() == 4
+ assert customerAEngineFiredRules.containsAll(["All", "All changed"])
+ assert smartHomeEngineFiredRules.size() == 9
+ assert smartHomeEngineFiredRules.containsAll(["Kitchen All", "Parent Type Residence", "Asset Type Room", "String Attributes", "Kitchen Integer Attributes"])
+ assert apartment1EngineFiredRules.size() == 4
+ assert apartment1EngineFiredRules.containsAll(["All", "All changed"])
+ assert apartment3EngineFiredRules.size() == 0
+ }
+
+ //region when: "the engine counters are reset"
+ when: "the engine counters are reset"
+ globalEngineFiredRules.clear();
+ customerAEngineFiredRules.clear();
+ smartHomeEngineFiredRules.clear();
+ apartment1EngineFiredRules.clear();
+ apartment3EngineFiredRules.clear();
+ //endregion
+
+ and: "the Kitchen room asset is deleted"
+ factCount = smartHomeEngine.facts.size()
+ asset = assetStorageService.delete(asset.getId())
+
+ then: "after a few seconds the facts should be removed from the rule engines"
+ conditions.eventually {
+ assert smartHomeEngine.facts.size() == factCount - 2
+ }
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
}
def attachRuleExecutionLogger(RulesDeployment ruleEngine, List<String> executedRules) {
diff --git a/manager/test/src/test/resources/org/openremote/test/rules/SmartHomeMatchAllAssetUpdates.drl b/manager/test/src/test/resources/org/openremote/test/rules/SmartHomeMatchAllAssetUpdates.drl
index 2837d85e4..a129f0915 100644
--- a/manager/test/src/test/resources/org/openremote/test/rules/SmartHomeMatchAllAssetUpdates.drl
+++ b/manager/test/src/test/resources/org/openremote/test/rules/SmartHomeMatchAllAssetUpdates.drl
@@ -13,6 +13,20 @@ then
return;
end
+rule "Kitchen All"
+when
+ $e: AssetUpdate(assetName == "Kitchen")
+then
+ return;
+end
+
+rule "Kitchen Integer Attributes"
+when
+ $e: AssetUpdate(assetName == "Kitchen", attributeType == AttributeType.INTEGER)
+then
+ return;
+end
+
rule "Living Room Thermostat"
when
$e: AssetUpdate(assetName == "Livingroom Thermostat")
diff --git a/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java b/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java
index 434b3fc2b..30bc0e911 100644
--- a/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java
+++ b/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java
@@ -29,7 +29,7 @@ import elemental.json.*;
*/
public abstract class AbstractValueTimestampHolder<T extends AbstractValueTimestampHolder> extends AbstractValueHolder<T> {
- protected static final String VALUE_TIMESTAMP_FIELD_NAME = "valueTimestamp";
+ public static final String VALUE_TIMESTAMP_FIELD_NAME = "valueTimestamp";
public AbstractValueTimestampHolder(JsonObject jsonObject) {
super(jsonObject);
diff --git a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
index d725fae34..19126e691 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java
@@ -105,7 +105,7 @@ public class AssetUpdate {
this.assetId = asset.getId();
this.assetName = asset.getName();
if (asset.getPath() == null) {
- throw new IllegalArgumentException("Asset no loaded completely, empty path: " + asset);
+ throw new IllegalArgumentException("Asset not loaded completely, empty path: " + asset);
}
this.assetPath = asset.getPath();
this.assetType = asset.getType();
@@ -291,7 +291,7 @@ public class AssetUpdate {
", attributeName=" + getAttributeName() +
", value=" + getValue().toJson() +
", valueTimestamp=" + getValueTimestamp() +
- ", oldValue=" + getOldValue().toJson() +
+ ", oldValue=" + (oldValue != null ? oldValue.toJson() : "null") +
", oldValueTimestamp=" + getOldValueTimestamp() +
'}';
}
diff --git a/model/src/main/java/org/openremote/model/util/JsonUtil.java b/model/src/main/java/org/openremote/model/util/JsonUtil.java
index caa250b38..c48004492 100644
--- a/model/src/main/java/org/openremote/model/util/JsonUtil.java
+++ b/model/src/main/java/org/openremote/model/util/JsonUtil.java
@@ -23,7 +23,9 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import elemental.json.*;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
public class JsonUtil {
@@ -33,6 +35,44 @@ public class JsonUtil {
return objectMapper.convertValue(props, targetType);
}
+ /**
+ * Compare two {@link JsonObject} instances and optionally exclude certain keys (if object A contains an ignoredKey
+ * but object B doesn't (or vice versa) then the objects can still be considered equal if all non-ignored keys are
+ * present and the values of the non ignored keys are considered equal)
+ */
+ public static boolean equals(JsonObject a, JsonObject b, List<String> ignoreKeys) {
+ if (ignoreKeys == null || ignoreKeys.size() == 0) {
+ return equals(a, b);
+ }
+
+ Map<String, JsonValue> mapA = asMap(a);
+ Map<String, JsonValue> mapB = asMap(b);
+ List<String> mapAKeys = mapA.keySet().stream().filter(k -> !ignoreKeys.contains(k)).collect(Collectors.toList());
+ List<String> mapBKeys = mapB.keySet().stream().filter(k -> !ignoreKeys.contains(k)).collect(Collectors.toList());
+
+ if (mapAKeys.size() != mapBKeys.size()) {
+ return false;
+ }
+
+ if (!mapAKeys.containsAll(mapBKeys)) {
+ return false;
+ }
+
+ for (Map.Entry<String, JsonValue> entry : mapA.entrySet()) {
+ if (ignoreKeys.contains(entry.getKey())) {
+ continue;
+ }
+
+ JsonValue mapAValue = entry.getValue();
+ JsonValue mapBValue = mapB.get(entry.getKey());
+ if (!equals(mapAValue, mapBValue)) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
/**
* Compare two {@link JsonValue} instances by value. Use this
* and {@link #hashCode} instead of {@link JsonValue#jsEquals}.
@@ -45,10 +85,11 @@ public class JsonUtil {
if (b == null)
return false;
if (a instanceof JsonObject && b instanceof JsonObject) {
- Map<String, JsonValue> mapA = asMap((JsonObject) a);
- Map<String, JsonValue> mapB = asMap((JsonObject) b);
+ Map<String, JsonValue> mapA = asMap((JsonObject)a);
+ Map<String, JsonValue> mapB = asMap((JsonObject)b);
if (!mapA.keySet().equals(mapB.keySet()))
return false;
+
for (Map.Entry<String, JsonValue> entry : mapA.entrySet()) {
JsonValue mapAValue = entry.getValue();
JsonValue mapBValue = mapB.get(entry.getKey());