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
Custom JSON equality/hashcode routines
Christian Bauerffc27dc6ac68
diff --git a/container/src/main/java/org/openremote/container/json/JsonUtil.java b/container/src/main/java/org/openremote/container/json/JsonUtil.javadeleted file mode 100644index 9a45aeb96..000000000--- a/container/src/main/java/org/openremote/container/json/JsonUtil.java+++ /dev/null@@ -1,15 +0,0 @@-package org.openremote.container.json;--import com.fasterxml.jackson.databind.ObjectMapper;--import java.util.Map;--public class JsonUtil {-- @SuppressWarnings("unchecked")- public static <T> T convert(ObjectMapper objectMapper, Class<T> targetType, Object object) {- Map<String, Object> props = objectMapper.convertValue(object, Map.class);- return objectMapper.convertValue(props, targetType);- }--}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 aa3b870be..762b08674 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@@ -42,6 +42,7 @@ 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.util.JsonUtil;import java.util.*;import java.util.function.Consumer;@@ -142,14 +143,16 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.filter(Attribute::isRulesFact).collect(Collectors.toList());- // TODO Compare using our own Json equality routine, jsEquals() is broken- // Compare attributes using JsonObject.jsEquals()+ // Compare attributes by JSON value// Retract facts for attributes that are in oldFactAttributes but not in newFactAttributesoldFactAttributes.stream().filter(oldFactAttribute -> newFactAttributes.stream()- .noneMatch(newFactAttribute -> oldFactAttribute.getJsonObject().jsEquals(newFactAttribute.getJsonObject())))+ .noneMatch(newFactAttribute ->+ JsonUtil.equals(oldFactAttribute.getJsonObject(), newFactAttribute.getJsonObject())+ )+ ).forEach(obsoleteFactAttribute -> {AssetUpdate update = new AssetUpdate(serverAsset, obsoleteFactAttribute);retractFact(update);@@ -160,7 +163,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.stream().filter(newFactAttribute -> oldFactAttributes.stream()- .noneMatch(oldFactAttribute -> newFactAttribute.getJsonObject().jsEquals(newFactAttribute.getJsonObject())))+ .noneMatch(oldFactAttribute ->+ JsonUtil.equals(newFactAttribute.getJsonObject(), newFactAttribute.getJsonObject())+ )+ ).forEach(newFactAttribute -> {AssetUpdate update = new AssetUpdate(serverAsset, newFactAttribute);// Set the status to completed already so rules cannot interfere with this initial insertdiff --git a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.javaindex 6e2b47e7e..17bcb04bf 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/ManagerIdentityService.java@@ -43,7 +43,7 @@ import java.util.ArrayList;import java.util.List;import java.util.logging.Logger;-import static org.openremote.container.json.JsonUtil.convert;+import static org.openremote.model.util.JsonUtil.convert;import static org.openremote.model.Constants.*;public class ManagerIdentityService extends IdentityService {diff --git a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.javaindex 40b541403..ed9fb5e10 100644--- a/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/security/UserResourceImpl.java@@ -45,7 +45,7 @@ import java.util.List;import java.util.ResourceBundle;import static javax.ws.rs.core.Response.Status.BAD_REQUEST;-import static org.openremote.container.json.JsonUtil.convert;+import static org.openremote.model.util.JsonUtil.convert;import static org.openremote.manager.shared.validation.ConstraintViolationReport.VIOLATION_EXCEPTION_HEADER;import static org.openremote.model.Constants.*;diff --git a/manager/test/src/test/groovy/org/openremote/test/json/JsonEqualityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/json/JsonEqualityTest.groovynew file mode 100644index 000000000..055b026d8--- /dev/null+++ b/manager/test/src/test/groovy/org/openremote/test/json/JsonEqualityTest.groovy@@ -0,0 +1,161 @@+package org.openremote.test.json++import elemental.json.Json+import elemental.json.JsonArray+import elemental.json.JsonObject+import spock.lang.Specification++import org.openremote.model.util.JsonUtil++class JsonEqualityTest extends Specification {++ def "Compare scalar Json values"() {+ expect:+ JsonUtil.equals(Json.create(true), Json.create(true))+ JsonUtil.hashCode(Json.create(true)) == JsonUtil.hashCode(Json.create(true))++ !JsonUtil.equals(Json.create(false), Json.create(true))+ JsonUtil.hashCode(Json.create(false)) != JsonUtil.hashCode(Json.create(true))++ !JsonUtil.equals(Json.create(true), Json.create(false))+ JsonUtil.hashCode(Json.create(true)) != JsonUtil.hashCode(Json.create(false))++ !JsonUtil.equals(Json.create(123), Json.create(false))+ JsonUtil.hashCode(Json.create(123)) != JsonUtil.hashCode(Json.create(false))++ !JsonUtil.equals(Json.create(0), Json.create(false))+ JsonUtil.hashCode(Json.create(0)) != JsonUtil.hashCode(Json.create(false))++ !JsonUtil.equals(Json.create(1), Json.create(true))+ JsonUtil.hashCode(Json.create(1)) != JsonUtil.hashCode(Json.create(true))++ JsonUtil.equals(Json.createNull(), Json.createNull())+ JsonUtil.hashCode(Json.createNull()) == JsonUtil.hashCode(Json.createNull())++ !JsonUtil.equals(Json.createNull(), Json.create(123))+ JsonUtil.hashCode(Json.createNull()) != JsonUtil.hashCode(Json.create(123))++ !JsonUtil.equals(Json.createNull(), Json.create(false))+ JsonUtil.hashCode(Json.createNull()) != JsonUtil.hashCode(Json.create(false))++ !JsonUtil.equals(Json.createNull(), Json.create(true))+ JsonUtil.hashCode(Json.createNull()) != JsonUtil.hashCode(Json.create(true))++ !JsonUtil.equals(Json.createNull(), Json.create("abc"))+ JsonUtil.hashCode(Json.createNull()) != JsonUtil.hashCode(Json.create("abc"))++ JsonUtil.equals(Json.create(123), Json.create(123))+ JsonUtil.hashCode(Json.create(123)) == JsonUtil.hashCode(Json.create(123))++ !JsonUtil.equals(Json.create(123), Json.create(456))+ JsonUtil.hashCode(Json.create(123)) != JsonUtil.hashCode(Json.create(456))++ !JsonUtil.equals(Json.create(456), Json.create(123))+ JsonUtil.hashCode(Json.create(456)) != JsonUtil.hashCode(Json.create(123))++ !JsonUtil.equals(Json.create(0), Json.create(""))+ JsonUtil.hashCode(Json.create(0)) != JsonUtil.hashCode(Json.create(""))++ JsonUtil.equals(Json.create("abc"), Json.create("abc"))+ JsonUtil.hashCode(Json.create("abc")) == JsonUtil.hashCode(Json.create("abc"))++ !JsonUtil.equals(Json.create("abcd"), Json.create("abc"))+ JsonUtil.hashCode(Json.create("abcd")) != JsonUtil.hashCode(Json.create("abc"))++ !JsonUtil.equals(Json.create("abc"), Json.create("abcd"))+ JsonUtil.hashCode(Json.create("abc")) != JsonUtil.hashCode(Json.create("abcd"))++ !JsonUtil.equals(Json.create("abc"), Json.createNull())+ JsonUtil.hashCode(Json.create("abc")) != JsonUtil.hashCode(Json.createNull())++ !JsonUtil.equals(Json.create("abc"), Json.create(123))+ JsonUtil.hashCode(Json.create("abc")) != JsonUtil.hashCode(Json.create(123))++ !JsonUtil.equals(Json.create(""), Json.create(0))+ JsonUtil.hashCode(Json.create("")) != JsonUtil.hashCode(Json.create(0))+ }++ def "Compare non-scalar Json values"() {++ given:+ JsonObject sampleObject1 = Json.createObject()+ sampleObject1.put("object1A", "O1-AAA")+ sampleObject1.put("object1B", 456)++ JsonObject sampleObject2 = Json.createObject()+ sampleObject2.put("object2A", "O2-AAA")+ sampleObject2.put("object2B", 789)++ JsonArray sampleArray1 = Json.createArray()+ sampleArray1.set(0, "A0")+ sampleArray1.set(1, "A1")+ sampleArray1.set(2, sampleObject1)++ JsonArray sampleArray2 = Json.createArray()+ sampleArray1.set(0, sampleObject1)+ sampleArray1.set(1, "A1")+ sampleArray1.set(2, "A0")++ expect: "Array equality comparisons to be correct"+ JsonUtil.equals(Json.createArray(), Json.createArray())+ JsonUtil.hashCode(Json.createArray()) == JsonUtil.hashCode(Json.createArray())++ !JsonUtil.equals(Json.createArray(), Json.createNull())+ JsonUtil.hashCode(Json.createArray()) != JsonUtil.hashCode(Json.createNull())++ JsonUtil.equals(sampleArray1, sampleArray1)+ JsonUtil.hashCode(sampleArray1) == JsonUtil.hashCode(sampleArray1)++ !JsonUtil.equals(sampleArray2, sampleArray1)+ JsonUtil.hashCode(sampleArray2) != JsonUtil.hashCode(sampleArray1)++ !JsonUtil.equals(sampleArray1, sampleArray2)+ JsonUtil.hashCode(sampleArray1) != JsonUtil.hashCode(sampleArray2)++ and: "Objects with no fields to be equal"+ JsonUtil.equals(null, null)+ JsonUtil.hashCode(null) == JsonUtil.hashCode(null)++ JsonUtil.equals(Json.createObject(), Json.createObject())+ JsonUtil.hashCode(Json.createObject()) == JsonUtil.hashCode(Json.createObject())++ !JsonUtil.equals(null, Json.createObject())+ JsonUtil.hashCode(null) != JsonUtil.hashCode(Json.createObject())++ !JsonUtil.equals(Json.createNull(), Json.createObject())+ JsonUtil.hashCode(Json.createNull()) != JsonUtil.hashCode(Json.createObject())++ !JsonUtil.equals(Json.createArray(), Json.createObject())+ JsonUtil.hashCode(Json.createArray()) != JsonUtil.hashCode(Json.createObject())++ and: "Objects with the same fields to be equal"+ JsonObject sameFields1 = Json.createObject()+ sameFields1.put("fieldA", "AAA")+ sameFields1.put("fieldB", 123)+ sameFields1.put("fieldC", true)+ sameFields1.put("fieldD", sampleArray1)+ JsonObject sameFields2 = Json.createObject()+ sameFields2.put("fieldD", sampleArray1)+ sameFields2.put("fieldC", true)+ sameFields2.put("fieldB", 123)+ sameFields2.put("fieldA", "AAA")+ JsonUtil.equals(sameFields1, sameFields2)+ JsonUtil.hashCode(sameFields1) == JsonUtil.hashCode(sameFields2)++ and: "Objects with the different fields to be not equal"+ JsonObject otherFields1 = Json.createObject()+ otherFields1.put("fieldA", "AAA")+ JsonObject otherFields2 = Json.createObject()+ otherFields2.put("fieldB", 123)+ !JsonUtil.equals(otherFields1, otherFields2)+ JsonUtil.hashCode(otherFields1) != JsonUtil.hashCode(otherFields2)++ and: "Objects with the different field values to be not equal"+ JsonObject differentValues1 = Json.createObject()+ differentValues1.put("fieldA", "AAA")+ JsonObject differentValues2 = Json.createObject()+ differentValues2.put("fieldA", "AAAAA")+ !JsonUtil.equals(differentValues1, differentValues2)+ JsonUtil.hashCode(differentValues1) != JsonUtil.hashCode(differentValues2)+ }+}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AssetUpdate.javaindex 9e1e35107..16ce5dbb9 100644--- a/model/src/main/java/org/openremote/model/asset/AssetUpdate.java+++ b/model/src/main/java/org/openremote/model/asset/AssetUpdate.java@@ -22,6 +22,7 @@ package org.openremote.model.asset;import elemental.json.JsonValue;import org.openremote.model.Attribute;import org.openremote.model.AttributeType;+import org.openremote.model.util.JsonUtil;import java.util.Date;@@ -210,7 +211,7 @@ public class AssetUpdate {}public boolean isValueChanged() {- return !attribute.getValue().jsEquals(oldValue);+ return !JsonUtil.equals(attribute.getValue(), oldValue);}/////////////////////////////////////////////////////////////////@@ -266,18 +267,18 @@ public class AssetUpdate {// TODO Don't use jsEquals(), write own comparison by valuereturn assetId.equals(that.assetId) &&- getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&- getValue().jsEquals(that.getValue()) &&- getValueTimestamp() == that.getValueTimestamp() &&- ((oldValue == null && that.oldValue == null) || (oldValue != null && oldValue.jsEquals(that.oldValue))) &&- oldValueTimestamp == that.oldValueTimestamp;+ getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&+ JsonUtil.equals(getValue(), that.getValue()) &&+ getValueTimestamp() == that.getValueTimestamp() &&+ ((oldValue == null && that.oldValue == null) || (oldValue != null && JsonUtil.equals(oldValue, that.oldValue))) &&+ oldValueTimestamp == that.oldValueTimestamp;}@Overridepublic int hashCode() {- return assetId.hashCode() + getAttributeName().hashCode() + getValue().hashCode()+ return assetId.hashCode() + getAttributeName().hashCode() + JsonUtil.hashCode(getValue())+ Long.hashCode(getValueTimestamp())- + (oldValue != null ? oldValue.hashCode() : 0) + Long.hashCode(oldValueTimestamp);+ + (oldValue != null ? JsonUtil.hashCode(oldValue) : 0) + Long.hashCode(oldValueTimestamp);}@Overridediff --git a/model/src/main/java/org/openremote/model/util/JsonUtil.java b/model/src/main/java/org/openremote/model/util/JsonUtil.javanew file mode 100644index 000000000..caa250b38--- /dev/null+++ b/model/src/main/java/org/openremote/model/util/JsonUtil.java@@ -0,0 +1,130 @@+/*+ * Copyright 2016, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.util;++import com.fasterxml.jackson.databind.ObjectMapper;+import elemental.json.*;++import java.util.HashMap;+import java.util.Map;++public class JsonUtil {++ @SuppressWarnings("unchecked")+ public static <T> T convert(ObjectMapper objectMapper, Class<T> targetType, Object object) {+ Map<String, Object> props = objectMapper.convertValue(object, Map.class);+ return objectMapper.convertValue(props, targetType);+ }++ /**+ * Compare two {@link JsonValue} instances by value. Use this+ * and {@link #hashCode} instead of {@link JsonValue#jsEquals}.+ */+ public static boolean equals(JsonValue a, JsonValue b) {+ if (a == null && b == null)+ return true;+ if (a == null)+ return false;+ 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);+ 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());+ if (!equals(mapAValue, mapBValue)) {+ return false;+ }+ }+ return true;+ } else if (a instanceof JsonArray && b instanceof JsonArray) {+ JsonArray arrayA = (JsonArray) a;+ JsonArray arrayB = (JsonArray) b;+ if (arrayA.length() != arrayB.length())+ return false;+ for (int i = 0; i < arrayA.length(); i++) {+ JsonValue valueA = arrayA.get(i);+ JsonValue valueB = arrayB.get(i);+ if (!equals(valueA, valueB)) {+ return false;+ }+ }+ return true;+ } else if (a instanceof JsonNull && b instanceof JsonNull) {+ return true;+ } else if (a instanceof JsonBoolean && b instanceof JsonBoolean) {+ JsonBoolean booleanA = (JsonBoolean) a;+ JsonBoolean booleanB = (JsonBoolean) b;+ return booleanA.getBoolean() == booleanB.getBoolean();+ } else if (a instanceof JsonNumber && b instanceof JsonNumber) {+ JsonNumber numberA = (JsonNumber) a;+ JsonNumber numberB = (JsonNumber) b;+ return numberA.getNumber() == numberB.getNumber();+ } else if (a instanceof JsonString && b instanceof JsonString) {+ JsonString stringA = (JsonString) a;+ JsonString stringB = (JsonString) b;+ return stringA.getString().equals(stringB.getString());+ }+ return false;+ }++ public static Map<String, JsonValue> asMap(JsonObject jsonObject) {+ Map<String, JsonValue> map = new HashMap<>();+ for (int i = 0; i < jsonObject.keys().length; i++) {+ String key = jsonObject.keys()[i];+ JsonValue value = jsonObject.get(key);+ map.put(key, value);+ }+ return map;+ }++ public static int hashCode(JsonValue jsonValue) {+ int result = 31;+ if (jsonValue == null)+ return result;+ if (jsonValue instanceof JsonObject) {+ result = result * 3;+ Map<String, JsonValue> map = asMap((JsonObject) jsonValue);+ for (Map.Entry<String, JsonValue> entry : map.entrySet()) {+ result = result * 3 + entry.getKey().hashCode();+ result = result * 3 + hashCode(entry.getValue());+ }+ } else if (jsonValue instanceof JsonArray) {+ JsonArray array = (JsonArray) jsonValue;+ result = result * 5;+ for (int i = 0; i < array.length(); i++) {+ result = result * 5 + (i + hashCode(array.get(i)));+ }+ } else if (jsonValue instanceof JsonBoolean) {+ JsonBoolean booleanA = (JsonBoolean) jsonValue;+ result = result * 7 + (booleanA.getBoolean() ? 1 : 0);+ } else if (jsonValue instanceof JsonNumber) {+ JsonNumber number = (JsonNumber) jsonValue;+ result = result * 11 + Double.hashCode(number.getNumber());+ } else if (jsonValue instanceof JsonString) {+ JsonString string = (JsonString) jsonValue;+ result = result * 13 + string.getString().hashCode();+ }+ return result;+ }+}