100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
More MergeOptions in ProtocolAssetService
Christian Bauerb4f44668a607
diff --git a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.javaindex 8813db8c9..e850adfdc 100644--- a/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java+++ b/agent/src/main/java/org/openremote/agent/protocol/ProtocolAssetService.java@@ -20,12 +20,11 @@package org.openremote.agent.protocol;import org.openremote.container.ContainerService;-import org.openremote.model.AbstractValueTimestampHolder;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.attribute.AttributeEvent;-import java.util.Objects;+import java.util.function.Predicate;/*** Interface for protocols to perform limited asset related operations.@@ -38,19 +37,21 @@ public interface ProtocolAssetService extends ContainerService {class MergeOptions {final protected String assignToUserName;- final protected boolean ignoreAttributeValueTimestamps;+ final protected Predicate<String> ignoredAttributeNames;+ final protected Predicate<String> ignoredAttributeKeys;public MergeOptions(String assignToUserName) {- this(assignToUserName, false);+ this(assignToUserName, null, null);}- public MergeOptions(boolean ignoreAttributeValueTimestamps) {- this(null, ignoreAttributeValueTimestamps);+ public MergeOptions(Predicate<String> ignoredAttributeNames, Predicate<String> ignoredAttributeKeys) {+ this(null, ignoredAttributeNames, ignoredAttributeKeys);}- public MergeOptions(String assignToUserName, boolean ignoreAttributeValueTimestamps) {+ public MergeOptions(String assignToUserName, Predicate<String> ignoredAttributeNames, Predicate<String> ignoredAttributeKeys) {this.assignToUserName = assignToUserName;- this.ignoreAttributeValueTimestamps = ignoreAttributeValueTimestamps;+ this.ignoredAttributeNames = ignoredAttributeNames;+ this.ignoredAttributeKeys = ignoredAttributeKeys;}/**@@ -63,26 +64,19 @@ public interface ProtocolAssetService extends ContainerService {}/**- * Compare existing and merged asset state before storing, if only the- * {@link AbstractValueTimestampHolder#getValueTimestamp()}s have changed, don't perform the merge.+ * Compare existing and merged asset state before doing the actual storage merge. If only the+ * ignored attributes have changed, don't perform the merge on storage.*/- public boolean isIgnoreAttributeValueTimestamps() {- return ignoreAttributeValueTimestamps;+ public Predicate<String> getIgnoredAttributeNames() {+ return ignoredAttributeNames;}- @Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;- MergeOptions that = (MergeOptions) o;- return ignoreAttributeValueTimestamps == that.ignoreAttributeValueTimestamps &&- Objects.equals(assignToUserName, that.assignToUserName);- }-- @Override- public int hashCode() {-- return Objects.hash(assignToUserName, ignoreAttributeValueTimestamps);+ /**+ * Compare existing and merged asset state before doing the actual storage merge. If only the+ * ignored keys of any attributes have changed, don't perform the merge on storage.+ */+ public Predicate<String> getIgnoredAttributeKeys() {+ return ignoredAttributeKeys;}}diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex e617caab1..72b9a28da 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java@@ -233,19 +233,23 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Use the unique identifier provided by the protocol, it manages its own identifier spaceupdatedAsset.setId(asset.getId());- if (options != null && options.isIgnoreAttributeValueTimestamps()) {- // Must check manually if asset exists and if any attributes were changed (ignoring different value timestamps)+ if (options != null && (options.getIgnoredAttributeNames() != null || options.getIgnoredAttributeKeys() != null)) {ServerAsset existingAsset = assetStorageService.find(updatedAsset.getId(), true);if (existingAsset != null) {+ // Check if any attributes except the ignored ones were modifiedList<AssetAttribute> existingAttributes = existingAsset.getAttributesList();List<AssetAttribute> updatedAttributes = updatedAsset.getAttributesList();- List<AssetAttribute> addedOrModifiedAttributes =- getAddedOrModifiedAttributes(existingAttributes, updatedAttributes, VALUE_TIMESTAMP_FIELD_NAME).collect(Collectors.toList());- List<AssetAttribute> removedAttributes =- getAddedOrModifiedAttributes(updatedAttributes, existingAttributes, VALUE_TIMESTAMP_FIELD_NAME).collect(Collectors.toList());+ List<AssetAttribute> addedOrModifiedAttributes = getAddedOrModifiedAttributes(+ existingAttributes, updatedAttributes, options.getIgnoredAttributeNames(), options.getIgnoredAttributeKeys()+ ).collect(Collectors.toList());++ List<AssetAttribute> removedAttributes = getAddedOrModifiedAttributes(+ updatedAttributes, existingAttributes, options.getIgnoredAttributeNames(), options.getIgnoredAttributeKeys()+ ).collect(Collectors.toList());+if (addedOrModifiedAttributes.isEmpty() && removedAttributes.isEmpty()) {- LOG.fine("Ignoring merge, protocol-provided asset unchanged (except maybe attribute value timestamps): " + asset);+ LOG.finest("Skipping merge, protocol-provided asset unchanged (excluding ignored attribute names/keys): " + asset);return existingAsset;}}@@ -398,13 +402,13 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Unlink thing attributes that are in old but not in newgetGroupedAgentLinkAttributes(- getAddedOrModifiedAttributes(newAgentLinkedAttributes, oldAgentLinkedAttributes, VALUE_TIMESTAMP_FIELD_NAME),+ getAddedOrModifiedAttributes(newAgentLinkedAttributes, oldAgentLinkedAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)),attribute -> true).forEach(this::unlinkAttributes);// Link thing attributes that are in new but not in oldgetGroupedAgentLinkAttributes(- getAddedOrModifiedAttributes(oldAgentLinkedAttributes, newAgentLinkedAttributes, VALUE_TIMESTAMP_FIELD_NAME),+ getAddedOrModifiedAttributes(oldAgentLinkedAttributes, newAgentLinkedAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)),attribute -> true,attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)).forEach(this::linkAttributes);diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex a02ff8fba..36a3ea1c4 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -300,7 +300,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprocessorLoop:for (Consumer<AssetState> processor : processors) {try {- LOG.fine("==> Processor " + processor + " accepts: " + assetState);+ LOG.finest("==> Processor " + processor + " accepts: " + assetState);processor.accept(assetState);} catch (Throwable t) {LOG.log(Level.SEVERE, "!!! Processor " + processor + " threw an exception whilst consuming: " + assetState, t);@@ -310,13 +310,13 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerswitch (assetState.getProcessingStatus()) {case COMPLETED:- LOG.fine("<== Processor " + processor + " finally handled: " + assetState);+ LOG.finest("<== Processor " + processor + " finally handled: " + assetState);break processorLoop;case ERROR:LOG.log(Level.SEVERE, "<== Processor " + processor + " error: " + assetState, assetState.getError());break processorLoop;default:- LOG.fine("<== Processor " + processor + " done with: " + assetState);+ LOG.finest("<== Processor " + processor + " done with: " + assetState);}}if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.ERROR) {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.javaindex 079346ec3..e0011f136 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@@ -302,7 +302,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons).filter(AssetAttribute::isRuleState).collect(Collectors.toList());// Retract facts for attributes that are obsolete- getAddedOrModifiedAttributes(newRuleStateAttributes, oldRuleStateAttributes, VALUE_TIMESTAMP_FIELD_NAME)+ getAddedOrModifiedAttributes(newRuleStateAttributes, oldRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)).forEach(obsoleteFactAttribute -> {AssetState update = buildAssetState.apply(loadedAsset, obsoleteFactAttribute);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting: " + update);@@ -310,7 +310,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons});// Insert facts for attributes that are new- getAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, VALUE_TIMESTAMP_FIELD_NAME)+ getAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)).forEach(newFactAttribute -> {AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);// Set the status to completed already so rules cannot interfere with this initial insertdiff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex 6ec481e4b..fd3c04672 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -32,6 +32,7 @@ import java.util.Arrays;import java.util.Collection;import java.util.List;import java.util.Optional;+import java.util.function.Predicate;import java.util.stream.Stream;import static org.openremote.model.asset.AssetMeta.*;@@ -411,14 +412,36 @@ public class AssetAttribute extends Attribute {return Optional.of(attribute);}+ /**+ * @return All attributes that exist only in the new list or are different than any attribute in the old list.+ */+ public static Stream<AssetAttribute> getAddedOrModifiedAttributes(List<AssetAttribute> oldAttributes,+ List<AssetAttribute> newAttributes) {+ return getAddedOrModifiedAttributes(oldAttributes, newAttributes, key -> false);+ }++ /**+ * @return All attributes that exist only in the new list or are different than any attribute in the old list.+ */+ public static Stream<AssetAttribute> getAddedOrModifiedAttributes(List<AssetAttribute> oldAttributes,+ List<AssetAttribute> newAttributes,+ Predicate<String> ignoredAttributeKeys) {+ return getAddedOrModifiedAttributes(oldAttributes, newAttributes, name -> false, ignoredAttributeKeys);+ }+/*** @return All attributes that exist only in the new list or are different than any attribute in the old list.*/public static Stream<AssetAttribute> getAddedOrModifiedAttributes(List<AssetAttribute> oldAttributes,List<AssetAttribute> newAttributes,- String... ignoreAttributeKeys) {+ Predicate<String> ignoredAttributeNames,+ Predicate<String> ignoredAttributeKeys) {return newAttributes.stream().filter(newAttribute -> oldAttributes.stream().noneMatch(- oldAttribute -> newAttribute.getObjectValue().equalsIgnoreKeys(oldAttribute.getObjectValue(), ignoreAttributeKeys))+ oldAttribute -> newAttribute.getObjectValue().equalsIgnoreKeys(oldAttribute.getObjectValue(), ignoredAttributeKeys))+ ).filter(addedOrModifiedAttribute ->+ !addedOrModifiedAttribute.getName().isPresent() ||+ ignoredAttributeNames == null ||+ !ignoredAttributeNames.test(addedOrModifiedAttribute.getName().get()));}diff --git a/model/src/main/java/org/openremote/model/value/ObjectValue.java b/model/src/main/java/org/openremote/model/value/ObjectValue.javaindex 0abead749..72082aa4d 100644--- a/model/src/main/java/org/openremote/model/value/ObjectValue.java+++ b/model/src/main/java/org/openremote/model/value/ObjectValue.java@@ -18,6 +18,7 @@ package org.openremote.model.value;import org.openremote.model.util.Pair;import java.util.Optional;+import java.util.function.Predicate;import java.util.stream.Stream;/**@@ -73,7 +74,8 @@ public interface ObjectValue extends Value {ObjectValue deepCopy();/**- * @param ignoreKeys Keys to ignore in comparison.+ *+ * @param ignoreKeyPredicate Ignore given keys in the comparison.*/- boolean equalsIgnoreKeys(ObjectValue that, String... ignoreKeys);+ boolean equalsIgnoreKeys(ObjectValue that, Predicate<String> ignoreKeyPredicate);}diff --git a/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.javaindex b132b4ea1..ef28c61f8 100644--- a/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/ObjectValueImpl.java@@ -19,6 +19,7 @@ import org.openremote.model.util.Pair;import org.openremote.model.value.*;import java.util.*;+import java.util.function.Predicate;import java.util.stream.Collectors;import java.util.stream.Stream;@@ -172,7 +173,7 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {if (!(o instanceof ObjectValueImpl))return false;ObjectValueImpl that = (ObjectValueImpl) o;- return equalsIgnoreKeys(that);+ return equalsIgnoreKeys(that, key -> false);}@Override@@ -184,22 +185,23 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {}@Override- public boolean equalsIgnoreKeys(ObjectValue that, String... ignoreKeys) {+ public boolean equalsIgnoreKeys(ObjectValue that, Predicate<String> ignoreKeyPredicate) {if (!(that instanceof ObjectValueImpl))return false;ObjectValueImpl thatImpl = (ObjectValueImpl) that;- List<String> ignoreKeysList = Arrays.asList(ignoreKeys);-Set<String> thisKeys = this.map.keySet().stream()- .filter(key -> !ignoreKeysList.contains(key)).collect(Collectors.toSet());+ .filter(key -> ignoreKeyPredicate == null || !ignoreKeyPredicate.test(key))+ .collect(Collectors.toSet());Set<String> thatKeys = this.map.keySet().stream()- .filter(key -> !ignoreKeysList.contains(key)).collect(Collectors.toSet());+ .filter(key -> ignoreKeyPredicate == null || !ignoreKeyPredicate.test(key))+ .collect(Collectors.toSet());+if (!thisKeys.equals(thatKeys))return false;for (Map.Entry<String, Value> entry : this.map.entrySet()) {- if (ignoreKeysList.contains(entry.getKey()))+ if (ignoreKeyPredicate != null && ignoreKeyPredicate.test(entry.getKey()))continue;Value mapAValue = entry.getValue();Value mapBValue = thatImpl.map.get(entry.getKey());diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovyindex a25cce4bd..6b0b50765 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy@@ -46,25 +46,25 @@ class AssetModelTest extends Specification {def timestamp = System.currentTimeMillis()def timestamp2 = timestamp + 1000- def attributeA =new AssetAttribute("a", STRING, Values.create("foo"), timestamp)- def attributeB =new AssetAttribute("b", STRING, Values.create("foo"), timestamp2)+ def attributeA = new AssetAttribute("a", STRING, Values.create("foo"), timestamp)+ def attributeB = new AssetAttribute("b", STRING, Values.create("foo"), timestamp2)then: "they should be different"- !attributeA.getObjectValue().equalsIgnoreKeys(attributeB.getObjectValue())+ !attributeA.getObjectValue().equalsIgnoreKeys(attributeB.getObjectValue(), null)and: "if we ignore the timestamp they should be equal"- attributeA.getObjectValue().equalsIgnoreKeys(attributeB.getObjectValue(), VALUE_TIMESTAMP_FIELD_NAME)+ attributeA.getObjectValue().equalsIgnoreKeys(attributeB.getObjectValue(), { key -> key == VALUE_TIMESTAMP_FIELD_NAME })when: "an attribute has no timestamp"- def attributeC = new AssetAttribute("c", STRING, Values.create("foo"))+ def attributeC = new AssetAttribute("c", STRING, Values.create("foo"))then: "it should be different than attributes with a timestamp"- !attributeA.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue())- !attributeB.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue())+ !attributeA.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), null)+ !attributeB.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), null)and: "if we ignore the timestamp they all should be equal"- attributeA.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), VALUE_TIMESTAMP_FIELD_NAME)- attributeB.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), VALUE_TIMESTAMP_FIELD_NAME)+ attributeA.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), { key -> key == VALUE_TIMESTAMP_FIELD_NAME })+ attributeB.getObjectValue().equalsIgnoreKeys(attributeC.getObjectValue(), { key -> key == VALUE_TIMESTAMP_FIELD_NAME })}def "Comparing asset attribute lists"() {@@ -86,6 +86,22 @@ class AssetModelTest extends Specification {addedOrModifiedAttributes.size() == 1addedOrModifiedAttributes[0].name.get() == "a3"+ when: "two lists of asset attributes are compared, ignoring some"+ timestamp = System.currentTimeMillis()+ attributesA = [+ new AssetAttribute("a1", STRING, Values.create("a111"), timestamp),+ new AssetAttribute("a2", STRING, Values.create("a222"), timestamp),+ ]+ attributesB = [+ new AssetAttribute("a1", STRING, Values.create("a111"), timestamp),+ new AssetAttribute("a2", STRING, Values.create("a222"), timestamp),+ new AssetAttribute("a3", STRING, Values.create("a333"), timestamp),+ ]+ addedOrModifiedAttributes = getAddedOrModifiedAttributes(attributesA, attributesB, { name -> name == "a3" }, { key -> false }).collect(Collectors.toList())++ then: "they should be the same"+ addedOrModifiedAttributes.size() == 0+when: "two lists of asset attributes with different value timestamp are compared"timestamp = System.currentTimeMillis()def timestamp2 = timestamp + 1000@@ -117,7 +133,7 @@ class AssetModelTest extends Specification {new AssetAttribute("a1", STRING, Values.create("a111"), timestamp2),new AssetAttribute("a2", STRING, Values.create("a222"), timestamp2),]- addedOrModifiedAttributes = getAddedOrModifiedAttributes(attributesA, attributesB, VALUE_TIMESTAMP_FIELD_NAME).collect(Collectors.toList())+ addedOrModifiedAttributes = getAddedOrModifiedAttributes(attributesA, attributesB, { key -> key == VALUE_TIMESTAMP_FIELD_NAME }).collect(Collectors.toList())then: "they should be the same"addedOrModifiedAttributes.size() == 0