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
Migration to new value model complete
Christian Bauer9280fd069e90
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.javaindex ff33065fb..42253d904 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java@@ -27,9 +27,9 @@ import org.openremote.container.message.MessageBrokerContext;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.timer.TimerService;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;import org.openremote.model.asset.AssetAttribute;import java.util.Collection;@@ -145,12 +145,14 @@ public abstract class AbstractProtocol implements Protocol {protected void sendAttributeEvent(AttributeState state) {AttributeEvent event = new AttributeEvent(state, timerService.getCurrentTimeMillis());- LOG.info("Sending attribute event: " + event);+ LOG.info("Sending on sensor queue: " + event);producerTemplate.sendBodyAndHeader(SENSOR_QUEUE, event, "isSensorUpdate", false);}protected void onSensorUpdate(AttributeState state, long timestamp) {- producerTemplate.sendBody(SENSOR_QUEUE, new AttributeEvent(state, timestamp));+ AttributeEvent event = new AttributeEvent(state, timestamp);+ LOG.fine("Sending on sensor queue: " + event);+ producerTemplate.sendBody(SENSOR_QUEUE, event);}protected void onSensorUpdate(AttributeState state) {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.javaindex e586a13dd..c220d09ad 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java@@ -20,7 +20,7 @@package org.openremote.agent3.protocol;import org.openremote.container.ContainerService;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.Constants;import org.openremote.model.asset.AssetAttribute;diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.javaindex 33a24be51..adbefec33 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroAction.java@@ -19,12 +19,12 @@*/package org.openremote.agent3.protocol.macro;-import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.AttributeState;-import org.openremote.model.MetaItem;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Objects;import java.util.Optional;@@ -55,7 +55,7 @@ public class MacroAction {}public void setAttributeState(AttributeState attributeState) {- this.attributeState = attributeState;+ this.attributeState = Objects.requireNonNull(attributeState);}public int getDelayMilliseconds() {@@ -66,15 +66,15 @@ public class MacroAction {this.delayMilliseconds = Math.max(0, delayMilliseconds);}- public JsonValue toJsonValue() {- JsonObject jsonObect = Json.createObject();- jsonObect.put("attributeState", attributeState != null ? attributeState.toJsonValue() : Json.create(null));- jsonObect.put("delay", Json.create(delayMilliseconds));- return jsonObect;+ public ObjectValue toObjectValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("attributeState", attributeState.toObjectValue());+ objectValue.put("delay", Values.create(delayMilliseconds));+ return objectValue;}public MetaItem toMetaItem() {- return new MetaItem(META_MACRO_ACTION, toJsonValue());+ return new MetaItem(META_MACRO_ACTION, toObjectValue());}@Override@@ -85,16 +85,13 @@ public class MacroAction {'}';}- public static Optional<MacroAction> fromJsonValue(JsonValue jsonValue) {- return JsonUtil.asJsonObject(jsonValue)- .map(jsonObject -> {-- Optional<AttributeState> state = AttributeState.fromJsonValue(jsonObject.get("attributeState"));- Optional<Integer> delay = JsonUtil.asInteger((JsonValue)jsonObject.get("delay"));-- return state- .map(attributeState -> new MacroAction(attributeState, delay.orElse(0)))- .orElse(null);- });+ public static Optional<MacroAction> fromValue(Value value) {+ return Values.getObject(value)+ .map(objectValue -> new Pair<>(+ AttributeState.fromValue(objectValue.get("attributeState").get()),+ objectValue.getNumber("delay").orElse(0d)+ )+ ).filter(pair -> pair.key.isPresent())+ .map(pair -> new MacroAction(pair.key.get(), pair.value.intValue()));}}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.javaindex 231df494d..3f743fddf 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroConfiguration.java@@ -30,7 +30,7 @@ import java.util.stream.Collectors;import java.util.stream.Stream;import static org.openremote.model.Constants.ASSET_META_NAMESPACE;-import static org.openremote.model.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;import static org.openremote.model.asset.agent.ProtocolConfiguration.getProtocolName;import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;@@ -70,7 +70,7 @@ final public class MacroConfiguration {.getMetaStream().filter(isMetaNameEqualTo(META_MACRO_ACTION)).map(metaItem -> metaItem.getValue().orElse(null))- .map(MacroAction::fromJsonValue)+ .map(MacroAction::fromValue).filter(Optional::isPresent).map(Optional::get);}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.javaindex affba4091..7f0627e08 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java@@ -19,14 +19,14 @@*/package org.openremote.agent3.protocol.macro;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeExecuteStatus;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeExecuteStatus;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.*;import java.util.concurrent.ScheduledFuture;@@ -67,7 +67,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asJsonValue()));+ onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asValue()));run();}@@ -80,7 +80,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asJsonValue()));+ onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asValue()));}private void run() {@@ -112,7 +112,7 @@ public class MacroProtocol extends AbstractProtocol {}// Update the command Status of this attribute- onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.COMPLETED.asJsonValue()));+ onSensorUpdate(new AttributeState(attributeRef, AttributeExecuteStatus.COMPLETED.asValue()));return;}@@ -138,8 +138,11 @@ public class MacroProtocol extends AbstractProtocol {protected void sendToActuator(AttributeEvent event) {// Asset processing service has already done sanity checks// Can be valid to pass null to- Optional<JsonValue> value = event.getValue();- AttributeExecuteStatus status = AttributeExecuteStatus.fromString(value.flatMap(JsonUtil::asString).orElse(null));+ Optional<Value> value = event.getValue();+ AttributeExecuteStatus status = event.getValue()+ .flatMap(Values::getString)+ .flatMap(AttributeExecuteStatus::fromString)+ .orElse(null);AttributeRef attributeRef = event.getAttributeRef();// Check if it's a cancellation requestdiff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.javaindex d73dff688..be26ba1e5 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java@@ -19,14 +19,14 @@*/package org.openremote.agent3.protocol.simulator;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.agent3.protocol.simulator.element.*;import org.openremote.model.AbstractValueHolder;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;import java.util.HashMap;import java.util.Locale;@@ -155,10 +155,12 @@ public class SimulatorProtocol extends AbstractProtocol {}SimulatorElement element = createElement(elementType, attribute);- try {- element.setState(attribute.getValue());- } catch (IllegalArgumentException ex) {- throw new RuntimeException("Error setting initial state of: " + attribute, ex);+ if (attribute.getValue().isPresent()) {+ try {+ element.setState(attribute.getValue().get());+ } catch (IllegalArgumentException ex) {+ throw new RuntimeException("Error setting initial state of: " + attribute, ex);+ }}LOG.info("Putting element '" + element + "' for: " + attribute);@@ -220,7 +222,7 @@ public class SimulatorProtocol extends AbstractProtocol {* Call this to simulate a sensor update after the specified delay (it uses the last value supplied from send to actuator).*/public void updateSensor(AttributeRef attributeRef, int updateSensorDelayMilliseconds) {- JsonValue value = getState(attributeRef);+ Value value = getState(attributeRef);final AttributeState state = new AttributeState(attributeRef, value);if (updateSensorDelayMilliseconds <= 0) {@@ -233,14 +235,14 @@ public class SimulatorProtocol extends AbstractProtocol {/*** Call this to simulate a send to actuator.*/- public void putState(String entityId, String attributeName, JsonValue value) {+ public void putState(String entityId, String attributeName, Value value) {putState(new AttributeState(new AttributeRef(entityId, attributeName), value));}/*** Call this to simulate a send to actuator.*/- public void putState(AttributeRef attributeRef, JsonValue value) {+ public void putState(AttributeRef attributeRef, Value value) {putState(new AttributeState(attributeRef, value));}@@ -279,7 +281,7 @@ public class SimulatorProtocol extends AbstractProtocol {throw new IllegalArgumentException("No simulated element for: " + attributeRef);}- element.setState(attributeState.getValue());+ element.setState(attributeState.getCurrentValue().orElse(null));}if (instance.getMode() != Mode.MANUAL) {@@ -290,14 +292,14 @@ public class SimulatorProtocol extends AbstractProtocol {/*** Call this to get the current value of an attribute.*/- public JsonValue getState(String entityId, String attributeName) {+ public Value getState(String entityId, String attributeName) {return getState(new AttributeRef(entityId, attributeName));}/*** Call this to get the current value of an attribute.*/- public JsonValue getState(AttributeRef attributeRef) {+ public Value getState(AttributeRef attributeRef) {synchronized (elements) {SimulatorElement element = elements.get(attributeRef);if (element == null)@@ -328,6 +330,6 @@ public class SimulatorProtocol extends AbstractProtocol {public static Optional<String> getElementType(AssetAttribute attribute) {returnattribute.getMetaItem(SIMULATOR_ELEMENT)- .flatMap(AbstractValueHolder::getValueAsString);+ .flatMap(AbstractValueHolder::getValueAsString);}}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.javaindex f958c3c9e..8303175a8 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/ColorSimulatorElement.java@@ -19,13 +19,13 @@*/package org.openremote.agent3.protocol.simulator.element;-import org.openremote.model.AttributeType;+import org.openremote.model.attribute.AttributeType;public class ColorSimulatorElement extends SimulatorElement {public static final String ELEMENT_NAME = "color";public ColorSimulatorElement() {- super(AttributeType.INTEGER_ARRAY);+ super(AttributeType.COLOR_RGB);}}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.javaindex 4b737e3c8..0ce1ded67 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/DecimalSimulatorElement.java@@ -19,7 +19,7 @@*/package org.openremote.agent3.protocol.simulator.element;-import org.openremote.model.AttributeType;+import org.openremote.model.attribute.AttributeType;public class DecimalSimulatorElement extends SimulatorElement {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.javaindex f16afbe9b..fa1b19718 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/IntegerSimulatorElement.java@@ -19,10 +19,9 @@*/package org.openremote.agent3.protocol.simulator.element;-import elemental.json.JsonValue;-import org.openremote.model.AttributeType;--import javax.persistence.criteria.CriteriaBuilder;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;public class IntegerSimulatorElement extends SimulatorElement {@@ -51,12 +50,12 @@ public class IntegerSimulatorElement extends SimulatorElement {}@Override- protected boolean isValid(JsonValue value) {+ protected boolean isValid(Value value) {boolean valid = super.isValid(value);return valid && (value == null || (- (getMin() == null || value.asNumber() >= getMin())- && (getMax() == null || value.asNumber() <= getMax())+ (getMin() == null || Values.getNumber(value).filter(v -> v >= getMin()).isPresent())+ && (getMax() == null || Values.getNumber(value).filter(v -> v <= getMax()).isPresent())));}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.javaindex 6891f433e..c11e06365 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SimulatorElement.java@@ -19,48 +19,38 @@*/package org.openremote.agent3.protocol.simulator.element;-import elemental.json.JsonValue;-import org.openremote.model.AttributeType;--import java.util.Optional;--import static org.openremote.model.util.JsonUtil.replaceJsonNull;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.value.Value;public abstract class SimulatorElement<T> {final protected AttributeType expectedType;- protected JsonValue state = null;+ protected Value state = null;public SimulatorElement(AttributeType expectedType) {this.expectedType = expectedType;}- public JsonValue getState() {+ public Value getState() {return state;}- public void setState(Optional<JsonValue> state) {- // This is only used server side so JsonValue optional issue isn't a problem- state- .map(st -> {- st = replaceJsonNull(st);- if (!isValid(st)) {- throw new IllegalArgumentException(- "Invalid state, expected JSON type '" + expectedType + "' but got '" + st.getType() + "' on: " + this- );- }- this.state = st;- return st;- })- .orElseGet(() -> {- this.state = null;- return null;- });+ public void setState(Value value) {+ if (value != null) {+ if (!isValid(value)) {+ throw new IllegalArgumentException(+ "Invalid state, expected JSON type '" + expectedType + "' but got '" + value.getType() + "' on: " + this+ );+ }+ this.state = value;+ } else {+ this.state = null;+ }}- protected boolean isValid(JsonValue value) {- return value == null || value.getType() == expectedType.getJsonType();+ protected boolean isValid(Value value) {+ return value == null || value.getType() == expectedType.getValueType();}@Overridediff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.javaindex 6928a18bc..e81c4e5d7 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/element/SwitchSimulatorElement.java@@ -19,7 +19,7 @@*/package org.openremote.agent3.protocol.simulator.element;-import org.openremote.model.AttributeType;+import org.openremote.model.attribute.AttributeType;public class SwitchSimulatorElement extends SimulatorElement {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.javaindex 4473e4581..abf6bcb52 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/AbstractTriggerHandler.java@@ -19,12 +19,12 @@*/package org.openremote.agent3.protocol.trigger;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.container.Container;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;public abstract class AbstractTriggerHandler {@@ -32,11 +32,11 @@ public abstract class AbstractTriggerHandler {protected abstract String getName();- protected abstract boolean isValidValue(JsonValue triggerValue);+ protected abstract boolean isValidValue(Value triggerValue);- protected abstract void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled);+ protected abstract void registerTrigger(AttributeRef triggerRef, Value value, boolean isEnabled);- protected abstract void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled);+ protected abstract void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled);protected abstract void unregisterTrigger(AttributeRef triggerRef);diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.javaindex fc810025d..8047cce2b 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerConfiguration.java@@ -19,22 +19,21 @@*/package org.openremote.agent3.protocol.trigger;-import elemental.json.Json;-import elemental.json.JsonValue;import org.openremote.model.AbstractValueHolder;-import org.openremote.model.AttributeState;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Optional;import java.util.function.Function;import static org.openremote.agent3.protocol.trigger.TriggerProtocol.*;-import static org.openremote.agent3.protocol.trigger.TriggerType.toJsonValue;-import static org.openremote.model.AttributeType.STRING;-import static org.openremote.model.MetaItem.isMetaNameEqualTo;-import static org.openremote.model.MetaItem.replaceMetaByName;+import static org.openremote.agent3.protocol.trigger.TriggerType.toValue;import static org.openremote.model.asset.agent.ProtocolConfiguration.getProtocolName;+import static org.openremote.model.attribute.AttributeType.STRING;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.attribute.MetaItem.replaceMetaByName;/*** Utility functions for working with trigger attributes for the {@link TriggerProtocol}@@ -46,8 +45,8 @@ final public class TriggerConfiguration {public static Function<AssetAttribute, AssetAttribute> initTriggerConfiguration() {return attribute -> {- attribute.setType(STRING);- attribute.setValue(Json.create(TriggerProtocol.PROTOCOL_NAME));+ attribute.setTypeAndClearValue(STRING);+ attribute.setValue(Values.create(TriggerProtocol.PROTOCOL_NAME));return attribute;};}@@ -85,7 +84,7 @@ final public class TriggerConfiguration {if (attribute == null)return;- replaceMetaByName(attribute.getMeta(), META_TRIGGER_TYPE, toJsonValue(triggerType));+ replaceMetaByName(attribute.getMeta(), META_TRIGGER_TYPE, toValue(triggerType));}public static Optional<AbstractTriggerHandler> getTriggerTypeHandler(AssetAttribute attribute) {@@ -98,7 +97,7 @@ final public class TriggerConfiguration {}public static boolean isTriggerTypeAndValueValid(AssetAttribute attribute) {- Optional<JsonValue> triggerValue = getTriggerValue(attribute);+ Optional<Value> triggerValue = getTriggerValue(attribute);Optional<AbstractTriggerHandler> handler = getTriggerTypeHandler(attribute);return triggerValue.isPresent() && handler.map(h ->@@ -109,17 +108,17 @@ final public class TriggerConfiguration {.orElse(false);}- public static boolean isTriggerValueValid(AbstractTriggerHandler handler, JsonValue value) {+ public static boolean isTriggerValueValid(AbstractTriggerHandler handler, Value value) {return handler != null && value != null && handler.isValidValue(value);}- public static Optional<JsonValue> getTriggerValue(AssetAttribute attribute) {+ public static Optional<Value> getTriggerValue(AssetAttribute attribute) {return attribute == null ? Optional.empty() : attribute.getMetaItem(META_TRIGGER_VALUE).flatMap(AbstractValueHolder::getValue);}- public static void setTriggerValue(AssetAttribute attribute, JsonValue value) {+ public static void setTriggerValue(AssetAttribute attribute, Value value) {if (attribute == null)return;@@ -140,15 +139,14 @@ final public class TriggerConfiguration {public static Optional<AttributeState> getTriggerAction(AssetAttribute attribute) {return attribute == null ? Optional.empty() : attribute.getMetaItem(META_TRIGGER_ACTION)- .flatMap(AbstractValueHolder::getValueAsJsonObject)- .flatMap(AttributeState::fromJsonValue);+ .flatMap(AbstractValueHolder::getValueAsObject)+ .flatMap(AttributeState::fromValue);}public static void setTriggerAction(AssetAttribute attribute, AttributeState action) {if (attribute == null)return;-- replaceMetaByName(attribute.getMeta(), META_TRIGGER_ACTION, AttributeState.toJsonValue(action));+ replaceMetaByName(attribute.getMeta(), META_TRIGGER_ACTION, action.toObjectValue());}public static void removeTrigger(AssetAttribute attribute) {@@ -161,15 +159,7 @@ final public class TriggerConfiguration {isMetaNameEqualTo(META_TRIGGER_TYPE).or(isMetaNameEqualTo(META_TRIGGER_VALUE)).or(isMetaNameEqualTo(META_TRIGGER_ACTION))- );- }-- public static boolean hasTriggerProperty(AssetAttribute attribute) {- return attribute != null && attribute- .getMetaItem(META_TRIGGER_PROPERTY)- .flatMap(AbstractValueHolder::getValue)- .map(JsonUtil::isOfTypeString)- .orElse(false);+ );}public static Optional<String> getTriggerProperty(AssetAttribute attribute) {diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.javaindex 5135209e2..f20f07a98 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerProtocol.java@@ -19,14 +19,14 @@*/package org.openremote.agent3.protocol.trigger;-import elemental.json.Json;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.AbstractProtocol;import org.openremote.container.Container;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.HashMap;import java.util.Map;@@ -38,26 +38,24 @@ import static org.openremote.model.Constants.ASSET_META_NAMESPACE;import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;import static org.openremote.model.asset.AssetMeta.ENABLED;import static org.openremote.model.asset.agent.AgentLink.getAgentLink;-import static org.openremote.model.util.JsonUtil.asBoolean;/*** This protocol can be used to trigger {@link AttributeEvent} using a trigger type:- *+ * <p>* A trigger is defined by creating a {@link TriggerConfiguration} attribute on an* agent. A trigger consists of:- *+ * <p>* Trigger Type {@link TriggerType}- * Trigger Value ({@link TriggerType#TIME} = CRON EXPRESSION, {@link TriggerType#ATTRIBUTE} = {@link org.openremote.model.AttributeRef})- * Trigger Action {@link org.openremote.model.AttributeState} that should be sent when triggered- *+ * Trigger Value ({@link TriggerType#TIME} = CRON EXPRESSION, {@link TriggerType#ATTRIBUTE} = {@link AttributeRef})+ * Trigger Action {@link AttributeState} that should be sent when triggered+ * <p>* {@link AssetAttribute}s can link to time triggers to read/write the trigger time and/or enable/disable* the trigger.- *+ * <p>* The {@link #META_TRIGGER_PROPERTY} meta should be used on linked attributes to indicate what property* of the trigger the attribute should read/write. The content of the meta should be a string that is* specific to the trigger type handler. The only globally recognised value is {@link #TRIGGER_PROPERTY_ENABLED}* which reads/writes the trigger's {@link org.openremote.model.asset.AssetMeta#ENABLED} meta item.- **/public class TriggerProtocol extends AbstractProtocol {@@ -129,17 +127,19 @@ public class TriggerProtocol extends AbstractProtocol {.ifPresent(propertyName -> {if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {// Check that event contains a boolean- asBoolean(event.getValue())- .ifPresent(enabled ->- // We update the trigger configuration and wait for it to come back through the processing- // chain as an update to the protocol configuration in the agent service- updateTriggerMeta(new AttributeState(triggerRef, Json.create(enabled)), ENABLED.getUrn())+ event.getValue()+ .flatMap(Values::getBoolean)+ .ifPresent(enabled -> {+ // We update the trigger configuration and wait for it to come back through the processing+ // chain as an update to the protocol configuration in the agent service+ updateTriggerMeta(new AttributeState(triggerRef, Values.create(enabled)), ENABLED.getUrn());+ });} else {synchronized (attributeTriggerHandlerMap) {AbstractTriggerHandler handler = attributeTriggerHandlerMap.get(event.getAttributeRef());if (handler != null) {- LOG.info("Passing attribute write request to trigger handler '" +handler.getName() + "'");+ LOG.info("Passing attribute write request to trigger handler '" + handler.getName() + "'");handler.processAttributeWrite(event.getAttributeRef(), triggerRef, propertyName, event);}}@@ -167,7 +167,7 @@ public class TriggerProtocol extends AbstractProtocol {// Register the trigger with its handlerTriggerType type = getTriggerType(protocolConfiguration).get();AbstractTriggerHandler handler = getTriggerTypeHandler(protocolConfiguration).get();- JsonValue value = getTriggerValue(protocolConfiguration).get();+ Value value = getTriggerValue(protocolConfiguration).get();handler.registerTrigger(protocolConfigRef, value, protocolConfiguration.isEnabled());return protocolConfiguration;@@ -239,7 +239,7 @@ public class TriggerProtocol extends AbstractProtocol {AttributeRef attributeRef = attribute.getReferenceOrThrow();if (TRIGGER_PROPERTY_ENABLED.equals(propertyName)) {- AttributeState state = new AttributeState(attributeRef, Json.create(triggerConfiguration.isEnabled()));+ AttributeState state = new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled()));// Push current value of enabled status into the attributeLOG.info("Updating attribute value with trigger enabled status: " + state);onSensorUpdate(state);@@ -267,7 +267,7 @@ public class TriggerProtocol extends AbstractProtocol {LOG.info("Registering attribute for trigger enabled status: " + attributeRef);// Push current value of enabled status into the attribute- onSensorUpdate(new AttributeState(attributeRef, Json.create(triggerConfiguration.isEnabled())));+ onSensorUpdate(new AttributeState(attributeRef, Values.create(triggerConfiguration.isEnabled())));} else {LOG.info("Updating attribute '" + attributeRef + "' on trigger handler '" + handler.getName() + "'");handler.updateAttribute(attributeRef, triggerConfiguration.getReferenceOrThrow(), propertyName);@@ -326,7 +326,7 @@ public class TriggerProtocol extends AbstractProtocol {synchronized (protocolConfigMap) {Optional.ofNullable(protocolConfigMap.get(state.getAttributeRef())).ifPresent(triggerConfiguration ->- LOG.info("Updating trigger configuration")+ LOG.info("Updating trigger configuration")// Set the trigger Configuration meta and update the agent//replaceMetaByName(triggerConfiguration, metaName, state.getValue());//Asset agent = assetStorageService.get(triggerConfiguration.getAssetId(), true);diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.javaindex e7942a022..6c55c79d3 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/TriggerType.java@@ -19,24 +19,24 @@*/package org.openremote.agent3.protocol.trigger;-import elemental.json.Json;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.trigger.attribute.AttributeTriggerHandler;import org.openremote.agent3.protocol.trigger.time.TimeTriggerHandler;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Objects;import java.util.Optional;-import static org.openremote.model.util.JsonUtil.asString;-public enum TriggerType implements TriggerHandlerProducer {+/*** For cron based triggers*/TIME(new TimeTriggerHandler()),/**- * For {@link org.openremote.model.AttributeEvent} triggers+ * For {@link AttributeEvent} triggers*/ATTRIBUTE(new AttributeTriggerHandler());@@ -66,13 +66,11 @@ public enum TriggerType implements TriggerHandlerProducer {return triggerType.toString();}- public static TriggerType fromJsonValue(JsonValue value) {- return asString(value)- .flatMap(TriggerType::fromString)- .orElse(null);+ public static Optional<TriggerType> fromValue(Value value) {+ return Values.getString(value).flatMap(TriggerType::fromString);}- public static JsonValue toJsonValue(TriggerType triggerType) {- return Json.create(toString(triggerType));+ public static Value toValue(TriggerType triggerType) {+ return Values.create(toString(triggerType));}}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.javaindex b565cd49a..de03a7a98 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/attribute/AttributeTriggerHandler.java@@ -19,12 +19,13 @@*/package org.openremote.agent3.protocol.trigger.attribute;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.value.Value;public class AttributeTriggerHandler extends AbstractTriggerHandler {+public static final String ATTRIBUTE_TRIGGER_HANDLER_NAME = "Attribute Event Trigger Handler";@Override@@ -33,17 +34,17 @@ public class AttributeTriggerHandler extends AbstractTriggerHandler {}@Override- protected boolean isValidValue(JsonValue triggerValue) {+ protected boolean isValidValue(Value triggerValue) {return false;}@Override- protected void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {+ protected void registerTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {}@Override- protected void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {+ protected void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {}diff --git a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.javaindex aaf9a99e9..7153086ba 100644--- a/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java+++ b/agent/src/main/java/org/openremote/agent3/protocol/trigger/time/TimeTriggerHandler.java@@ -19,13 +19,13 @@*/package org.openremote.agent3.protocol.trigger.time;-import elemental.json.Json;-import elemental.json.JsonValue;import org.openremote.agent3.protocol.trigger.AbstractTriggerHandler;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;import org.openremote.model.util.TextUtil;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import org.quartz.CronExpression;import javax.ws.rs.NotSupportedException;@@ -37,10 +37,10 @@ import java.util.logging.Logger;import static java.util.logging.Level.FINER;import static org.openremote.agent3.protocol.trigger.time.CronExpressionParser.parseNumberExpression;-import static org.openremote.model.util.JsonUtil.asString;import static org.openremote.model.util.TextUtil.isNullOrEmpty;public class TimeTriggerHandler extends AbstractTriggerHandler {+private static final Logger LOG = Logger.getLogger(TimeTriggerHandler.class.getName());public static final String TIME_TRIGGER_HANDLER_NAME = "Time Trigger Handler";protected final Map<AttributeRef, CronExpressionParser> cronExpressionMap = new HashMap<>();@@ -52,13 +52,13 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {}@Override- protected boolean isValidValue(JsonValue triggerValue) {- return isValidCronExpression(asString(triggerValue).orElse(null));+ protected boolean isValidValue(Value triggerValue) {+ return Values.getString(triggerValue).filter(TimeTriggerHandler::isValidCronExpression).isPresent();}@Override- protected void registerTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {- Optional<String> expression = asString(value).flatMap(TextUtil::asNonNullAndNonEmpty);+ protected void registerTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {+ Optional<String> expression = Values.getString(value).flatMap(TextUtil::asNonNullAndNonEmpty);CronExpressionParser cronExpressionParser = null;if (expression.isPresent()) {@@ -84,7 +84,7 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {}@Override- protected void updateTrigger(AttributeRef triggerRef, JsonValue value, boolean isEnabled) {+ protected void updateTrigger(AttributeRef triggerRef, Value value, boolean isEnabled) {unregisterTrigger(triggerRef);registerTrigger(triggerRef, value, isEnabled);}@@ -111,11 +111,11 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {switch (property) {case CRON_EXPRESSION:// Pass the entire cron expression through to the attribute- updateAttributeValue(new AttributeState(attributeRef, Json.create(parser.buildCronExpression())));+ updateAttributeValue(new AttributeState(attributeRef, Values.create(parser.buildCronExpression())));break;case TIME:// Pass the 24h formatted time- updateAttributeValue(new AttributeState(attributeRef, Json.create(parser.getFormattedTime())));+ updateAttributeValue(new AttributeState(attributeRef, Values.create(parser.getFormattedTime())));break;}}@@ -140,7 +140,7 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {// Don't remove or alter any running trigger just push update back through the system// and wait for add, remove or update trigger call- Optional<String> writeValue = asString(event.getValue()).flatMap(TextUtil::asNonNullAndNonEmpty);+ Optional<String> writeValue = event.getValue().flatMap(Values::getString).flatMap(TextUtil::asNonNullAndNonEmpty);if (!writeValue.isPresent()) {LOG.warning("Send to actuator value for time trigger must be a non empty string");@@ -153,7 +153,7 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {case CRON_EXPRESSION:// Allow writing invalid cron expressions; mean that the trigger will stop working// but that is handled gracefully- updateTriggerValue(new AttributeState(triggerRef, Json.create(value)));+ updateTriggerValue(new AttributeState(triggerRef, Values.create(value)));break;case TIME:CronExpressionParser parser = getCronExpressionParser(triggerRef);@@ -176,7 +176,7 @@ public class TimeTriggerHandler extends AbstractTriggerHandler {}parser.setTime(hours, minutes, seconds);- updateTriggerValue(new AttributeState(triggerRef, Json.create(parser.buildCronExpression())));+ updateTriggerValue(new AttributeState(triggerRef, Values.create(parser.buildCronExpression())));break;default:throw new NotSupportedException("Unsupported trigger property");diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.javaindex 04a9e5499..7fd14cbcb 100644--- a/container/src/main/java/org/openremote/container/Container.java+++ b/container/src/main/java/org/openremote/container/Container.java@@ -25,7 +25,6 @@ import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.DeserializationFeature;import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;-import org.openremote.container.json.ElementalJsonModule;import org.openremote.container.concurrent.ContainerThreads;import org.openremote.container.json.ModelValueModule;import org.openremote.container.util.LogUtil;@@ -69,8 +68,7 @@ public class Container {.setVisibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.IS_GETTER, JsonAutoDetect.Visibility.NONE).setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE)- .registerModule(new ModelValueModule())- .registerModule(new ElementalJsonModule());+ .registerModule(new ModelValueModule());protected final Map<String, String> config = new HashMap<>();protected final boolean devMode;diff --git a/container/src/main/java/org/openremote/container/json/ElementalJsonModule.java b/container/src/main/java/org/openremote/container/json/ElementalJsonModule.javadeleted file mode 100644index fec3b295a..000000000--- a/container/src/main/java/org/openremote/container/json/ElementalJsonModule.java+++ /dev/null@@ -1,74 +0,0 @@-/*- * 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.container.json;--import com.fasterxml.jackson.core.JsonGenerator;-import com.fasterxml.jackson.core.JsonParser;-import com.fasterxml.jackson.core.JsonProcessingException;-import com.fasterxml.jackson.core.Version;-import com.fasterxml.jackson.databind.DeserializationContext;-import com.fasterxml.jackson.databind.JsonSerializer;-import com.fasterxml.jackson.databind.SerializerProvider;-import com.fasterxml.jackson.databind.deser.std.StdDeserializer;-import com.fasterxml.jackson.databind.module.SimpleModule;-import elemental.json.*;--import java.io.IOException;--public class ElementalJsonModule extends SimpleModule {-- private static class ElementalJsonDeserializer<T extends JsonValue> extends StdDeserializer<T> {-- public ElementalJsonDeserializer() {- super(JsonValue.class);- }-- @Override- public T deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {- return (T) Json.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString());- }- }-- private static class ElementalJsonSerializer extends JsonSerializer<JsonValue> {- @Override- public void serialize(JsonValue value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {- if (value == null)- return;- if (value instanceof JsonNull) {- gen.writeNull();- } else {- gen.writeRawValue(value.toJson());- }- }- }-- public ElementalJsonModule() {- super("ElementalJsonModule", new Version(1, 0, 0, "latest", null, null));- ElementalJsonSerializer serializer = new ElementalJsonSerializer();- ElementalJsonDeserializer deserializer = new ElementalJsonDeserializer();- this.addSerializer(JsonValue.class, serializer);- this.addDeserializer(JsonObject.class, deserializer);- this.addDeserializer(JsonString.class, deserializer);- this.addDeserializer(JsonNumber.class, deserializer);- this.addDeserializer(JsonArray.class, deserializer);- this.addDeserializer(JsonValue.class, deserializer);- this.addDeserializer(JsonNull.class, deserializer);- }-}diff --git a/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java b/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.javadeleted file mode 100644index 1dcc2504d..000000000--- a/container/src/main/java/org/openremote/container/json/ElementalMessageBodyConverter.java+++ /dev/null@@ -1,70 +0,0 @@-/*- * Copyright 2017, 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.container.json;--import elemental.json.impl.JsonUtil;-import org.jboss.resteasy.plugins.providers.ProviderHelper;-import org.openremote.model.value.Value;-import org.openremote.model.value.Values;--import javax.ws.rs.WebApplicationException;-import javax.ws.rs.core.MediaType;-import javax.ws.rs.core.MultivaluedMap;-import javax.ws.rs.ext.MessageBodyReader;-import javax.ws.rs.ext.MessageBodyWriter;-import javax.ws.rs.ext.Provider;-import java.io.IOException;-import java.io.InputStream;-import java.io.OutputStream;-import java.lang.annotation.Annotation;-import java.lang.reflect.Type;--@Provider-public class ElementalMessageBodyConverter implements MessageBodyReader<Value>, MessageBodyWriter<Value> {-- @Override- public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {- return Value.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);- }-- @Override- public Value readFrom(Class<Value> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {- String str = ProviderHelper.readString(entityStream, mediaType);- return Values.parse(str).orElseThrow(() -> new IOException("Empty JSON data"));- }-- @Override- public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {- return Value.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);- }-- @Override- public long getSize(Value value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {- return -1;- }-- @Override- public void writeTo(Value value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {- String str = value.toJson();- String charset = mediaType.getParameters().get("charset");- if (charset == null) entityStream.write(str.getBytes("UTF-8"));- else entityStream.write(str.getBytes(charset));- }-}diff --git a/container/src/main/java/org/openremote/container/json/ElementalJsonObjectType.java b/container/src/main/java/org/openremote/container/json/ModelArrayValuePersistentType.javasimilarity index 69%rename from container/src/main/java/org/openremote/container/json/ElementalJsonObjectType.javarename to container/src/main/java/org/openremote/container/json/ModelArrayValuePersistentType.javaindex 7346e252d..a697b0863 100644--- a/container/src/main/java/org/openremote/container/json/ElementalJsonObjectType.java+++ b/container/src/main/java/org/openremote/container/json/ModelArrayValuePersistentType.java@@ -19,26 +19,27 @@*/package org.openremote.container.json;-import elemental.json.JsonObject;import org.hibernate.HibernateException;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Values;import java.io.Serializable;-public class ElementalJsonObjectType extends PostgreSQLJsonType {+public class ModelArrayValuePersistentType extends PostgreSQLJsonType {@Overridepublic Serializable disassemble(Object value) throws HibernateException {- return value == null ? null : ((JsonObject) value).toJson();+ return value == null ? null : ((ArrayValue) value).toJson();}@Override- public Object assemble(Serializable cached, Object owner) throws HibernateException {- return cached == null ? null : elemental.json.impl.JsonUtil.parse(cached.toString());+ public ArrayValue assemble(Serializable cached, Object owner) throws HibernateException {+ return cached == null ? null : Values.<ArrayValue>parse(cached.toString()).orElseThrow(() -> new HibernateException("Empty JSON data"));}@Overridepublic Class returnedClass() {- return JsonObject.class;+ return ArrayValue.class;}}diff --git a/container/src/main/java/org/openremote/container/json/ElementalJsonValueType.java b/container/src/main/java/org/openremote/container/json/ModelObjectValuePersistentType.javasimilarity index 68%rename from container/src/main/java/org/openremote/container/json/ElementalJsonValueType.javarename to container/src/main/java/org/openremote/container/json/ModelObjectValuePersistentType.javaindex ea3c38f9f..c1776d218 100644--- a/container/src/main/java/org/openremote/container/json/ElementalJsonValueType.java+++ b/container/src/main/java/org/openremote/container/json/ModelObjectValuePersistentType.java@@ -19,26 +19,27 @@*/package org.openremote.container.json;-import elemental.json.JsonValue;import org.hibernate.HibernateException;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Values;import java.io.Serializable;-public class ElementalJsonValueType extends PostgreSQLJsonType {+public class ModelObjectValuePersistentType extends PostgreSQLJsonType {@Overridepublic Serializable disassemble(Object value) throws HibernateException {- return value == null ? null : ((JsonValue) value).toJson();+ return value == null ? null : ((ObjectValue) value).toJson();}@Override- public Object assemble(Serializable cached, Object owner) throws HibernateException {- return cached == null ? null : elemental.json.impl.JsonUtil.parse(cached.toString());+ public ObjectValue assemble(Serializable cached, Object owner) throws HibernateException {+ return cached == null ? null : Values.<ObjectValue>parse(cached.toString()).orElseThrow(() -> new HibernateException("Empty JSON data"));}@Overridepublic Class returnedClass() {- return JsonValue.class;+ return ObjectValue.class;}}diff --git a/container/src/main/java/org/openremote/container/json/ModelValueMessageBodyConverter.java b/container/src/main/java/org/openremote/container/json/ModelValueMessageBodyConverter.javaindex 10483854e..0757b937a 100644--- a/container/src/main/java/org/openremote/container/json/ModelValueMessageBodyConverter.java+++ b/container/src/main/java/org/openremote/container/json/ModelValueMessageBodyConverter.java@@ -19,9 +19,9 @@*/package org.openremote.container.json;-import elemental.json.JsonValue;-import elemental.json.impl.JsonUtil;import org.jboss.resteasy.plugins.providers.ProviderHelper;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.MediaType;@@ -36,32 +36,32 @@ import java.lang.annotation.Annotation;import java.lang.reflect.Type;@Provider-public class ModelValueMessageBodyConverter implements MessageBodyReader<JsonValue>, MessageBodyWriter<JsonValue> {+public class ModelValueMessageBodyConverter implements MessageBodyReader<Value>, MessageBodyWriter<Value> {@Overridepublic boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {- return JsonValue.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);+ return Value.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);}@Override- public JsonValue readFrom(Class<JsonValue> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {+ public Value readFrom(Class<Value> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {String str = ProviderHelper.readString(entityStream, mediaType);- return JsonUtil.parse(str);+ return Values.parse(str).orElseThrow(() -> new IOException("Empty JSON data"));}@Overridepublic boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {- return JsonValue.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);+ return Value.class.isAssignableFrom(type) && mediaType.equals(MediaType.APPLICATION_JSON_TYPE);}@Override- public long getSize(JsonValue jsonValue, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {+ public long getSize(Value value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {return -1;}@Override- public void writeTo(JsonValue jsonValue, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {- String str = jsonValue.toJson();+ public void writeTo(Value value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {+ String str = value.toJson();String charset = mediaType.getParameters().get("charset");if (charset == null) entityStream.write(str.getBytes("UTF-8"));else entityStream.write(str.getBytes(charset));diff --git a/container/src/main/java/org/openremote/container/json/ModelValueModule.java b/container/src/main/java/org/openremote/container/json/ModelValueModule.javaindex 282e7a705..649fb0519 100644--- a/container/src/main/java/org/openremote/container/json/ModelValueModule.java+++ b/container/src/main/java/org/openremote/container/json/ModelValueModule.java@@ -43,7 +43,8 @@ public class ModelValueModule extends SimpleModule {@Overridepublic T deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException {try {- return (T) Values.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString()).orElse(null);+ return (T) Values.instance().parse(jsonParser.getCodec().readTree(jsonParser).toString()).+ orElseThrow(() -> new IOException("Empty JSON data"));} catch (ValueException ex) {throw new IOException(ex);}@@ -69,6 +70,7 @@ public class ModelValueModule extends SimpleModule {ValueJsonSerializer serializer = new ValueJsonSerializer();ValueJsonDeserializer deserializer = new ValueJsonDeserializer();this.addSerializer(Value.class, serializer);+ this.addDeserializer(Value.class, deserializer);this.addDeserializer(ObjectValue.class, deserializer);this.addDeserializer(ArrayValue.class, deserializer);this.addDeserializer(StringValue.class, deserializer);diff --git a/container/src/main/java/org/openremote/container/json/ElementalJsonArrayType.java b/container/src/main/java/org/openremote/container/json/ModelValuePersistentType.javasimilarity index 70%rename from container/src/main/java/org/openremote/container/json/ElementalJsonArrayType.javarename to container/src/main/java/org/openremote/container/json/ModelValuePersistentType.javaindex c4f29c7ae..95089e50a 100644--- a/container/src/main/java/org/openremote/container/json/ElementalJsonArrayType.java+++ b/container/src/main/java/org/openremote/container/json/ModelValuePersistentType.java@@ -19,26 +19,27 @@*/package org.openremote.container.json;-import elemental.json.JsonArray;import org.hibernate.HibernateException;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.io.Serializable;-public class ElementalJsonArrayType extends PostgreSQLJsonType {+public class ModelValuePersistentType extends PostgreSQLJsonType {@Overridepublic Serializable disassemble(Object value) throws HibernateException {- return value == null ? null : ((JsonArray) value).toJson();+ return value == null ? null : ((Value) value).toJson();}@Override- public Object assemble(Serializable cached, Object owner) throws HibernateException {- return cached == null ? null : elemental.json.impl.JsonUtil.parse(cached.toString());+ public Value assemble(Serializable cached, Object owner) throws HibernateException {+ return cached == null ? null : Values.parse(cached.toString()).orElseThrow(() -> new HibernateException("Empty JSON data"));}@Overridepublic Class returnedClass() {- return JsonArray.class;+ return Value.class;}}diff --git a/container/src/main/java/org/openremote/container/persistence/package-info.java b/container/src/main/java/org/openremote/container/persistence/package-info.javaindex 186a775ee..26ec21450 100644--- a/container/src/main/java/org/openremote/container/persistence/package-info.java+++ b/container/src/main/java/org/openremote/container/persistence/package-info.java@@ -21,21 +21,21 @@@org.hibernate.annotations.TypeDefs({@org.hibernate.annotations.TypeDef(name = Constants.PERSISTENCE_JSON_VALUE_TYPE,- typeClass = ElementalJsonValueType.class+ typeClass = ModelValuePersistentType.class),@org.hibernate.annotations.TypeDef(name = Constants.PERSISTENCE_JSON_OBJECT_TYPE,- typeClass = ElementalJsonObjectType.class+ typeClass = ModelObjectValuePersistentType.class),@org.hibernate.annotations.TypeDef(name = Constants.PERSISTENCE_JSON_ARRAY_TYPE,- typeClass = ElementalJsonArrayType.class+ typeClass = ModelArrayValuePersistentType.class)})package org.openremote.container.persistence;-import org.openremote.model.Constants;-import org.openremote.container.json.ElementalJsonArrayType;-import org.openremote.container.json.ElementalJsonObjectType;-import org.openremote.container.json.ElementalJsonValueType;+import org.openremote.container.json.ModelArrayValuePersistentType;+import org.openremote.container.json.ModelObjectValuePersistentType;+import org.openremote.container.json.ModelValuePersistentType;+import org.openremote.model.Constants;\ No newline at end of filediff --git a/container/src/main/java/org/openremote/container/web/WebClient.java b/container/src/main/java/org/openremote/container/web/WebClient.javaindex dcb2dc3fc..bb0468a04 100644--- a/container/src/main/java/org/openremote/container/web/WebClient.java+++ b/container/src/main/java/org/openremote/container/web/WebClient.java@@ -21,9 +21,8 @@ package org.openremote.container.web;import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;-import org.openremote.container.Container;-import org.openremote.container.json.ElementalMessageBodyConverter;import org.openremote.container.json.JacksonConfig;+import org.openremote.container.json.ModelValueMessageBodyConverter;import org.openremote.container.security.BearerAuthClientRequestFilter;import org.openremote.container.security.ClientSecretRequestFilter;@@ -43,7 +42,7 @@ public interface WebClient {static ResteasyClientBuilder registerDefaults(ResteasyClientBuilder builder) {return builder.register(new JacksonConfig())- .register(ElementalMessageBodyConverter.class)+ .register(ModelValueMessageBodyConverter.class).register(new ProxyClientRequestFilter()).register(new BearerAuthClientRequestFilter()).register(new ClientSecretRequestFilter());diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.javaindex b0ed71788..3c3da4048 100644--- a/container/src/main/java/org/openremote/container/web/WebService.java+++ b/container/src/main/java/org/openremote/container/web/WebService.java@@ -35,8 +35,8 @@ import org.jboss.resteasy.spi.ResteasyDeployment;import org.keycloak.adapters.KeycloakConfigResolver;import org.openremote.container.Container;import org.openremote.container.ContainerService;-import org.openremote.container.json.ElementalMessageBodyConverter;import org.openremote.container.json.JacksonConfig;+import org.openremote.container.json.ModelValueMessageBodyConverter;import org.openremote.container.security.AuthOverloadHandler;import org.openremote.container.security.CORSFilter;import org.openremote.container.security.IdentityService;@@ -343,7 +343,7 @@ public abstract class WebService implements ContainerService {resteasyDeployment.getProviders().add(new WebServiceExceptions.ForbiddenResteasyExceptionMapper(devMode));resteasyDeployment.getProviders().add(new JacksonConfig());resteasyDeployment.getProviders().add(new CORSFilter());- resteasyDeployment.getActualProviderClasses().add(ElementalMessageBodyConverter.class);+ resteasyDeployment.getActualProviderClasses().add(ModelValueMessageBodyConverter.class);resteasyDeployment.getActualProviderClasses().add(AlreadyGzippedWriterInterceptor.class);resteasyDeployment.getActualProviderClasses().add(ClientErrorExceptionHandler.class);diff --git a/manager/client/build.gradle b/manager/client/build.gradleindex 59f94e69b..c8c534797 100644--- a/manager/client/build.gradle+++ b/manager/client/build.gradle@@ -12,6 +12,7 @@ dependencies {compile resolveProject(":manager:shared")compile "com.google.gwt:gwt-user:$gwtVersion"+ compile "com.google.gwt:gwt-elemental:$gwtVersion"compile("com.google.gwt.inject:gin:$ginVersion")compile files(['lib/gwt-jackson-0.14.3-SNAPSHOT.jar'])//compile "com.github.nmorel.gwtjackson:gwt-jackson:$gwtJacksonVersion"diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.javaindex f8370dee1..8683a8958 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesBrowser.java@@ -26,10 +26,12 @@ import org.openremote.manager.client.Environment;import org.openremote.manager.client.datapoint.DatapointBrowser;import org.openremote.manager.client.util.CollectionsUtil;import org.openremote.manager.client.widget.*;-import org.openremote.model.*;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.ReadAssetAttributesEvent;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeExecuteStatus;+import org.openremote.model.attribute.AttributeType;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;import org.openremote.model.event.bus.EventRegistration;@@ -39,7 +41,7 @@ import java.util.LinkedHashMap;import java.util.List;import java.util.function.Consumer;-import static org.openremote.model.Attribute.isAttributeTypeEqualTo;+import static org.openremote.model.attribute.Attribute.isAttributeTypeEqualTo;public abstract class AttributesBrowserextends AttributesView<AttributesBrowser.Container, AttributesBrowser.Style> {@@ -67,7 +69,7 @@ public abstract class AttributesBrowserevent -> {for (AssetAttribute assetAttribute : attributeGroups.keySet()) {if (assetAttribute.getReference().map(ref -> ref.equals(event.getAttributeRef())).orElse(false)) {- assetAttribute.setValue(event.getValue(), event.getTimestamp());+ assetAttribute.setValue(event.getValue().orElse(null), event.getTimestamp());refreshAttribute(assetAttribute);break;}@@ -141,7 +143,7 @@ public abstract class AttributesBrowserstartButton.setPrimary(true);startButton.setIcon("play-circle");startButton.addClickHandler(clickEvent -> {- attribute.setValue(AttributeExecuteStatus.REQUEST_START.asJsonValue());+ attribute.setValue(AttributeExecuteStatus.REQUEST_START.asValue());writeAttributeValue(attribute);});formGroupActions.add(startButton);@@ -152,7 +154,7 @@ public abstract class AttributesBrowserrepeatButton.setPrimary(true);repeatButton.setIcon("repeat");repeatButton.addClickHandler(clickEvent -> {- attribute.setValue(AttributeExecuteStatus.REQUEST_REPEATING.asJsonValue());+ attribute.setValue(AttributeExecuteStatus.REQUEST_REPEATING.asValue());writeAttributeValue(attribute);});formGroupActions.add(repeatButton);@@ -163,7 +165,7 @@ public abstract class AttributesBrowsercancelButton.setPrimary(true);cancelButton.setIcon("stop-circle");cancelButton.addClickHandler(clickEvent -> {- attribute.setValue(AttributeExecuteStatus.REQUEST_CANCEL.asJsonValue());+ attribute.setValue(AttributeExecuteStatus.REQUEST_CANCEL.asValue());writeAttributeValue(attribute);});formGroupActions.add(cancelButton);diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.javaindex 1a8e08a4c..f2c1b9a4f 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesEditor.java@@ -23,25 +23,22 @@ import com.google.gwt.dom.client.Document;import com.google.gwt.event.dom.client.DomEvent;import com.google.gwt.user.client.ui.FlowPanel;import com.google.gwt.user.client.ui.IsWidget;-import elemental.json.Json;-import elemental.json.JsonType;-import elemental.json.JsonValue;import org.openremote.manager.client.Environment;import org.openremote.manager.client.widget.*;-import org.openremote.model.Attribute;-import org.openremote.model.AttributeType;-import org.openremote.model.MetaItem;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.MetaItem;import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ValueType;+import org.openremote.model.value.Values;import java.util.List;import java.util.Optional;import java.util.function.Consumer;-import static org.openremote.model.Attribute.ATTRIBUTE_NAME_VALIDATOR;-import static org.openremote.model.util.JsonUtil.getJsonValueType;-import static org.openremote.model.util.JsonUtil.sanitizeJsonValue;+import static org.openremote.model.attribute.Attribute.ATTRIBUTE_NAME_VALIDATOR;public class AttributesEditorextends AttributesView<AttributesEditor.Container, AttributesEditor.Style> {@@ -141,12 +138,8 @@ public class AttributesEditoraddButton.addClickHandler(clickEvent -> {if (attribute.isValid()) {formGroup.setError(false);- // TODO This is necessary because JSON elemental behavior is weird- AssetAttribute att2 = attribute.copy();- getAttributes().add(att2);- if (attribute.hasName()) {- showInfo(environment.getMessages().attributeAdded(attribute.getName().get()));- }+ getAttributes().add(attribute);+ showInfo(environment.getMessages().attributeAdded(attribute.getName().get()));build();} else {formGroup.setError(true);@@ -186,14 +179,14 @@ public class AttributesEditorFormListBox typeListBox = new FormListBox();typeListBox.addItem(environment.getMessages().selectType());for (AttributeType attributeType : AttributeType.values()) {- typeListBox.addItem(attributeType.getValue());+ typeListBox.addItem(attributeType.getDisplayName());}typeListBox.addChangeHandler(event -> {AttributeType attributeType =typeListBox.getSelectedIndex() > 0? AttributeType.values()[typeListBox.getSelectedIndex() - 1]: null;- attribute.setType(attributeType);+ attribute.setTypeAndClearValue(attributeType);});formField.add(typeListBox);@@ -225,7 +218,7 @@ public class AttributesEditorprotected void buildItemList() {itemListPanel.clear();- if (!attribute.hasMeta() || attribute.getMeta().isEmpty()) {+ if (attribute.getMeta().isEmpty()) {itemListSectionLabel.setVisible(false);return;}@@ -242,9 +235,10 @@ public class AttributesEditorFormField formField = new FormField();- // Determine editor based on JSON raw value type- JsonValue value = sanitizeJsonValue(item.getValue());- JsonType valueType = getJsonValueType(value);+ // Determine editor based on value type+ if (!item.getValue().isPresent())+ continue;+ ValueType valueType = item.getValue().get().getType();formField.add(createEditor(item, valueType, false, formGroup));formGroup.addFormField(formField);@@ -286,9 +280,7 @@ public class AttributesEditorif (item.isValid()) {itemNameEditorGroup.setError(false);itemValueEditorGroup.setError(false);- // TODO This is necessary because JSON elemental behavior is weird- MetaItem storedItem = new MetaItem(Json.parse(item.getJsonObject().toJson()));- attribute.getMeta().add(storedItem);+ attribute.getMeta().add(item);buildItemList();buildItemEditor();} else {@@ -301,7 +293,7 @@ public class AttributesEditoritemValueEditorGroup.addFormGroupActions(formGroupActions);}- protected IsWidget createEditor(MetaItem item, JsonType valueType, boolean forceEditable, FormGroup formGroup) {+ protected IsWidget createEditor(MetaItem item, ValueType valueType, boolean forceEditable, FormGroup formGroup) {IsWidget editor;AttributesEditor.Style style = container.getStyle();@@ -314,26 +306,26 @@ public class AttributesEditor// TODO: We should support more JSON types, and have special editors for well-known meta items// Default to STRING editor if value is empty/no type available- if (valueType == null || valueType.equals(JsonType.STRING)) {- String currentValue = item.getValueAsString().orElse(null);+ if (valueType == null || valueType.equals(ValueType.STRING)) {+ String currentValue = item.getValue().map(Object::toString).orElse(null);Consumer<String> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {formGroup.setError(false);- item.setValue(Json.create(value));+ item.setValue(Values.create(value));} : null;editor = createStringEditorWidget(style, currentValue, Optional.empty(), updateConsumer);- } else if (valueType.equals(JsonType.NUMBER)) {- String currentValue = item.getValueAsString().orElse(null);+ } else if (valueType.equals(ValueType.NUMBER)) {+ String currentValue = item.getValue().map(Object::toString).orElse(null);Consumer<String> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {Double decimalValue = Double.valueOf(value);formGroup.setError(false);- item.setValue(Json.create(decimalValue));+ item.setValue(Values.create(decimalValue));} : null;editor = createDecimalEditorWidget(style, currentValue, Optional.empty(), updateConsumer, errorConsumer);- } else if (valueType.equals(JsonType.BOOLEAN)) {+ } else if (valueType.equals(ValueType.BOOLEAN)) {Boolean currentValue = item.getValueAsBoolean().orElse(false);Consumer<Boolean> updateConsumer = isEditable == null || isEditable || forceEditable ? value -> {formGroup.setError(false);- item.setValue(Json.create(value));+ item.setValue(Values.create(value));} : null;editor = createBooleanEditorWidget(style, currentValue, Optional.empty(), updateConsumer);} else {@@ -421,11 +413,11 @@ public class AttributesEditor// Create and add new editor, default to empty STRINGitem.clearValue();- JsonType valueType = typeListBox.getSelectedIndex() > 0+ ValueType valueType = typeListBox.getSelectedIndex() > 0? AssetMeta.EditableType.valueOf(typeListBox.getSelectedValue()).valueType- : JsonType.STRING;- if (valueType == JsonType.BOOLEAN) {- item.setValue(Json.create(false)); // Special case boolean editor, has an "initial" state, there is always a value+ : ValueType.STRING;+ if (valueType == ValueType.BOOLEAN) {+ item.setValue(Values.create(false)); // Special case boolean editor, has an "initial" state, there is always a value}IsWidget editor = createEditor(item, valueType, true, formGroup);formField.add(editor);diff --git a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.javaindex f10042dca..805c7e268 100644--- a/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/assets/attributes/AttributesView.java@@ -19,13 +19,11 @@*/package org.openremote.manager.client.assets.attributes;-import com.google.gwt.dom.client.Style;import com.google.gwt.i18n.client.DateTimeFormat;import com.google.gwt.user.client.ui.FlowPanel;import com.google.gwt.user.client.ui.InsertPanel;import com.google.gwt.user.client.ui.IsWidget;import com.google.gwt.user.client.ui.Label;-import elemental.json.Json;import org.openremote.manager.client.Environment;import org.openremote.manager.client.event.ShowFailureEvent;import org.openremote.manager.client.event.ShowInfoEvent;@@ -34,12 +32,13 @@ import org.openremote.manager.client.i18n.ManagerMessages;import org.openremote.manager.client.util.CollectionsUtil;import org.openremote.manager.client.widget.*;import org.openremote.model.AbstractValueHolder;-import org.openremote.model.AttributeType;import org.openremote.model.Constants;-import org.openremote.model.MetaItem;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.MetaItem;import org.openremote.model.util.TextUtil;+import org.openremote.model.value.Values;import java.util.*;import java.util.function.Consumer;@@ -236,19 +235,19 @@ public abstract class AttributesView<FormField unsupportedField = new FormField();unsupportedField.add(new FormOutputText(environment.getMessages().unsupportedAttributeType(- attribute.getType().map(AttributeType::getValue).orElse(null)+ attribute.getType().map(AttributeType::getDisplayName).orElse(null))));return () -> unsupportedField;}protected AttributeEditor createStringEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {- String currentValue = attribute.getValueAsString().orElse(null);+ String currentValue = attribute.getValue().map(Object::toString).orElse(null);Optional<String> defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsString);Consumer<String> updateConsumer = isEditorReadOnly(attribute) ? null : value -> {formGroup.setError(false);- attribute.setValue(Json.create(value));+ attribute.setValue(Values.create(value));};FlowPanel panel = new FlowPanel();@@ -288,12 +287,12 @@ public abstract class AttributesView<}protected AttributeEditor createIntegerEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {- String currentValue = attribute.getValueAsString().orElse(null);+ String currentValue = attribute.getValue().map(Object::toString).orElse(null);Optional<String> defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsString);Consumer<String> updateConsumer = isEditorReadOnly(attribute) ? null : value -> {Integer intValue = Integer.valueOf(value);formGroup.setError(false);- attribute.setValue(Json.create(intValue));+ attribute.setValue(Values.create(intValue));};Consumer<String> errorConsumer = msg -> {@@ -343,12 +342,12 @@ public abstract class AttributesView<}protected AttributeEditor createDecimalEditor(AssetAttribute attribute, Optional<MetaItem> defaultValueItem, S style, FormGroup formGroup) {- String currentValue = attribute.getValueAsString().orElse(null);+ String currentValue = attribute.getValue().map(Object::toString).orElse(null);Optional<String> defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsString);Consumer<String> updateConsumer = isEditorReadOnly(attribute) ? null : value -> {Double decimalValue = Double.valueOf(value);formGroup.setError(false);- attribute.setValue(Json.create(decimalValue));+ attribute.setValue(Values.create(decimalValue));};Consumer<String> errorConsumer = msg -> {@@ -403,7 +402,7 @@ public abstract class AttributesView<Optional<Boolean> defaultValue = defaultValueItem.flatMap(AbstractValueHolder::getValueAsBoolean);Consumer<Boolean> updateConsumer = isEditorReadOnly(attribute) ? null : value -> {formGroup.setError(false);- attribute.setValue(Json.create(value));+ attribute.setValue(Values.create(value));};FlowPanel panel = new FlowPanel();diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonDeserializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonDeserializer.javadeleted file mode 100644index 43ebf0b8d..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonDeserializer.java+++ /dev/null@@ -1,44 +0,0 @@-/*- * 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.manager.client.interop.jackson;--import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;-import com.github.nmorel.gwtjackson.client.JsonDeserializer;-import com.github.nmorel.gwtjackson.client.JsonDeserializerParameters;-import com.github.nmorel.gwtjackson.client.stream.JsonReader;-import elemental.json.Json;-import elemental.json.JsonValue;-import org.openremote.model.util.JsonUtil;--import static org.openremote.model.util.JsonUtil.sanitizeJsonValue;--public class ElementalJsonDeserializer extends JsonDeserializer<JsonValue> {-- @Override- protected JsonValue doDeserialize(JsonReader reader, JsonDeserializationContext ctx, JsonDeserializerParameters params) {- if (reader.hasNext()) {- String nextValue = reader.nextValue();- JsonValue value = Json.instance().parse(nextValue);- value = sanitizeJsonValue(value);- return value;- }- return null;- }-}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonSerializer.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonSerializer.javadeleted file mode 100644index 1c997452a..000000000--- a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/ElementalJsonSerializer.java+++ /dev/null@@ -1,47 +0,0 @@-/*- * 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.manager.client.interop.jackson;--import com.github.nmorel.gwtjackson.client.JsonSerializationContext;-import com.github.nmorel.gwtjackson.client.JsonSerializer;-import com.github.nmorel.gwtjackson.client.JsonSerializerParameters;-import com.github.nmorel.gwtjackson.client.stream.JsonWriter;-import elemental.json.JsonValue;--import static org.openremote.model.util.JsonUtil.sanitizeJsonValue;--public class ElementalJsonSerializer extends JsonSerializer<Object> {-- @Override- protected void doSerialize(JsonWriter writer, Object value, JsonSerializationContext ctx, JsonSerializerParameters params) {- if (value instanceof JsonValue) {- JsonValue jsonValue = (JsonValue) value;- writer.rawValue(jsonValue.toJson());- } else {- // If elemental gives us a JS primitive, use JS serialization- writer.rawValue(stringify(value));- }- }-- final public native String stringify(Object value) /*-{- return $wnd.JSON.stringify(value);- }-*/;--}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.javaindex a21796363..5e3fc2f24 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/jackson/SerializationConfiguration.java@@ -21,7 +21,6 @@ package org.openremote.manager.client.interop.jackson;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.github.nmorel.gwtjackson.client.AbstractConfiguration;-import elemental.json.*;import org.openremote.model.value.*;/**@@ -42,15 +41,5 @@ public class SerializationConfiguration extends AbstractConfiguration {type(NumberValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);type(StringValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);type(BooleanValue.class).serializer(ModelValueSerializer.class).deserializer(ModelValueDeserializer.class);-- // TODO remove elemental json- type(JsonObject.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonArray.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonValue.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonNull.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonNumber.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonString.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);- type(JsonBoolean.class).serializer(ElementalJsonSerializer.class).deserializer(ElementalJsonDeserializer.class);-}}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/keycloak/Keycloak.java b/manager/client/src/main/java/org/openremote/manager/client/interop/keycloak/Keycloak.javaindex c9ab3fbd2..f5e412056 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/keycloak/Keycloak.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/keycloak/Keycloak.java@@ -19,8 +19,9 @@*/package org.openremote.manager.client.interop.keycloak;-import elemental.json.JsonArray;-import elemental.json.JsonObject;+import com.google.gwt.core.client.JavaScriptObject;+import com.google.gwt.json.client.JSONArray;+import com.google.gwt.json.client.JSONObject;import jsinterop.annotations.JsProperty;import jsinterop.annotations.JsType;import org.openremote.manager.client.interop.Runnable;@@ -51,19 +52,19 @@ public class Keycloak {public String idToken;@JsProperty- public JsonObject idTokenParsed;+ public JavaScriptObject idTokenParsed;@JsProperty- public JsonArray realmAceess;+ public JavaScriptObject realmAccess;@JsProperty- public JsonArray resourceAccess;+ public JavaScriptObject resourceAccess;@JsPropertypublic String refreshToken;@JsProperty- public JsonObject refreshTokenParsed;+ public JavaScriptObject refreshTokenParsed;@JsPropertypublic int timeSkew;diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/AnimationOptions.java b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/AnimationOptions.javaindex 553234627..849430956 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/AnimationOptions.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/AnimationOptions.java@@ -19,7 +19,7 @@*/package org.openremote.manager.client.interop.mapbox;-import elemental.json.JsonArray;+import com.google.gwt.core.client.JavaScriptObject;import jsinterop.annotations.JsProperty;public class AnimationOptions {@@ -30,7 +30,7 @@ public class AnimationOptions {public EasingFn easing;@JsProperty- public JsonArray offset;+ public JavaScriptObject offset;@JsPropertypublic boolean animate;diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/FeaturesCallbackFn.java b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/FeaturesCallbackFn.javaindex 99574fa18..b959ee3c9 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/FeaturesCallbackFn.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/FeaturesCallbackFn.java@@ -19,12 +19,11 @@*/package org.openremote.manager.client.interop.mapbox;-import elemental.json.JsonArray;-import elemental.json.JsonObject;+import com.google.gwt.core.client.JavaScriptObject;import jsinterop.annotations.JsFunction;@FunctionalInterface@JsFunctionpublic interface FeaturesCallbackFn {- void onCallback(JsonObject error, JsonArray features);+ void onCallback(JavaScriptObject error, JavaScriptObject features);}diff --git a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapOptions.java b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapOptions.javaindex 580ff364d..db084727b 100644--- a/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapOptions.java+++ b/manager/client/src/main/java/org/openremote/manager/client/interop/mapbox/MapOptions.java@@ -19,13 +19,13 @@*/package org.openremote.manager.client.interop.mapbox;-import elemental.json.JsonArray;-import elemental.json.JsonObject;+import com.google.gwt.core.client.JavaScriptObject;import jsinterop.annotations.JsProperty;import jsinterop.annotations.JsType;@JsTypepublic class MapOptions {+@JsPropertypublic boolean touchZoomRotate;@@ -39,7 +39,7 @@ import jsinterop.annotations.JsType;public int maxZoom;@JsProperty- public JsonObject style;+ public JavaScriptObject style;@JsPropertypublic boolean hash;@@ -51,7 +51,7 @@ import jsinterop.annotations.JsType;public int bearingSnap;@JsProperty- public JsonArray classes;+ public JavaScriptObject classes;@JsPropertypublic boolean attributionControl;diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.javaindex fd21f0639..ea99b1a06 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapActivity.java@@ -33,13 +33,13 @@ import org.openremote.manager.client.mvp.AppActivity;import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.map.MapResource;import org.openremote.manager.shared.security.Tenant;-import org.openremote.model.AttributeEvent;-import org.openremote.model.Pair;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.event.bus.EventBus;import org.openremote.model.event.bus.EventRegistration;import org.openremote.model.geo.GeoJSON;+import org.openremote.model.util.Pair;import javax.inject.Inject;import java.util.ArrayList;@@ -50,7 +50,7 @@ import java.util.logging.Logger;import java.util.stream.Collectors;import static org.openremote.manager.client.http.RequestExceptionHandler.handleRequestException;-import static org.openremote.model.Attribute.isAttributeNameEqualTo;+import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapView.Presenter {@@ -126,9 +126,7 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapV.filter(isAttributeNameEqualTo(event.getAttributeName())).findFirst().map(attribute -> {- attribute.setValue(- event.getValue(), event.getTimestamp()- );+ attribute.setValue(event.getValue().orElse(null), event.getTimestamp());return attribute;});@@ -198,8 +196,12 @@ public class MapActivity extends AssetBrowsingActivity<MapPlace> implements MapVprotected void showAssetInfoItems() {List<Pair<String, String>> infoItems = dashboardAttributes.stream().map(attribute -> new Pair<>(- attribute.getLabel().orElse(""),- format(attribute.getFormat().orElse(null), attribute.getValueAsString().orElse(null)))+ attribute.getLabel().orElse(""),+ format(+ attribute.getFormat().orElse(null),+ attribute.getValue().map(Object::toString).orElse(null)+ )+ )).sorted(Comparator.comparing(pair -> pair.key)).collect(Collectors.toList());diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.javaindex 7c8894d11..e3f1757c4 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapInfoPanel.java@@ -32,7 +32,7 @@ import org.openremote.manager.client.style.WidgetStyle;import org.openremote.manager.client.widget.AbstractAppPanel;import org.openremote.manager.client.widget.FormLabel;import org.openremote.manager.client.widget.PopupPanel;-import org.openremote.model.Pair;+import org.openremote.model.util.Pair;import org.openremote.model.util.TextUtil;import java.util.List;diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapView.javaindex 2d6b37aab..3ae5df2c2 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapView.java@@ -20,7 +20,7 @@package org.openremote.manager.client.map;import com.google.gwt.user.client.ui.IsWidget;-import org.openremote.model.Pair;+import org.openremote.model.util.Pair;import org.openremote.model.geo.GeoJSON;import org.openremote.model.value.ObjectValue;diff --git a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.javaindex e4f1b08e7..6c6ded899 100644--- a/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java+++ b/manager/client/src/main/java/org/openremote/manager/client/map/MapViewImpl.java@@ -26,13 +26,12 @@ import com.google.gwt.user.client.ui.Composite;import com.google.gwt.user.client.ui.HTMLPanel;import com.google.inject.Provider;import elemental.client.Browser;-import elemental.json.JsonObject;import org.openremote.manager.client.assets.browser.AssetBrowser;import org.openremote.manager.client.style.WidgetStyle;import org.openremote.manager.client.widget.FlexSplitPanel;import org.openremote.manager.client.widget.Hyperlink;import org.openremote.manager.client.widget.MapWidget;-import org.openremote.model.Pair;+import org.openremote.model.util.Pair;import org.openremote.model.geo.GeoJSON;import org.openremote.model.value.ObjectValue;diff --git a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.javaindex a86459545..07c5a028d 100644--- a/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java+++ b/manager/client/src/main/java/org/openremote/manager/client/widget/MapWidget.java@@ -23,7 +23,6 @@ import com.google.gwt.core.client.JavaScriptObject;import com.google.gwt.dom.client.Document;import com.google.gwt.user.client.ui.FlowPanel;import elemental.client.Browser;-import elemental.js.util.*;import org.openremote.manager.client.interop.mapbox.*;import org.openremote.model.geo.GeoJSON;import org.openremote.model.value.ArrayValue;@@ -32,6 +31,8 @@ import org.openremote.model.value.Values;import java.util.logging.Logger;+import static org.openremote.model.value.Values.create;+public class MapWidget extends FlowPanel {private static final Logger LOG = Logger.getLogger(MapWidget.class.getName());@@ -47,19 +48,17 @@ public class MapWidget extends FlowPanel {public static final String FEATURE_LAYER_DROPPED_PIN = "feature-layer-dropped-pin";// Render a circle on location- @SuppressWarnings("GwtInconsistentSerializableClass")- static final public JsMapFromStringTo<Object> LAYER_CIRCLE = JsMapFromStringTo.create();+ static final public ObjectValue LAYER_CIRCLE = Values.createObject();// Render a dropped pin and feature title on location- @SuppressWarnings("GwtInconsistentSerializableClass")- static final public JsMapFromStringTo<Object> LAYER_DROPPED_PIN = JsMapFromStringTo.create();+ static final public ObjectValue LAYER_DROPPED_PIN = Values.createObject();static {{- JsMapFromStringTo<Object> layout = JsMapFromStringTo.create();+ ObjectValue layout = Values.createObject();layout.put("visibility", "visible");- JsMapFromStringTo<Object> paint = JsMapFromStringTo.create();+ ObjectValue paint = Values.createObject();paint.put("circle-radius", 12.0); // This MUST be double!paint.put("circle-opacity", 0.5);// TODO Add color to theme settings@@ -72,38 +71,33 @@ public class MapWidget extends FlowPanel {LAYER_CIRCLE.put("paint", paint);}{- JsMapFromStringTo<Object> layout = JsMapFromStringTo.create();+ ObjectValue layout = Values.createObject();;layout.put("visibility", "visible");layout.put("text-field", "{title}");- JsArrayOfString textFont = JsArrayOfString.create();- textFont.push("Open Sans Semibold");+ ArrayValue textFont = Values.createArray();+ textFont.add(create("Open Sans Semibold"));layout.put("text-font", textFont);- JsMapFromStringTo<Object> textSize = JsMapFromStringTo.create();- JsArrayOfInt stop1 = JsArrayOfInt.create();- stop1.push(3);- stop1.push(8);- JsArrayOfInt stop2 = JsArrayOfInt.create();- stop2.push(10);- stop2.push(20);- JsArrayOf<JsArrayOfInt> stops = JsArrayOf.create();- stops.push(stop1);- stops.push(stop2);+ ObjectValue textSize = Values.createObject();+ ArrayValue stop1 = Values.createArray();+ stop1.addAll(create(3), create(8));+ ArrayValue stop2 = Values.createArray();+ stop2.addAll(create(10), create(20));+ ArrayValue stops = Values.createArray();+ stops.addAll(stop1, stop2);textSize.put("stops", stops);layout.put("text-size", textSize);layout.put("text-allow-overlap", true);- JsArrayOfNumber offset = JsArrayOfNumber.create();- offset.push(0);- offset.push(0.8);+ ArrayValue offset = Values.createArray();+ offset.addAll(create(0), create(0.8));layout.put("text-offset", offset);layout.put("icon-image", "marker-15");- offset = JsArrayOfNumber.create();- offset.push(0);- offset.push(-4);+ offset = Values.createArray();+ offset.addAll(create(0), create(-4));layout.put("icon-offset", offset);- JsMapFromStringTo<Object> paint = JsMapFromStringTo.create();+ ObjectValue paint = Values.createObject();// TODO Add color to theme settings//paint.put("icon-color", "rgb(193, 215, 47)");paint.put("text-color", "#000");@@ -198,8 +192,8 @@ public class MapWidget extends FlowPanel {if (!isMapReady())throw new IllegalStateException("Map not ready");ObjectValue popupOptions = Values.createObject();- popupOptions.put("closeOnClick", Values.create(false));- popupOptions.put("closeButton", Values.create(false));+ popupOptions.put("closeOnClick", create(false));+ popupOptions.put("closeButton", create(false));popup = new Popup(popupOptions.asNativeObject());popup.setLngLat(new LngLat(lng, lat)).setText(text);popup.addTo(mapboxMap);@@ -239,18 +233,18 @@ public class MapWidget extends FlowPanel {ObjectValue sourceOptionsSelection = prepareSourceOptions(FEATURE_SOURCE_DROPPED_PIN);mapboxMap.addSource(FEATURE_SOURCE_DROPPED_PIN, sourceOptionsSelection.asNativeObject());- mapboxMap.addLayer(LAYER_DROPPED_PIN);+ mapboxMap.addLayer(LAYER_DROPPED_PIN.asNativeObject());ObjectValue sourceOptionsAll = prepareSourceOptions(FEATURE_SOURCE_CIRCLE);- sourceOptionsAll.put("maxzoom", Values.create(20));- sourceOptionsAll.put("buffer", Values.create(128));- sourceOptionsAll.put("tolerance", Values.create(0.375));- sourceOptionsAll.put("cluster", Values.create(false));- sourceOptionsAll.put("clusterRadius", Values.create(50));- sourceOptionsAll.put("clusterMaxZoom", Values.create(15));+ sourceOptionsAll.put("maxzoom", create(20));+ sourceOptionsAll.put("buffer", create(128));+ sourceOptionsAll.put("tolerance", create(0.375));+ sourceOptionsAll.put("cluster", create(false));+ sourceOptionsAll.put("clusterRadius", create(50));+ sourceOptionsAll.put("clusterMaxZoom", create(15));mapboxMap.addSource(FEATURE_SOURCE_CIRCLE, sourceOptionsAll.asNativeObject());- mapboxMap.addLayer(LAYER_CIRCLE, FEATURE_LAYER_DROPPED_PIN);+ mapboxMap.addLayer(LAYER_CIRCLE.asNativeObject(), FEATURE_LAYER_DROPPED_PIN);}protected ObjectValue prepareSourceOptions(String featureSourceId) {@@ -258,7 +252,7 @@ public class MapWidget extends FlowPanel {// Initialize with empty collectionObjectValue initialData = GeoJSON.EMPTY_FEATURE_COLLECTION.getObjectValue();LOG.fine("Preparing initial data on feature source: " + featureSourceId);- sourceOptions.put("type", Values.create("geojson"));+ sourceOptions.put("type", create("geojson"));sourceOptions.put("data", initialData);return sourceOptions;}diff --git a/manager/client/src/main/resources/org/openremote/manager/Manager.gwt.xml b/manager/client/src/main/resources/org/openremote/manager/Manager.gwt.xmlindex b078dc879..8e4306e60 100644--- a/manager/client/src/main/resources/org/openremote/manager/Manager.gwt.xml+++ b/manager/client/src/main/resources/org/openremote/manager/Manager.gwt.xml@@ -13,6 +13,7 @@<inherits name="com.google.gwt.inject.Inject"/><inherits name="com.google.gwt.i18n.I18N"/><inherits name="com.google.gwt.http.HTTP"/>+ <inherits name="elemental.Elemental"/><inherits name="com.github.nmorel.gwtjackson.GwtJackson"/><inherits name="org.jboss.resteasy.api.validation.ResteasyValidation"/><inherits name="org.keycloak.representations.idm.KeycloakIDM"/>diff --git a/manager/client/src/main/resources/org/openremote/model/Model.gwt.xml b/manager/client/src/main/resources/org/openremote/model/Model.gwt.xmlindex 7091332e6..c52a121c5 100644--- a/manager/client/src/main/resources/org/openremote/model/Model.gwt.xml+++ b/manager/client/src/main/resources/org/openremote/model/Model.gwt.xml@@ -3,8 +3,6 @@<module rename-to="Model">- <inherits name="elemental.Elemental"/>-<source path=""/></module>\ No newline at end of filediff --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 4d55ce1f3..a511d0b09 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@@ -19,7 +19,6 @@*/package org.openremote.manager.server.agent;-import elemental.json.JsonObject;import org.apache.camel.builder.RouteBuilder;import org.openremote.agent3.protocol.Protocol;import org.openremote.container.Container;@@ -31,13 +30,13 @@ import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.datapoint.AssetDatapointService;import org.openremote.model.AbstractValueTimestampHolder;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.Pair;import org.openremote.model.asset.*;import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.asset.agent.ProtocolConfiguration;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;import java.util.*;import java.util.function.Consumer;@@ -143,7 +142,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// which protocol configs are affectedList<AssetAttribute> oldProtocolConfigurations =attributesFromJson(- (JsonObject) persistenceEvent.getPreviousState()[attributesIndex],+ (ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],agent.getId()).filter(ProtocolConfiguration::isProtocolConfiguration)@@ -151,7 +150,7 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsList<AssetAttribute> newProtocolConfigurations =attributesFromJson(- (JsonObject) persistenceEvent.getCurrentState()[attributesIndex],+ (ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],agent.getId()).filter(ProtocolConfiguration::isProtocolConfiguration)@@ -163,9 +162,8 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.stream().filter(oldProtocolAttribute -> newProtocolConfigurations.stream()- .noneMatch(newProtocolAttribute -> JsonUtil.equals(- oldProtocolAttribute.getJsonObject(),- newProtocolAttribute.getJsonObject())+ .noneMatch(newProtocolAttribute ->+ oldProtocolAttribute.getObjectValue().equals(newProtocolAttribute.getObjectValue()))).forEach(this::unlinkProtocol);@@ -176,10 +174,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.filter(newProtocolAttribute -> oldProtocolConfigurations.stream().noneMatch(oldProtocolAttribute ->- JsonUtil.equals(- oldProtocolAttribute.getJsonObject(),- newProtocolAttribute.getJsonObject()- )+ oldProtocolAttribute.getObjectValue().equals(newProtocolAttribute.getObjectValue()))).forEach(this::linkProtocol);@@ -226,7 +221,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// AGENT_LINK attributesList<AssetAttribute> oldAgentLinkedAttributes =attributesFromJson(- (JsonObject) persistenceEvent.getPreviousState()[attributesIndex],+ (ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],asset.getId()).filter(AgentLink::hasAgentLink)@@ -234,7 +229,7 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsList<AssetAttribute> newAgentLinkedAttributes =attributesFromJson(- (JsonObject) persistenceEvent.getCurrentState()[attributesIndex],+ (ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],asset.getId()).filter(AgentLink::hasAgentLink)@@ -245,10 +240,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.stream().filter(oldAgentLinkedAttribute -> newAgentLinkedAttributes.stream()- .noneMatch(newAgentLinkedAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison- oldAgentLinkedAttribute.getJsonObject(),- newAgentLinkedAttribute.getJsonObject(),- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))+ .noneMatch(newAgentLinkedAttribute ->+ oldAgentLinkedAttribute.getObjectValue().equalsIgnoreKeys(+ newAgentLinkedAttribute.getObjectValue(),+ AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME+ )));@@ -260,10 +256,11 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons.stream().filter(newThingAttribute -> oldAgentLinkedAttributes.stream()- .noneMatch(oldThingAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison- oldThingAttribute.getJsonObject(),- newThingAttribute.getJsonObject(),- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))+ .noneMatch(oldThingAttribute ->+ oldThingAttribute.getObjectValue().equalsIgnoreKeys(+ newThingAttribute.getObjectValue(),+ AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME+ )));@@ -409,7 +406,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Conspublic void accept(AssetState assetState) {// If update was initiated by a protocol ignore itif (assetState.isNorthbound()) {- LOG.fine("Ignoring as it came from a protocol:" + assetState);+ LOG.fine("Ignoring as it came from a protocol: " + assetState);return;}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 9b0d900fe..0b1427869 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@@ -32,9 +32,10 @@ import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.rules.RulesService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.security.ClientRole;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeExecuteStatus;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.asset.*;+import org.openremote.model.value.Values;import java.util.ArrayList;import java.util.Date;@@ -48,7 +49,6 @@ import static org.openremote.agent3.protocol.Protocol.SENSOR_QUEUE;import static org.openremote.manager.server.event.EventService.INCOMING_EVENT_TOPIC;import static org.openremote.manager.server.event.EventService.getWebsocketAuth;import static org.openremote.model.asset.agent.AgentLink.getAgentLink;-import static org.openremote.model.util.JsonUtil.asString;/*** Receives {@link AttributeEvent}s and processes them.@@ -331,16 +331,16 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// If attribute is marked as executable and not from northbound only allow write AttributeExecuteStatus to be sentif (!fromProtocol && attribute.get().isExecutable()) {- AttributeExecuteStatus status = asString(attributeEvent.getValue())- .map(AttributeExecuteStatus::fromString)- .orElse(null);+ Optional<AttributeExecuteStatus> status = attributeEvent.getValue()+ .flatMap(Values::getString)+ .flatMap(AttributeExecuteStatus::fromString);- if (status == null) {+ if (!status.isPresent()) {LOG.warning("Attribute event doesn't contain a valid AttributeExecuteStatus value: " + attributeEvent);return;}- if (!status.isWrite()) {+ if (!status.get().isWrite()) {LOG.warning("Only AttributeExecuteStatus write value can be written to an attribute: " + attributeEvent);return;}@@ -417,7 +417,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Set new value and event timestamp on attribute, thus validating any attribute constraintstry {- attribute.setValue(attributeEvent.getAttributeState().getValue(), attributeEvent.getTimestamp());+ attribute.setValue(attributeEvent.getValue().orElse(null), attributeEvent.getTimestamp());} catch (IllegalArgumentException ex) {LOG.log(Level.WARNING, "Ignoring " + attributeEvent + ", attribute constraint violation in: " + asset, ex);return;diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.javaindex 3557041e9..5294a6f69 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetResourceImpl.java@@ -19,18 +19,18 @@*/package org.openremote.manager.server.asset;-import elemental.json.Json;-import elemental.json.JsonValue;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.web.ManagerWebResource;import org.openremote.manager.shared.asset.AssetResource;import org.openremote.manager.shared.http.RequestParams;import org.openremote.manager.shared.security.Tenant;-import org.openremote.model.Attribute;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetQuery;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;@@ -260,7 +260,9 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour// Process updatetry {- JsonValue value = Json.instance().parse(rawJson);+ Value value = Values.instance()+ .parse(rawJson)+ .orElse(null); // When parsing literal JSON "null"assetProcessingService.sendAttributeEvent(new AttributeEvent(new AttributeRef(assetId, attributeName), value));diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex e9bf857f8..35d4c94be 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -19,8 +19,6 @@*/package org.openremote.manager.server.asset;-import elemental.json.JsonType;-import elemental.json.JsonValue;import org.apache.camel.builder.RouteBuilder;import org.hibernate.Session;import org.hibernate.jdbc.AbstractReturningWork;@@ -36,10 +34,10 @@ import org.openremote.manager.server.event.EventService;import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.shared.security.ClientRole;import org.openremote.manager.shared.security.Tenant;-import org.openremote.model.AttributeEvent;-import org.openremote.model.Pair;-import org.openremote.model.asset.ReadAssetAttributesEvent;import org.openremote.model.asset.*;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.util.Pair;+import org.openremote.model.value.Value;import org.postgresql.util.PGobject;import javax.persistence.EntityManager;@@ -124,7 +122,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicString assetId = assetState.getId();String attributeName = assetState.getAttribute().getName().orElseThrow(() -> new IllegalStateException("Cannot store asset state for attribute with no name"));- JsonValue value = assetState.getAttribute().getValue().orElse(null);+ Value value = assetState.getAttribute().getValue().orElse(null);// Some sanity checking, of course the timestamp should never be -1 if we store updated attribute statelong timestamp = assetState.getAttribute().getValueTimestamp();String valueTimestamp = Long.toString(@@ -580,7 +578,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic);}- protected boolean storeAttributeValue(String assetId, String attributeName, JsonValue value, String timestamp) {+ protected boolean storeAttributeValue(String assetId, String attributeName, Value value, String timestamp) {return persistenceService.doReturningTransaction(entityManager ->entityManager.unwrap(Session.class).doReturningWork(connection -> {@@ -607,7 +605,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicPGobject pgJsonValue = new PGobject();pgJsonValue.setType("jsonb");// Careful, do not set Java null (as returned by value.toJson()) here! It will erase your whole SQL column!- pgJsonValue.setValue(value == null || value.getType() == JsonType.NULL ? "null" : value.toJson());+ pgJsonValue.setValue(value == null ? "null" : value.toJson());statement.setObject(2, pgJsonValue);// Bind the value timestamp@@ -687,9 +685,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic// Client may want to read a subset or all attributes of the assetList<AttributeEvent> events = asset.getAttributesStream()- .filter(AssetAttribute::hasName)- .filter(attribute -> names.isEmpty() || names.contains(attribute.getName().get()))+ .filter(attribute -> names.isEmpty() || attribute.getName().filter(names::contains).isPresent()).map(AssetAttribute::getStateEvent)+ .filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList());diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.javaindex 6a9481d57..10aaa400e 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/ServerAsset.java@@ -23,13 +23,14 @@ import com.fasterxml.jackson.annotation.JsonIgnore;import com.vividsolutions.jts.geom.Coordinate;import com.vividsolutions.jts.geom.GeometryFactory;import com.vividsolutions.jts.geom.Point;-import elemental.json.Json;import org.geolatte.geom.Geometry;import org.geolatte.geom.jts.JTS;import org.hibernate.annotations.Check;import org.hibernate.spatial.dialect.postgis.PGGeometryTypeDescriptor;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetType;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Values;import javax.persistence.*;import javax.validation.constraints.NotNull;@@ -117,7 +118,9 @@ public class ServerAsset extends Asset {parentId, parentName, parentType,realmId, tenantRealm, tenantDisplayName,path != null ? (String[]) path.getArray() : null,- attributes != null && attributes.length() > 0 ? Json.instance().parse(attributes) : null+ attributes != null && attributes.length() > 0+ ? Values.instance().<ObjectValue>parse(attributes).orElse(null)+ : null);Point position = null;diff --git a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.javaindex 52f4b4cf9..716e08ff1 100644--- a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java+++ b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointResourceImpl.java@@ -25,7 +25,7 @@ import org.openremote.manager.server.security.ManagerIdentityService;import org.openremote.manager.server.web.ManagerWebResource;import org.openremote.manager.shared.datapoint.AssetDatapointResource;import org.openremote.manager.shared.http.RequestParams;-import org.openremote.model.AttributeRef;+import org.openremote.model.attribute.AttributeRef;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;@@ -33,7 +33,7 @@ import javax.ws.rs.BeanParam;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.Response;-import static org.openremote.model.Attribute.isAttributeNameEqualTo;+import static org.openremote.model.attribute.Attribute.isAttributeNameEqualTo;public class AssetDatapointResourceImpl extends ManagerWebResource implements AssetDatapointResource {diff --git a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.javaindex 54417ff00..e0c8390a0 100644--- a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java@@ -8,7 +8,7 @@ import org.openremote.container.persistence.PersistenceService;import org.openremote.container.web.WebService;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.model.AttributeRef;+import org.openremote.model.attribute.AttributeRef;import org.openremote.model.asset.AssetState;import org.openremote.model.datapoint.AssetDatapoint;import org.openremote.model.datapoint.DatapointInterval;diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex b207740b4..bf2b5aa52 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -55,7 +55,7 @@ import org.openremote.manager.shared.rules.AssetRuleset;import org.openremote.manager.shared.rules.GlobalRuleset;import org.openremote.manager.shared.rules.Ruleset;import org.openremote.manager.shared.rules.TenantRuleset;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.asset.AbstractAssetUpdate;import org.openremote.model.asset.AssetEvent;import org.openremote.model.asset.AssetQuery;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 e9d30acf2..6c3c86b7f 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@@ -19,7 +19,6 @@*/package org.openremote.manager.server.rules;-import elemental.json.JsonObject;import org.apache.camel.builder.RouteBuilder;import org.drools.core.base.evaluators.TimeIntervalParser;import org.openremote.container.Container;@@ -31,18 +30,18 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.server.asset.AssetProcessingService;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.ServerAsset;+import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.manager.server.notification.NotificationService;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.manager.shared.rules.AssetRuleset;import org.openremote.manager.shared.rules.GlobalRuleset;import org.openremote.manager.shared.rules.Ruleset;import org.openremote.manager.shared.rules.TenantRuleset;import org.openremote.manager.shared.security.Tenant;import org.openremote.model.AbstractValueTimestampHolder;-import org.openremote.model.Pair;import org.openremote.model.asset.*;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;import java.util.*;import java.util.function.BiFunction;@@ -251,7 +250,7 @@ public class RulesService extends RouteBuilder implements ContainerService, ConsBiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->new AssetState(loadedAsset,- attribute.copy()+ attribute.deepCopy());Asset loadedAsset;@@ -291,7 +290,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// which facts to retract and which to insertList<AssetAttribute> oldFactAttributes =attributesFromJson(- (JsonObject) persistenceEvent.getPreviousState()[attributesIndex],+ (ObjectValue) persistenceEvent.getPreviousState()[attributesIndex],asset.getId()).filter(AssetAttribute::isRuleState)@@ -299,7 +298,7 @@ public class RulesService extends RouteBuilder implements ContainerService, ConsList<AssetAttribute> newFactAttributes =attributesFromJson(- (JsonObject) persistenceEvent.getCurrentState()[attributesIndex],+ (ObjectValue) persistenceEvent.getCurrentState()[attributesIndex],asset.getId()).filter(AssetAttribute::isRuleState)@@ -311,10 +310,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.stream().filter(oldFactAttribute -> newFactAttributes.stream()- .noneMatch(newFactAttribute -> JsonUtil.equals( // Ignore the timestamp in comparison- oldFactAttribute.getJsonObject(),- newFactAttribute.getJsonObject(),- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME))+ .noneMatch(newFactAttribute ->+ oldFactAttribute.getObjectValue().equalsIgnoreKeys(+ newFactAttribute.getObjectValue(),+ AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME+ )));@@ -331,10 +331,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.filter(newFactAttribute -> oldFactAttributes.stream().noneMatch(oldFactAttribute ->- JsonUtil.equals( // Ignore the timestamp in comparison- oldFactAttribute.getJsonObject(),- newFactAttribute.getJsonObject(),- Collections.singletonList(AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)+ oldFactAttribute.getObjectValue().equalsIgnoreKeys(+ newFactAttribute.getObjectValue(),+ AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME)));diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex ce0069dba..8080a9c9a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -20,7 +20,6 @@package org.openremote.manager.server.setup.builtin;import com.vividsolutions.jts.geom.Coordinate;-import elemental.json.Json;import org.openremote.agent3.protocol.simulator.SimulatorProtocol;import org.openremote.agent3.protocol.simulator.element.ColorSimulatorElement;import org.openremote.agent3.protocol.simulator.element.DecimalSimulatorElement;@@ -30,12 +29,12 @@ import org.openremote.container.Container;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.setup.AbstractManagerSetup;import org.openremote.manager.shared.security.Tenant;-import org.openremote.model.*;+import org.openremote.model.Constants;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.AssetState;-import org.openremote.model.units.AttributeUnits;-import org.openremote.model.units.ColorRGB;+import org.openremote.model.attribute.*;+import org.openremote.model.value.Values;import java.time.LocalDateTime;import java.time.ZoneId;@@ -43,11 +42,11 @@ import java.time.ZonedDateTime;import java.util.Arrays;import java.util.List;-import static org.openremote.model.AttributeType.*;import static org.openremote.model.asset.AssetMeta.ABOUT;import static org.openremote.model.asset.AssetMeta.LABEL;import static org.openremote.model.asset.AssetType.*;import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;+import static org.openremote.model.attribute.AttributeType.*;public class ManagerDemoSetup extends AbstractManagerSetup {@@ -94,25 +93,25 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartOffice.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));smartOffice.setType(BUILDING);List<AssetAttribute> smartOfficeAttributes = Arrays.asList(- new AssetAttribute("geoStreet", STRING, Json.create("Torenallee 20"))+ new AssetAttribute("geoStreet", STRING, Values.create("Torenallee 20")).setMeta(- new MetaItem(LABEL, Json.create("Street")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet"))+ new MetaItem(LABEL, Values.create("Street")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))),- new AssetAttribute("geoPostalCode", AttributeType.INTEGER, Json.create(5617))+ new AssetAttribute("geoPostalCode", AttributeType.INTEGER, Values.create(5617)).setMeta(- new MetaItem(LABEL, Json.create("Postal Code")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode"))+ new MetaItem(LABEL, Values.create("Postal Code")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))),- new AssetAttribute("geoCity", STRING, Json.create("Eindhoven"))+ new AssetAttribute("geoCity", STRING, Values.create("Eindhoven")).setMeta(- new MetaItem(LABEL, Json.create("City")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity"))+ new MetaItem(LABEL, Values.create("City")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))),- new AssetAttribute("geoCountry", STRING, Json.create("Netherlands"))+ new AssetAttribute("geoCountry", STRING, Values.create("Netherlands")).setMeta(- new MetaItem(LABEL, Json.create("Country")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry"))+ new MetaItem(LABEL, Values.create("Country")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))));@@ -137,11 +136,11 @@ public class ManagerDemoSetup extends AbstractManagerSetup {.setMeta(new MetaItem(SimulatorProtocol.CONFIG_MODE,- Json.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())+ Values.create(SimulatorProtocol.Mode.WRITE_THROUGH_DELAYED.toString())),new MetaItem(SimulatorProtocol.CONFIG_WRITE_DELAY_MILLISECONDS,- Json.create(500)+ Values.create(500))));@@ -151,74 +150,68 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset thing = new ServerAsset("Demo Thing", THING, agent);thing.setLocation(geometryFactory.createPoint(new Coordinate(5.460315214821094, 51.44541688237109)));thing.setAttributes(- new AssetAttribute("light1Toggle", BOOLEAN, Json.create(true))+ new AssetAttribute("light1Toggle", BOOLEAN, Values.create(true)).setMeta(new Meta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The switch for the light in the living room")),+ Values.create("The switch for the light in the living room")),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toJsonValue()),+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(SwitchSimulatorElement.ELEMENT_NAME)+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(SwitchSimulatorElement.ELEMENT_NAME)))),new AssetAttribute("light1Dimmer", INTEGER) // No initial value!.setMeta(new Meta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The dimmer for the light in the living room")),+ Values.create("The dimmer for the light in the living room")),new MetaItem(AssetMeta.RANGE_MIN,- Json.create(0)),+ Values.create(0)),new MetaItem(AssetMeta.RANGE_MAX,- Json.create(100)),+ Values.create(100)),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toJsonValue()),+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(IntegerSimulatorElement.ELEMENT_NAME_RANGE)),+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(IntegerSimulatorElement.ELEMENT_NAME_RANGE)),new MetaItem(- SimulatorProtocol.CONFIG_MODE, Json.create(true))+ SimulatorProtocol.CONFIG_MODE, Values.create(true)))),- new AssetAttribute("light1Color", INTEGER_ARRAY, new ColorRGB(88, 123, 88).asJsonValue())+ new AssetAttribute("light1Color", COLOR_RGB, new ColorRGB(88, 123, 88).asArrayValue()).setMeta(new Meta(- new MetaItem(- AssetMeta.UNITS,- Json.create(AttributeUnits.COLOR_RGB.toString())),new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The color of the living room light")),+ Values.create("The color of the living room light")),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toJsonValue()),+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(ColorSimulatorElement.ELEMENT_NAME))+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(ColorSimulatorElement.ELEMENT_NAME)))),- new AssetAttribute("light1PowerConsumption", DECIMAL, Json.create(12.345))+ new AssetAttribute("light1PowerConsumption", ENERGY_KWH, Values.create(12.345)).setMeta(new Meta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The total power consumption of the living room light")),+ Values.create("The total power consumption of the living room light")),new MetaItem(AssetMeta.READ_ONLY,- Json.create(true)),+ Values.create(true)),new MetaItem(AssetMeta.FORMAT,- Json.create("%3d kWh")),- new MetaItem(- AssetMeta.UNITS,- Json.create(AttributeUnits.ENERGY_KWH.name())),+ Values.create("%3d kWh")),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(agent.getId(), agentProtocolConfigName).toJsonValue()),+ new AttributeRef(agent.getId(), agentProtocolConfigName).toArrayValue()),new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(DecimalSimulatorElement.ELEMENT_NAME)),+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(DecimalSimulatorElement.ELEMENT_NAME)),new MetaItem(- AssetMeta.STORE_DATA_POINTS.getUrn(), Json.create(true))+ AssetMeta.STORE_DATA_POINTS.getUrn(), Values.create(true)))));@@ -229,55 +222,56 @@ public class ManagerDemoSetup extends AbstractManagerSetup {thing = assetStorageService.find(thingId, true);ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());- AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption").get();+ AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption")+ .orElseThrow(() -> new RuntimeException("Invalid test data"));assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(0.11), now.minusDays(80).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(1.22), now.minusDays(40).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(2.33), now.minusDays(20).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(3.44), now.minusDays(10).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(4.55), now.minusDays(8).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);- light1PowerConsumptionAttribute.setValue(Json.create(5.66), now.minusDays(6).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(6.77), now.minusDays(3).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(7.88), now.minusDays(1).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(8.99), now.minusHours(10).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(9.11), now.minusHours(5).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(10.22), now.minusHours(2).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(11.33), now.minusHours(1).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));- light1PowerConsumptionAttribute.setValue(Json.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute));// ################################ Demo assets for 'customerA' realm ###################################@@ -288,25 +282,25 @@ public class ManagerDemoSetup extends AbstractManagerSetup {smartHome.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));smartHome.setType(BUILDING);smartHome.setAttributes(- new AssetAttribute("geoStreet", STRING, Json.create("Wilhelminaplein 21C"))+ new AssetAttribute("geoStreet", STRING, Values.create("Wilhelminaplein 21C")).setMeta(- new MetaItem(LABEL, Json.create("Street")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet"))+ new MetaItem(LABEL, Values.create("Street")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))),- new AssetAttribute("geoPostalCode", AttributeType.INTEGER, Json.create(5611))+ new AssetAttribute("geoPostalCode", AttributeType.INTEGER, Values.create(5611)).setMeta(- new MetaItem(LABEL, Json.create("Postal Code")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode"))+ new MetaItem(LABEL, Values.create("Postal Code")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))),- new AssetAttribute("geoCity", STRING, Json.create("Eindhoven"))+ new AssetAttribute("geoCity", STRING, Values.create("Eindhoven")).setMeta(- new MetaItem(LABEL, Json.create("City")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity"))+ new MetaItem(LABEL, Values.create("City")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))),- new AssetAttribute("geoCountry", STRING, Json.create("Netherlands"))+ new AssetAttribute("geoCountry", STRING, Values.create("Netherlands")).setMeta(- new MetaItem(LABEL, Json.create("Country")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry"))+ new MetaItem(LABEL, Values.create("Country")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))));smartHome = assetStorageService.merge(smartHome);@@ -315,169 +309,169 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset apartment1 = new ServerAsset("Apartment 1", RESIDENCE, smartHome);apartment1.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1.setAttributes(- new AssetAttribute("alarmEnabled", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("alarmEnabled", AttributeType.BOOLEAN, Values.create(false)).setMeta(new Meta(- new MetaItem(AssetMeta.LABEL, Json.create("Alarm Enabled")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Send notifications when presence is detected")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Alarm Enabled")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Send notifications when presence is detected")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))),new AssetAttribute("vacationDays", AttributeType.INTEGER, null).setMeta(new Meta(- new MetaItem(AssetMeta.LABEL, Json.create("Vacation Days")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Enable vacation mode for given days")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Vacation Days")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Enable vacation mode for given days")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))),- new AssetAttribute("autoSceneSchedule", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("autoSceneSchedule", AttributeType.BOOLEAN, Values.create(false)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Automatic scene schedule")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Predict presence and automatically adjust scene schedule")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Automatic scene schedule")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Predict presence and automatically adjust scene schedule")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("lastExecutedScene", AttributeType.STRING, Json.create("HOME"))+ new AssetAttribute("lastExecutedScene", AttributeType.STRING, Values.create("HOME")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Last executed scene")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Last executed scene")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneMONDAY", AttributeType.STRING, Json.create("06:45:00"))+ new AssetAttribute("homeSceneMONDAY", AttributeType.STRING, Values.create("06:45:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Monday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Monday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneMONDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("awaySceneMONDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Monday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Monday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneMONDAY", AttributeType.STRING, Json.create("17:30:00"))+ new AssetAttribute("eveningSceneMONDAY", AttributeType.STRING, Values.create("17:30:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Monday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Monday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneMONDAY", AttributeType.STRING, Json.create("22:00:00"))+ new AssetAttribute("nightSceneMONDAY", AttributeType.STRING, Values.create("22:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Monday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Monday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneTUESDAY", AttributeType.STRING, Json.create("06:45:00"))+ new AssetAttribute("homeSceneTUESDAY", AttributeType.STRING, Values.create("06:45:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Tuesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Tuesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneTUESDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("awaySceneTUESDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Tuesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Tuesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneTUESDAY", AttributeType.STRING, Json.create("17:30:00"))+ new AssetAttribute("eveningSceneTUESDAY", AttributeType.STRING, Values.create("17:30:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Tuesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Tuesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneTUESDAY", AttributeType.STRING, Json.create("22:00:00"))+ new AssetAttribute("nightSceneTUESDAY", AttributeType.STRING, Values.create("22:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Tuesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Tuesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneWEDNESDAY", AttributeType.STRING, Json.create("06:45:00"))+ new AssetAttribute("homeSceneWEDNESDAY", AttributeType.STRING, Values.create("06:45:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Wednesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Wednesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneWEDNESDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("awaySceneWEDNESDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Wednesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Wednesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneWEDNESDAY", AttributeType.STRING, Json.create("17:30:00"))+ new AssetAttribute("eveningSceneWEDNESDAY", AttributeType.STRING, Values.create("17:30:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Wednesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Wednesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneWEDNESDAY", AttributeType.STRING, Json.create("22:00:00"))+ new AssetAttribute("nightSceneWEDNESDAY", AttributeType.STRING, Values.create("22:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Wednesday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Wednesday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneTHURSDAY", AttributeType.STRING, Json.create("06:45:00"))+ new AssetAttribute("homeSceneTHURSDAY", AttributeType.STRING, Values.create("06:45:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Thursday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Thursday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneTHURSDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("awaySceneTHURSDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Thursday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Thursday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneTHURSDAY", AttributeType.STRING, Json.create("17:30:00"))+ new AssetAttribute("eveningSceneTHURSDAY", AttributeType.STRING, Values.create("17:30:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Thursday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Thursday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneTHURSDAY", AttributeType.STRING, Json.create("22:00:00"))+ new AssetAttribute("nightSceneTHURSDAY", AttributeType.STRING, Values.create("22:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Thursday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Thursday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneFRIDAY", AttributeType.STRING, Json.create("06:45:00"))+ new AssetAttribute("homeSceneFRIDAY", AttributeType.STRING, Values.create("06:45:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Friday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Friday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneFRIDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("awaySceneFRIDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Friday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Friday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneFRIDAY", AttributeType.STRING, Json.create("16:00:00"))+ new AssetAttribute("eveningSceneFRIDAY", AttributeType.STRING, Values.create("16:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Friday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Friday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneFRIDAY", AttributeType.STRING, Json.create("23:00:00"))+ new AssetAttribute("nightSceneFRIDAY", AttributeType.STRING, Values.create("23:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Friday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Friday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneSATURDAY", AttributeType.STRING, Json.create("07:30:00"))+ new AssetAttribute("homeSceneSATURDAY", AttributeType.STRING, Values.create("07:30:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Saturday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Saturday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneSATURDAY", AttributeType.STRING, Json.createNull())+ new AssetAttribute("awaySceneSATURDAY", AttributeType.STRING, null).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Saturday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Saturday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneSATURDAY", AttributeType.STRING, Json.create("18:00:00"))+ new AssetAttribute("eveningSceneSATURDAY", AttributeType.STRING, Values.create("18:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Saturday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Saturday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneSATURDAY", AttributeType.STRING, Json.create("23:00:00"))+ new AssetAttribute("nightSceneSATURDAY", AttributeType.STRING, Values.create("23:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Saturday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Saturday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("homeSceneSUNDAY", AttributeType.STRING, Json.create("08:00:00"))+ new AssetAttribute("homeSceneSUNDAY", AttributeType.STRING, Values.create("08:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Waking up on Sunday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Waking up on Sunday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("awaySceneSUNDAY", AttributeType.STRING, Json.createNull())+ new AssetAttribute("awaySceneSUNDAY", AttributeType.STRING, null).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to work on Sunday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to work on Sunday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("eveningSceneSUNDAY", AttributeType.STRING, Json.create("18:00:00"))+ new AssetAttribute("eveningSceneSUNDAY", AttributeType.STRING, Values.create("18:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Back from work on Sunday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Back from work on Sunday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("nightSceneSUNDAY", AttributeType.STRING, Json.create("22:00:00"))+ new AssetAttribute("nightSceneSUNDAY", AttributeType.STRING, Values.create("22:00:00")).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Going to bed on Sunday")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Going to bed on Sunday")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))));apartment1 = assetStorageService.merge(apartment1);@@ -486,29 +480,29 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset apartment1Livingroom = new ServerAsset("Living Room", ROOM, apartment1);apartment1Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment1Livingroom.setAttributes(- new AssetAttribute("motionCount", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("motionCount", AttributeType.INTEGER, Values.create(0)).setMeta(new Meta(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Count")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Sensor that increments a counter when motion is detected")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true)),- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Motion Count")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Sensor that increments a counter when motion is detected")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)),+ new MetaItem(AssetMeta.RULE_EVENT, Values.create(true)))),- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Values.create(false)).setMeta(new Meta(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Someone is currently present in the room")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Presence Detected")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Someone is currently present in the room")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))),new AssetAttribute("lastPresenceDetected", AttributeType.DECIMAL, null).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Last Presence Timestamp")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("Timestamp of last detected presence")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Last Presence Timestamp")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Timestamp of last detected presence")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("co2Level", AttributeType.DECIMAL, Json.create(450))+ new AssetAttribute("co2Level", AttributeType.DECIMAL, Values.create(450)).setMeta(new Meta(- new MetaItem(AssetMeta.LABEL, Json.create("CO2 Level")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("CO2 Level")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))));apartment1Livingroom = assetStorageService.merge(apartment1Livingroom);@@ -520,38 +514,38 @@ public class ManagerDemoSetup extends AbstractManagerSetup {.setMeta(new MetaItem(AssetMeta.LABEL,- Json.create("Current Temperature")),+ Values.create("Current Temperature")),new MetaItem(AssetMeta.RULE_STATE,- Json.create(true)),+ Values.create(true)),new MetaItem(AssetMeta.PROTECTED,- Json.create(true)),+ Values.create(true)),new MetaItem(AssetMeta.READ_ONLY,- Json.create(true)),+ Values.create(true)),new MetaItem(- Constants.NAMESPACE + ":foo:bar", Json.create("FOO")),+ Constants.NAMESPACE + ":foo:bar", Values.create("FOO")),new MetaItem(- "urn:thirdparty:bar", Json.create("BAR"))+ "urn:thirdparty:bar", Values.create("BAR"))),new AssetAttribute("comfortTemperature", DECIMAL, null).setMeta(new MetaItem(AssetMeta.LABEL,- Json.create("Comfort Temperature")),+ Values.create("Comfort Temperature")),new MetaItem(AssetMeta.RULE_STATE,- Json.create(true)),+ Values.create(true)),new MetaItem(AssetMeta.PROTECTED,- Json.create(true)),+ Values.create(true)),new MetaItem(- Constants.NAMESPACE + ":foo:bar", Json.create("FOO")),+ Constants.NAMESPACE + ":foo:bar", Values.create("FOO")),new MetaItem(- "urn:thirdparty:bar", Json.create("BAR")),+ "urn:thirdparty:bar", Values.create("BAR")),new MetaItem(- SimulatorProtocol.SIMULATOR_ELEMENT, Json.create(DecimalSimulatorElement.ELEMENT_NAME)+ SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(DecimalSimulatorElement.ELEMENT_NAME))));@@ -561,12 +555,12 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset apartment2 = new ServerAsset("Apartment 2", RESIDENCE, smartHome);apartment2.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2.setAttributes(- new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Json.create(true))+ new AssetAttribute("allLightsOffSwitch", AttributeType.BOOLEAN, Values.create(true)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("All Lights Off Switch")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("When triggered, turns all lights in the apartment off")),- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true)),- new MetaItem(AssetMeta.RULE_EVENT_EXPIRES, Json.create("10s"))+ new MetaItem(AssetMeta.LABEL, Values.create("All Lights Off Switch")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("When triggered, turns all lights in the apartment off")),+ new MetaItem(AssetMeta.RULE_EVENT, Values.create(true)),+ new MetaItem(AssetMeta.RULE_EVENT_EXPIRES, Values.create("10s"))));apartment2 = assetStorageService.merge(apartment2);@@ -575,37 +569,37 @@ public class ManagerDemoSetup extends AbstractManagerSetup {ServerAsset apartment2Livingroom = new ServerAsset("Living Room", ROOM, apartment2);apartment2Livingroom.setLocation(geometryFactory.createPoint(new Coordinate(5.470945, 51.438000)));apartment2Livingroom.setAttributes(- new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("motionSensor", AttributeType.BOOLEAN, Values.create(false)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Motion Sensor")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create("PIR sensor that sends 'true' when motion is sensed")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true)),- new MetaItem(AssetMeta.RULE_EVENT, Json.create(true))+ new MetaItem(AssetMeta.LABEL, Values.create("Motion Sensor")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("PIR sensor that sends 'true' when motion is sensed")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)),+ new MetaItem(AssetMeta.RULE_EVENT, Values.create(true))),- new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("presenceDetected", AttributeType.BOOLEAN, Values.create(false)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Presence Detected")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ new MetaItem(AssetMeta.LABEL, Values.create("Presence Detected")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Someone is currently present in the room")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),new AssetAttribute("lastPresenceDetected", AttributeType.DECIMAL, null).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Last Presence Timestamp")),- new MetaItem(AssetMeta.DESCRIPTION, Json.create(+ new MetaItem(AssetMeta.LABEL, Values.create("Last Presence Timestamp")),+ new MetaItem(AssetMeta.DESCRIPTION, Values.create("Timestamp of last detected presence")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Json.create(true))+ new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Values.create(true)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Light Switch")),- new MetaItem(AssetMeta.RULE_STATE, Json.create(false))+ new MetaItem(AssetMeta.LABEL, Values.create("Light Switch")),+ new MetaItem(AssetMeta.RULE_STATE, Values.create(false))),- new AssetAttribute("windowOpen", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("windowOpen", AttributeType.BOOLEAN, Values.create(false)).setMeta(- new MetaItem(AssetMeta.LABEL, Json.create("Window Open"))+ new MetaItem(AssetMeta.LABEL, Values.create("Window Open"))));apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drlindex 2a7d26200..cdb095247 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl@@ -2,7 +2,8 @@ package org.openremote.test.rules;import org.openremote.model.*;import org.openremote.model.asset.*-import elemental.json.Json;+import org.openremote.model.value.Values+import org.openremote.model.attribute.AttributeEventglobal java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;@@ -10,12 +11,12 @@ global org.openremote.model.rules.Assets assets;rule "Switch room lights off when apartment ALL LIGHTS OFF push-button is pressed"when// In an asset of type RESIDENCE the All Lights Off push-button is pressed, which sends a 'true' value- $e: AssetEvent(attributeName == "allLightsOffSwitch", type == AssetType.RESIDENCE, value.asBoolean() )+ $e: AssetEvent(attributeName == "allLightsOffSwitch", type == AssetType.RESIDENCE, valueAsBoolean )thenassets.query() // Execute a query to get "other" assets.parent($e.getId()) // Where parent is the apartment in LHS.type(AssetType.ROOM) // And the children are of type ROOM.applyResults(assetIds -> assetIds.forEach(assetId -> assets.dispatch( // For each asset ID in result...- new AttributeEvent(assetId, "lightSwitch", Json.create(false)) // Dispatch an event that turns the switch off+ new AttributeEvent(assetId, "lightSwitch", Values.create(false)) // Dispatch an event that turns the switch off)));enddiff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drlindex 5bb56fa98..52872993f 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionCounter.drl@@ -3,7 +3,8 @@ package org.openremote.test.rules;import java.util.ArrayList;import org.openremote.model.*;import org.openremote.model.asset.*-import elemental.json.Json;+import org.openremote.model.value.Values+import org.openremote.model.attribute.AttributeEvent;global java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;@@ -20,17 +21,17 @@ when// A room has a motion counter$room : AssetState(type == AssetType.ROOM, attributeName == "motionCount")// And the presence detected flag is not set already- AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", !valueAsBoolean)// And at least 5 motion counter increments have been received in the last 10 minutesaccumulate(- AssetEvent(id == $room.id, attributeName == "motionCount", value != null, value.asNumber > 0) over window:time(10m);+ AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0) over window:time(10m);$count: count(1);$count >= 5)then// Set the presence detected flag of the roomassets.dispatch(- new AttributeEvent($room.getId(), "presenceDetected", Json.create(true))+ new AttributeEvent($room.getId(), "presenceDetected", Values.create(true)));end@@ -39,20 +40,20 @@ when// A room has a motion counter$room : AssetState(type == AssetType.ROOM, attributeName == "motionCount")// And the presence detected flag is set- AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean)// And at least 5 motion counter increments have been received in the last 10 minutesaccumulate(- AssetEvent(id == $room.id, attributeName == "motionCount", value != null, value.asNumber > 0, $ts: valueTimestamp) over window:time(10m);+ AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0, $ts: valueTimestamp) over window:time(10m);$count: count(1),$latestIncrementTimestamp: max($ts);$count >= 5)// And the latest counter increment event is newer than the recorded last presence detected time- AssetState(id == $room.id, attributeName == "lastPresenceDetected", value != null, $latestIncrementTimestamp > value.asNumber)+ AssetState(id == $room.id, attributeName == "lastPresenceDetected", $latestIncrementTimestamp > valueAsNumber)then// Update the last presence detected timestamp to the latest counter increment eventassets.dispatch(- new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($latestIncrementTimestamp))+ new AttributeEvent($room.getId(), "lastPresenceDetected", Values.create($latestIncrementTimestamp)));end@@ -62,16 +63,16 @@ when// A room has a motion counter$room: AssetState(type == AssetType.ROOM, attributeName == "motionCount")// And the presence detected flag is set- AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean)// And no motion counter increments have been received in the last 10 minutesaccumulate(- AssetEvent(id == $room.id, attributeName == "motionCount", value != null, value.asNumber > 0) over window:time(10m);+ AssetEvent(id == $room.id, attributeName == "motionCount", valueAsNumber > 0) over window:time(10m);$count: count(1);$count == 0)then// Clear the presence detected flag of the roomassets.dispatch(- new AttributeEvent($room.getId(), "presenceDetected", Json.create(false))+ new AttributeEvent($room.getId(), "presenceDetected", Values.create(false)));enddiff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drlindex 23817c5db..bac117d44 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresenceDetectionPIR.drl@@ -2,8 +2,9 @@ package org.openremote.test.rules;import org.openremote.model.*;import org.openremote.model.asset.*-import elemental.json.Json-import java.util.Date;+import org.openremote.model.value.Values+import java.util.Date+import org.openremote.model.attribute.AttributeEvent;global java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;@@ -20,30 +21,30 @@ when// A room has a motion sensor$room : AssetState(type == AssetType.ROOM, attributeName == "motionSensor")// And the presence detected flag is not set already- AssetState(id == $room.id, attributeName == "presenceDetected", !value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", !valueAsBoolean)// And at least 5 motion sensor triggers have been received in the last 10 minutesaccumulate(- AssetEvent(id == $room.id, attributeName == "motionSensor", value.asBoolean) over window:time(10m);+ AssetEvent(id == $room.id, attributeName == "motionSensor", valueAsBoolean) over window:time(10m);$count: count(1);$count >= 5)then// Set the presence detected flag of the roomassets.dispatch(- new AttributeEvent($room.getId(), "presenceDetected", Json.create(true))+ new AttributeEvent($room.getId(), "presenceDetected", Values.create(true)));endrule "Update the presence detected timestamp if motion sensor is triggered and we have already detected presence"when// The presence detected flag is set in a room- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", value.asBoolean)+ $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueAsBoolean)// And the motion sensor is triggered- $sensorState: AssetState(id == $room.id, attributeName == "motionSensor", value.asBoolean)+ $sensorState: AssetState(id == $room.id, attributeName == "motionSensor", valueAsBoolean)then// Update the last presence detected timestamp of the roomassets.dispatch(- new AttributeEvent($room.getId(), "lastPresenceDetected", Json.create($sensorState.getValueTimestamp()))+ new AttributeEvent($room.getId(), "lastPresenceDetected", Values.create($sensorState.getValueTimestamp())));end@@ -52,16 +53,16 @@ when// A room has a motion sensor$room: AssetState(type == AssetType.ROOM, attributeName == "motionSensor")// And the presence detected flag is set- AssetState(id == $room.id, attributeName == "presenceDetected", value.asBoolean)+ AssetState(id == $room.id, attributeName == "presenceDetected", valueAsBoolean)// And no motion sensor triggers have been received in the last 10 minutesaccumulate(- AssetEvent(id == $room.id, attributeName == "motionSensor", value.asBoolean) over window:time(10m);+ AssetEvent(id == $room.id, attributeName == "motionSensor", valueAsBoolean) over window:time(10m);$count: count(1);$count == 0)then// Clear the presence detected flag of the roomassets.dispatch(- new AttributeEvent($room.getId(), "presenceDetected", Json.create(false))+ new AttributeEvent($room.getId(), "presenceDetected", Values.create(false)));enddiff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentPresencePrediction.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentPresencePrediction.drlindex 0a1454f7c..ec0f8a559 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentPresencePrediction.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentPresencePrediction.drl@@ -2,7 +2,7 @@ package org.openremote.test.rules;import org.openremote.model.*;import org.openremote.model.asset.*-import elemental.json.Json;+import org.openremote.model.value.Values;global java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;diff --git a/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drlindex 855efa1c1..a0d5f3396 100644--- a/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl+++ b/manager/server/src/main/resources/demo/rules/DemoApartmentVacationMode.drl@@ -2,7 +2,8 @@ package org.openremote.test.rules;import org.openremote.model.*;import org.openremote.model.asset.*-import elemental.json.Json;+import org.openremote.model.value.Values+import org.openremote.model.attribute.AttributeEvent;global java.util.logging.Logger LOG;global org.openremote.model.rules.Assets assets;@@ -12,8 +13,8 @@ rule "Decrement vacation days every day 1 minute after midnight until vacation itimer (cron: 0 1 0 1/1 * ? *)when// Vacation days are more than zero, which means vacation mode is enabled- AssetState($ref: attributeRef, attributeName == "vacationDays", type == AssetType.RESIDENCE, value != null, $val: value.asNumber() > 0 )+ AssetState($ref: attributeRef, attributeName == "vacationDays", type == AssetType.RESIDENCE, $val: valueAsNumber > 0 )then// Decrement the vacation days by one- assets.dispatch( new AttributeEvent($ref, Json.create($val- 1)) );+ assets.dispatch( new AttributeEvent($ref, Values.create($val - 1)) );end\ No newline at end of filediff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.javaindex 95fa999ce..4e724b91d 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/Capability.java@@ -1,6 +1,6 @@package org.openremote.manager.shared.device;-import org.openremote.model.Attribute;+import org.openremote.model.attribute.Attribute;import java.util.List;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.javaindex d2fed53ec..5298b7cf4 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/CapabilityDefinition.java@@ -1,6 +1,6 @@package org.openremote.manager.shared.device;-import org.openremote.model.Attribute;+import org.openremote.model.attribute.Attribute;import java.util.List;diff --git a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.javaindex ab64f6503..4432d8a04 100644--- a/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java+++ b/manager/shared/src/main/java/org/openremote/manager/shared/device/DeviceResource.java@@ -19,12 +19,6 @@*/package org.openremote.manager.shared.device;-import elemental.json.Json;-import elemental.json.JsonObject;-import org.openremote.model.Attribute;-import org.openremote.model.AttributeType;-import org.openremote.model.Constants;-/*** An attribute of an asset that represents a device resource.*diff --git a/manager/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovyindex 1820b8b35..89fd66bf7 100644--- a/manager/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovy+++ b/manager/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovy@@ -27,7 +27,6 @@ import com.google.gwt.place.shared.PlaceHistoryHandler.Historianimport com.google.gwt.user.client.Windowimport com.google.gwt.user.client.ui.AcceptsOneWidgetimport com.google.web.bindery.event.shared.SimpleEventBus-import elemental.json.JsonValueimport org.jboss.resteasy.client.jaxrs.ResteasyWebTargetimport org.openremote.manager.client.mvp.AppActivityManagerimport org.openremote.manager.client.mvp.AppActivityMapper@@ -40,6 +39,7 @@ import org.openremote.model.event.Eventimport org.openremote.model.event.bus.EventBusimport org.openremote.model.event.bus.EventListenerimport org.openremote.model.event.shared.SharedEvent+import org.openremote.model.value.Valueimport org.spockframework.mock.IMockMethodimport javax.ws.rs.ClientErrorException@@ -198,9 +198,9 @@ trait GwtClientTrait {&& producesAnnotation != null&& Arrays.asList(producesAnnotation.value()).contains(APPLICATION_JSON)) {// Handle elemental JsonValue special, don't use Jackson- if (result instanceof JsonValue) {- JsonValue jsonValue = (JsonValue) result- responseText = jsonValue.toJson()+ if (result instanceof Value) {+ Value value = (Value) result+ responseText = value.toJson()} else {responseText = jsonMapper.writeValueAsString(result)}diff --git a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovyindex 536a6b66d..0f1e9e085 100644--- a/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/agent/AgentDeploymentTest.groovy@@ -1,15 +1,15 @@package org.openremote.test.agent-import elemental.json.Json-import elemental.json.JsonArray-import elemental.json.JsonTypeimport org.openremote.agent3.protocol.simulator.SimulatorProtocolimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.AttributeEvent-import org.openremote.model.units.ColorRGB+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.ColorRGB+import org.openremote.model.value.ArrayValue+import org.openremote.model.value.ValueType+import org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -34,39 +34,39 @@ class AgentDeploymentTest extends Specification implements ManagerContainerTraitassert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Toggle").asBoolean()assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer") == null// No initial value!- assert new ColorRGB(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Color") as JsonArray) == new ColorRGB(88, 123, 88)- assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption").asNumber() == 12.345d+ assert new ColorRGB(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Color") as ArrayValue) == new ColorRGB(88, 123, 88)+ assert Values.getNumber(simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption")).orElse(null) == 12.345d}when: "a client wants to change a thing attributes' value, triggering an actuator"conditions = new PollingConditions(timeout: 3, initialDelay: 1)def light1DimmerChange = new AttributeEvent(- managerDemoSetup.thingId, "light1Dimmer", Json.create(66)+ managerDemoSetup.thingId, "light1Dimmer", Values.create(66))assetProcessingService.sendAttributeEvent(light1DimmerChange)then: "the simulator state and thing attribute value should be updated (simulator reflects actuator write as sensor read)"conditions.eventually {assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer") != null- assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer").asNumber() == 66+ assert Values.getNumber(simulatorProtocol.getState(managerDemoSetup.thingId, "light1Dimmer")).orElse(null) == 66ddef thing = assetStorageService.find(managerDemoSetup.thingId, true)def attribute = thing.getAttribute("light1Dimmer")assert attribute.get().getValue().isPresent()- assert attribute.get().getValue().get().getType() == JsonType.NUMBER+ assert attribute.get().getValue().get().getType() == ValueType.NUMBERassert attribute.get().getValueAsInteger().isPresent()assert attribute.get().getValueAsInteger().get() == 66}when: "a simulated sensor changes its value"conditions = new PollingConditions(timeout: 3, initialDelay: 1)- simulatorProtocol.putState(managerDemoSetup.thingId, "light1Dimmer", Json.create(77))+ simulatorProtocol.putState(managerDemoSetup.thingId, "light1Dimmer", Values.create(77))then: "the thing attribute value should be updated"conditions.eventually {def thing = assetStorageService.find(managerDemoSetup.thingId, true)def attribute = thing.getAttribute("light1Dimmer")assert attribute.get().getValue().isPresent()- assert attribute.get().getValue().get().getType() == JsonType.NUMBER+ assert attribute.get().getValue().get().getType() == ValueType.NUMBERassert attribute.get().getValueAsInteger().isPresent()assert attribute.get().getValueAsInteger().get() == 77}diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovyindex 9127d6ede..cf2533d9a 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy@@ -1,12 +1,12 @@package org.openremote.test.assets-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.agent3.protocol.simulator.SimulatorProtocolimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.datapoint.AssetDatapointServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.AttributeRef+import org.openremote.model.attribute.AttributeRefimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -28,29 +28,29 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitthen: "the simulator elements should have the initial state"conditions.eventually {- assert simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption").asNumber() == 12.345d+ assert Values.getNumber(simulatorProtocol.getState(managerDemoSetup.thingId, "light1PowerConsumption")).orElse(null) == 12.345d}when: "a simulated sensor changes its value several times"conditions = new PollingConditions(timeout: 3, initialDelay: 1)sleep(10)- simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Json.create(13.3))+ simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3))sleep(10)- simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Json.create(14.4))+ simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(14.4))sleep(10)- simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Json.create(15.5))+ simulatorProtocol.putState(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(15.5))then: "the thing attribute value should be updated and the datapoints stored"conditions.eventually {def thing = assetStorageService.find(managerDemoSetup.thingId, true)- assert thing.getAttribute("light1PowerConsumption").get().getValueAsDecimal().get() == 15.5d+ assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAsNumber() }.orElse(null) == 15.5ddef datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))datapoints.size() > 3- datapoints.get(0).value.asNumber() == 13.3d+ Values.getNumber(datapoints.get(0).value).orElse(null) == 13.3ddatapoints.get(0).timestamp < datapoints.get(1).timestamp- datapoints.get(1).value.asNumber() == 14.4d+ Values.getNumber(datapoints.get(1).value).orElse(null) == 14.4ddatapoints.get(1).timestamp < datapoints.get(2).timestamp- datapoints.get(2).value.asNumber() == 15.5d+ Values.getNumber(datapoints.get(2).value).orElse(null) == 15.5ddatapoints.get(2).timestamp < System.currentTimeMillis()}diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovyindex 574c0eaec..2e2f09816 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy@@ -1,12 +1,12 @@package org.openremote.test.assets-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.container.util.IdentifierUtilimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.shared.asset.AssetResource-import org.openremote.model.AttributeType+import org.openremote.model.attribute.AttributeTypeimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetAttributeimport org.openremote.model.asset.AssetType@@ -70,7 +70,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitwhen: "an asset is stored with a non-empty attribute value"testAsset = assetResource.get(null, testAsset.getId())testAsset.setAttributes(- new AssetAttribute("foo", AttributeType.STRING, Json.create("bar"))+ new AssetAttribute("foo", AttributeType.STRING, Values.create("bar")))assetResource.update(null, testAsset.id, testAsset)testAsset = assetResource.get(null, testAsset.getId())diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex 46866fbe7..a96f03578 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -1,13 +1,13 @@package org.openremote.test.assets-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.container.util.IdentifierUtilimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.shared.asset.AssetResource-import org.openremote.model.AttributeType-import org.openremote.model.Meta+import org.openremote.model.attribute.AttributeType+import org.openremote.model.attribute.Metaimport org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetType@@ -21,7 +21,7 @@ import static org.openremote.container.util.MapAccess.getStringimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORDimport static org.openremote.manager.server.setup.AbstractKeycloakSetup.SETUP_KEYCLOAK_ADMIN_PASSWORD_DEFAULTimport static org.openremote.model.Constants.*-import static org.openremote.model.MetaItem.isMetaNameEqualTo+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualToclass AssetPermissionsTest extends Specification implements ManagerContainerTrait {@@ -161,38 +161,38 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 404when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())then: "result should match"def assetconditions.eventually {asset = assetResource.get(null, managerDemoSetup.smartOfficeId)assert asset.getAttribute("geoStreet").get().getValue().isPresent()- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Json.create("Teststreet 123").toJson()+ assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()}when: "an non-existent attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Values.create("Teststreet 123").toJson())then: "the attribute should be not found"ex = thrown()ex.response.status == 404when: "an non-existent attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "doesnotexist", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "doesnotexist", Values.create("Teststreet 123").toJson())then: "the attribute should be not found"ex = thrown()ex.response.status == 404when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Values.create("Teststreet 456").toJson())then: "result should match"conditions.eventually {asset = assetResource.get(null, managerDemoSetup.smartHomeId)assert asset.getAttribute("geoStreet").get().getValue().isPresent()- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Json.create("Teststreet 456").toJson()+ assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 456").toJson()}cleanup: "the server should be stopped"@@ -335,17 +335,17 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())then: "result should match"conditions.eventually {def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)assert asset.getAttribute("geoStreet").get().getValue().isPresent()- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Json.create("Teststreet 123").toJson()+ assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()}when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 456").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Values.create("Teststreet 456").toJson())then: "access should be forbidden"ex = thrown()@@ -469,14 +469,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartHomeId, "geoStreet", Values.create("Teststreet 123").toJson())then: "access should be forbidden"ex = thrown()ex.response.status == 403when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 456").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 456").toJson())then: "access should be forbidden"ex = thrown()@@ -590,7 +590,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiprotectedAttributes.size() == 2def currentTemperature = apartment1LivingroomThermostat.getAttribute("currentTemperature").get()currentTemperature.getType().get() == AttributeType.DECIMAL- !currentTemperature.getValueAsDecimal().isPresent()+ !currentTemperature.getValue().isPresent()Meta protectedMeta = currentTemperature.getMeta()protectedMeta.size() == 3protectedMeta.stream().filter(isMetaNameEqualTo(AssetMeta.LABEL)).findFirst().get().getValueAsString().get() == "Current Temperature"@@ -648,52 +648,52 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "a private asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "lightSwitch", Json.create(false).toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "lightSwitch", Values.create(false).toJson())then: "the attribute should be not found"ex = thrown()ex.response.status == 404when: "a protected read-only asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "currentTemperature", Json.create(22.123).toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "currentTemperature", Values.create(22.123).toJson())then: "the request should be forbidden"ex = thrown()ex.response.status == 403when: "a protected asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Json.create(22.123).toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomThermostatId, "comfortTemperature", Values.create(22.123).toJson())then: "result should match"conditions.eventually {def asset = assetResource.get(null, managerDemoSetup.apartment1LivingroomThermostatId)assert asset.getAttribute("comfortTemperature").get().getValue().isPresent()- assert asset.getAttribute("comfortTemperature").get().getValue().get().toJson() == Json.create(22.123).toJson()+ assert asset.getAttribute("comfortTemperature").get().getValue().get().toJson() == Values.create(22.123).toJson()}when: "an attribute is written on a non-existent user asset"- assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", Json.create(false).toJson())+ assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", Values.create(false).toJson())then: "the attribute should be not found"ex = thrown()ex.response.status == 404when: "an non-existent attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "doesnotexist", Json.create("foo").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment1LivingroomId, "doesnotexist", Values.create("foo").toJson())then: "the attribute should be not found"ex = thrown()ex.response.status == 404when: "an asset attribute is written on a non-user asset"- assetResource.writeAttributeValue(null, managerDemoSetup.apartment3LivingroomId, "lightSwitch", Json.create(false).toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.apartment3LivingroomId, "lightSwitch", Values.create(false).toJson())then: "access should be forbidden"ex = thrown()ex.response.status == 403when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Json.create("Teststreet 123").toJson())+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())then: "access should be forbidden"ex = thrown()diff --git a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex a1939b609..bad0c5203 100644--- a/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -1,6 +1,6 @@package org.openremote.test.assets-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.agent3.protocol.AbstractProtocolimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageService@@ -15,6 +15,11 @@ import org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetStateimport org.openremote.model.asset.AssetTypeimport org.openremote.model.asset.agent.ProtocolConfiguration+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.AttributeRef+import org.openremote.model.attribute.AttributeState+import org.openremote.model.attribute.AttributeType+import org.openremote.model.attribute.MetaItemimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -107,33 +112,33 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitand: "a mock thing asset is created with a valid protocol attribute, an invalid protocol attribute and a plain attribute"def mockThing = new ServerAsset("Mock Thing Asset", AssetType.THING, mockAgent)mockThing.setAttributes(- new AssetAttribute("light1Toggle", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("light1Toggle", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The switch for the light 1 in the living room")+ Values.create("The switch for the light 1 in the living room")),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef(mockAgent.getId(), "mock123").toJsonValue()+ new AttributeRef(mockAgent.getId(), "mock123").toArrayValue())),- new AssetAttribute("light2Toggle", AttributeType.BOOLEAN, Json.create(false))+ new AssetAttribute("light2Toggle", AttributeType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("The switch for the light 2 in the living room")+ Values.create("The switch for the light 2 in the living room")),new MetaItem(AssetMeta.AGENT_LINK,- new AttributeRef("INVALID AGENT ID", managerDemoSetup.agentProtocolConfigName).toJsonValue()+ new AttributeRef("INVALID AGENT ID", managerDemoSetup.agentProtocolConfigName).toArrayValue())),- new AssetAttribute("plainAttribute", AttributeType.STRING, Json.create("demo"))+ new AssetAttribute("plainAttribute", AttributeType.STRING, Values.create("demo")).setMeta(new MetaItem(AssetMeta.DESCRIPTION,- Json.create("A plain string attribute for storing information")+ Values.create("A plain string attribute for storing information"))))@@ -146,7 +151,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitwhen: "an attribute event occurs for the valid protocol attribute"def light1toggleOn = new AttributeEvent(- new AttributeState(new AttributeRef(mockThing.getId(), "light1Toggle"), Json.create(true))+ new AttributeState(new AttributeRef(mockThing.getId(), "light1Toggle"), Values.create(true)))assetProcessingService.sendAttributeEvent(light1toggleOn)@@ -157,7 +162,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert sendToActuatorEvents.size() == 1assert sendToActuatorEvents[0].entityId == mockThing.idassert sendToActuatorEvents[0].attributeName == "light1Toggle"- assert sendToActuatorEvents[0].attributeState.value.asBoolean() == true+ assert Values.getBoolean(sendToActuatorEvents[0].attributeState.currentValue.orElse(null)).orElse(null) == trueassert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}@@ -172,8 +177,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert updatesReachedEndOfProcessingChain.size() == 1assert updatesReachedEndOfProcessingChain[0].name == "Mock Thing Asset"assert updatesReachedEndOfProcessingChain[0].attributeName == "light1Toggle"- assert updatesReachedEndOfProcessingChain[0].oldValue.asBoolean() == false- assert updatesReachedEndOfProcessingChain[0].value.asBoolean() == true+ assert Values.getBoolean(updatesReachedEndOfProcessingChain[0].oldValue).orElse(null) == false+ assert Values.getBoolean(updatesReachedEndOfProcessingChain[0].value).orElse(null) == trueassert updatesReachedEndOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}//endregion@@ -183,7 +188,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitupdatesReachedEndOfProcessingChain.clear()sendToActuatorEvents.clear()def light2toggleOn = new AttributeEvent(- new AttributeState(new AttributeRef(mockThing.getId(), "light2Toggle"), Json.create(true))+ new AttributeState(new AttributeRef(mockThing.getId(), "light2Toggle"), Values.create(true)))assetProcessingService.sendAttributeEvent(light2toggleOn)@@ -204,7 +209,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitupdatesReachedEndOfProcessingChain.clear()sendToActuatorEvents.clear()def plainAttributeTest = new AttributeEvent(- new AttributeState(new AttributeRef(mockThing.getId(), "plainAttribute"), Json.create("test"))+ new AttributeState(new AttributeRef(mockThing.getId(), "plainAttribute"), Values.create("test")))assetProcessingService.sendAttributeEvent(plainAttributeTest)@@ -215,8 +220,8 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert updatesReachedEndOfProcessingChain.size() == 1assert updatesReachedEndOfProcessingChain[0].name == "Mock Thing Asset"assert updatesReachedEndOfProcessingChain[0].attributeName == "plainAttribute"- assert updatesReachedEndOfProcessingChain[0].oldValue.asString() == "demo"- assert updatesReachedEndOfProcessingChain[0].value.asString() == "test"+ assert Values.getString(updatesReachedEndOfProcessingChain[0].oldValue).orElse(null) == "demo"+ assert Values.getString(updatesReachedEndOfProcessingChain[0].value).orElse(null) == "test"assert updatesReachedEndOfProcessingChain[0].error == nullassert updatesReachedEndOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}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.groovydeleted file mode 100644index 21ad898be..000000000--- a/manager/test/src/test/groovy/org/openremote/test/json/JsonEqualityTest.groovy+++ /dev/null@@ -1,161 +0,0 @@-package org.openremote.test.json--import elemental.json.Json-import elemental.json.JsonArray-import elemental.json.JsonObject-import elemental.json.JsonValue-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(null, null)- JsonUtil.hashCode(null) == JsonUtil.hashCode(null)-- !JsonUtil.equals(null, Json.create(123))- JsonUtil.hashCode(null) != JsonUtil.hashCode(Json.create(123))-- !JsonUtil.equals(null, Json.create(false))- JsonUtil.hashCode(null) != JsonUtil.hashCode(Json.create(false))-- !JsonUtil.equals(null, Json.create(true))- JsonUtil.hashCode(null) != JsonUtil.hashCode(Json.create(true))-- !JsonUtil.equals(null, Json.create("abc"))- JsonUtil.hashCode(null) != 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"), null)- JsonUtil.hashCode(Json.create("abc")) != JsonUtil.hashCode(null)-- !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(), null)- JsonUtil.hashCode(Json.createArray()) != JsonUtil.hashCode(null)-- 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.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(null, Json.createObject())- JsonUtil.hashCode(null) != 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/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex 749b297f5..c0915f77f 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -1,6 +1,6 @@package org.openremote.test.rules-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.asset.ServerAsset@@ -13,12 +13,11 @@ import org.openremote.manager.server.setup.builtin.ManagerDemoSetupimport org.openremote.manager.shared.rules.AssetRulesetimport org.openremote.manager.shared.rules.Ruleset.DeploymentStatusimport org.openremote.manager.shared.rules.TenantRuleset-import org.openremote.model.AttributeEvent-import org.openremote.model.AttributeType-import org.openremote.model.Meta-import org.openremote.model.MetaItem+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.AttributeType+import org.openremote.model.attribute.Meta+import org.openremote.model.attribute.MetaItemimport org.openremote.model.asset.AssetAttribute-import org.openremote.model.asset.AssetEventimport org.openremote.model.asset.AssetMetaimport org.openremote.model.asset.AssetTypeimport org.openremote.test.ManagerContainerTrait@@ -98,7 +97,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerand: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to true"def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -119,7 +118,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to false"resetRuleExecutionLoggers()def apartment2LivingroomLightSwitchChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "lightSwitch", Json.create(false)+ managerDemoSetup.apartment2LivingroomId, "lightSwitch", Values.create(false))assetProcessingService.sendAttributeEvent(apartment2LivingroomLightSwitchChange)@@ -129,7 +128,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"resetRuleExecutionLoggers()def apartment2LivingRoomWindowOpenChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "windowOpen", Json.create(true)+ managerDemoSetup.apartment2LivingroomId, "windowOpen", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomWindowOpenChange)@@ -146,7 +145,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event with the same value as current value is pushed into the system"resetRuleExecutionLoggers()apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -197,7 +196,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerand: "an attribute event occurs"apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Json.create(false)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(false))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)@@ -252,9 +251,9 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerdef asset = new ServerAsset("Kitchen", AssetType.ROOM, apartment2)asset.setRealmId(keycloakDemoSetup.customerATenant.getId())def attributes = [- new AssetAttribute("testString", AttributeType.STRING, Json.create("test"))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test")).setMeta(new Meta(- new MetaItem(AssetMeta.RULE_STATE, Json.create(true)))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))))]asset.setAttributes(attributes)@@ -283,11 +282,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"resetRuleExecutionLoggers()attributes = [- new AssetAttribute("testString", AttributeType.STRING, Json.create("test"))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test")).setMeta(- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("testInteger", AttributeType.INTEGER, Values.create(0))]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -309,11 +308,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to set the RULE_STATE to false"attributes = [- new AssetAttribute("testString", AttributeType.STRING, Json.create("test"))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test")).setMeta(- new MetaItem(AssetMeta.RULE_STATE, Json.create(false))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(false))),- new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("testInteger", AttributeType.INTEGER, Values.create(0))]asset.setAttributes(attributes)asset = assetStorageService.merge(asset)@@ -336,13 +335,13 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "the Kitchen room asset is modified to set all attributes to RULE_STATE = true"resetRuleExecutionLoggers()attributes = [- new AssetAttribute("testString", AttributeType.STRING, Json.create("test"))+ new AssetAttribute("testString", AttributeType.STRING, Values.create("test")).setMeta(- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true))),- new AssetAttribute("testInteger", AttributeType.INTEGER, Json.create(0))+ new AssetAttribute("testInteger", AttributeType.INTEGER, Values.create(0)).setMeta(- new MetaItem(AssetMeta.RULE_STATE, Json.create(true))+ new MetaItem(AssetMeta.RULE_STATE, Values.create(true)))]asset.setAttributes(attributes)@@ -444,7 +443,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerwhen: "an attribute event occurs"def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Json.create(true)+ managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true))assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovyindex 6bf3cb815..468607927 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy@@ -1,14 +1,13 @@package org.openremote.test.rules.apartment-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.rules.RulesEngineimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.setup.SetupService-import org.openremote.manager.server.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.AttributeEvent+import org.openremote.model.attribute.AttributeEventimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -50,7 +49,7 @@ class ApartmentAllLightsOffTest extends Specification implements ManagerContainewhen: "the ALL LIGHTS OFF push-button is pressed for an apartment"setPseudoClocksToRealTime(container, apartment2Engine)def lightsOffEvent = new AttributeEvent(- managerDemoSetup.apartment2Id, "allLightsOffSwitch", Json.create(true), getClockTimeOf(container)+ managerDemoSetup.apartment2Id, "allLightsOffSwitch", Values.create(true), getClockTimeOf(container))assetProcessingService.sendAttributeEvent(lightsOffEvent)diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovyindex 1fb6f6c77..714d2e904 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy@@ -1,13 +1,13 @@package org.openremote.test.rules.apartment-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.rules.RulesEngineimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.AttributeEvent+import org.openremote.model.attribute.AttributeEventimport org.openremote.model.asset.AssetEventimport org.openremote.test.ManagerContainerTraitimport spock.lang.Ignore@@ -60,7 +60,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 5 triggers each 3 minutes apartfor (i in 1..5) {def motionCountIncrement = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionCount", Json.create(i), getClockTimeOf(apartment1Engine)+ managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine))assetProcessingService.sendAttributeEvent(motionCountIncrement)new PollingConditions(timeout: 5, initialDelay: 0.2, delay: 0.2).eventually {@@ -90,7 +90,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 5 increments each 1 minute apartfor (i in 1..5) {def motionCountIncrement = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionCount", Json.create(i), getClockTimeOf(apartment1Engine)+ managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine))expectedLastPresenceTimestamp = motionCountIncrement.timestampassetProcessingService.sendAttributeEvent(motionCountIncrement)@@ -113,7 +113,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 20 increments each 90 seconds apartfor (i in 1..20) {def motionCountIncrement = new AttributeEvent(- managerDemoSetup.apartment1LivingroomId, "motionCount", Json.create(i), getClockTimeOf(apartment1Engine)+ managerDemoSetup.apartment1LivingroomId, "motionCount", Values.create(i), getClockTimeOf(apartment1Engine))expectedLastPresenceTimestamp = motionCountIncrement.timestampassetProcessingService.sendAttributeEvent(motionCountIncrement)@@ -193,7 +193,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 5 triggers each 3 minutes apartfor (i in 1..5) {def motionSensorTrigger = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment2Engine)+ managerDemoSetup.apartment2LivingroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine))assetProcessingService.sendAttributeEvent(motionSensorTrigger)new PollingConditions(timeout: 5, initialDelay: 0.2, delay: 0.2).eventually {@@ -223,7 +223,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 5 triggers each 1 minute apartfor (i in 1..5) {def motionSensorTrigger = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment2Engine)+ managerDemoSetup.apartment2LivingroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine))expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)@@ -246,7 +246,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon// Send 20 triggers each 90 seconds apartfor (i in 1..20) {def motionSensorTrigger = new AttributeEvent(- managerDemoSetup.apartment2LivingroomId, "motionSensor", Json.create(true), getClockTimeOf(apartment2Engine)+ managerDemoSetup.apartment2LivingroomId, "motionSensor", Values.create(true), getClockTimeOf(apartment2Engine))expectedLastPresenceTimestamp = motionSensorTrigger.timestampassetProcessingService.sendAttributeEvent(motionSensorTrigger)diff --git a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovyindex 7c465af25..763dedd6d 100644--- a/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy@@ -1,13 +1,13 @@package org.openremote.test.rules.apartment-import elemental.json.Json+import org.openremote.model.value.Valuesimport org.openremote.manager.server.asset.AssetProcessingServiceimport org.openremote.manager.server.asset.AssetStorageServiceimport org.openremote.manager.server.rules.RulesEngineimport org.openremote.manager.server.rules.RulesServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.ManagerDemoSetup-import org.openremote.model.AttributeEvent+import org.openremote.model.attribute.AttributeEventimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions@@ -45,7 +45,7 @@ class ApartmentVacationModeTest extends Specification implements ManagerContainewhen: "the vacation days are set to 5"setPseudoClocksToRealTime(container, apartment1Engine)assetProcessingService.sendAttributeEvent(new AttributeEvent(- managerDemoSetup.apartment1Id, "vacationDays", Json.create(5), getClockTimeOf(container)+ managerDemoSetup.apartment1Id, "vacationDays", Values.create(5), getClockTimeOf(container)))then: "that value should be stored"diff --git a/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy b/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovyindex 7d923b12b..67b3872f7 100644--- a/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy+++ b/manager/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy@@ -1,20 +1,18 @@package org.openremote.test.user+import org.openremote.manager.server.notification.NotificationServiceimport org.openremote.manager.server.setup.SetupServiceimport org.openremote.manager.server.setup.builtin.KeycloakDemoSetup-import org.openremote.manager.server.notification.NotificationService+import org.openremote.manager.shared.notification.NotificationResourceimport org.openremote.model.notification.ActionTypeimport org.openremote.model.notification.AlertActionimport org.openremote.model.notification.AlertNotification-import org.openremote.manager.shared.notification.NotificationResourceimport org.openremote.test.ManagerContainerTrait-import spock.lang.Ignoreimport spock.lang.Specificationimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_IDimport static org.openremote.model.Constants.MASTER_REALM-class NotificationServiceTest extends Specification implements ManagerContainerTrait {def "Store notification tokens for user devices"() {@@ -41,10 +39,10 @@ class NotificationServiceTest extends Specification implements ManagerContainerTmessage: "Message",)- def alertAction = new AlertAction();+ def alertAction = new AlertAction()alertAction.setTitle("TEST_ACTION")- alertAction.setType(ActionType.ACTUATOR)+ alertAction.setActionType(ActionType.ACTUATOR)notificationAlert.addAction(alertAction)and: "the notification resource"diff --git a/manager/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl b/manager/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drlindex cc88367c1..ba5d42c70 100644--- a/manager/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl+++ b/manager/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl@@ -1,8 +1,8 @@package org.openremote.test.rules;import org.openremote.model.*;+import org.openremote.model.value.ValueType;import org.openremote.model.asset.*;-import elemental.json.*;global java.util.logging.Logger LOG;@@ -64,7 +64,7 @@ endrule "JSON Number value types"when- AssetState(value != null, value.type == JsonType.NUMBER)+ AssetState(value != null, value.type == ValueType.NUMBER)thenreturn;enddiff --git a/model/build.gradle b/model/build.gradleindex 667e649dd..12f92681c 100644--- a/model/build.gradle+++ b/model/build.gradle@@ -3,7 +3,7 @@ apply plugin: "java"dependencies {compile "com.fasterxml.jackson.core:jackson-annotations:$jacksonVersion"compile "com.fasterxml.jackson.core:jackson-databind:$jacksonVersion"- compile "com.google.gwt:gwt-elemental:$gwtVersion"+ compile "com.google.gwt:gwt-user:$gwtVersion"compile "org.hibernate.javax.persistence:hibernate-jpa-2.1-api:$javaxPersistenceVersion"compile "org.hibernate:hibernate-core:$hibernateVersion"compile "org.jboss.logging:jboss-logging-annotations:$jbossLoggingAnnotationsVersion"diff --git a/model/src/main/java/org/openremote/model/AbstractValueHolder.java b/model/src/main/java/org/openremote/model/AbstractValueHolder.javaindex fb6c4460e..f0ff05d3d 100644--- a/model/src/main/java/org/openremote/model/AbstractValueHolder.java+++ b/model/src/main/java/org/openremote/model/AbstractValueHolder.java@@ -19,147 +19,112 @@*/package org.openremote.model;-import elemental.json.*;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Objects;import java.util.Optional;-import static org.openremote.model.util.JsonUtil.*;-/**- * Base class for all model classes which have to internally store data in a- * {@link JsonObject} that has a <code>value</code> field that accepts any- * {@link JsonValue}.+ * Base class for all model classes which have to internally store data in an+ * {@link ObjectValue} that has a <code>value</code> field that accepts any+ * {@link Value}.*/public abstract class AbstractValueHolder {-- protected static final String VALUE_FIELD_NAME = "value";-- final protected JsonObject jsonObject;-- public AbstractValueHolder(JsonObject jsonObject) {- Objects.requireNonNull(jsonObject);- this.jsonObject = jsonObject;- }- public boolean hasValue() {- return getValue().isPresent();- }+ protected static final String VALUE_FIELD_NAME = "value";- public Optional<String> getValueAsString() {- return asString(getValue());- }+ final protected ObjectValue objectValue;- public Optional<Integer> getValueAsInteger() {- return asInteger(getValue());+ public AbstractValueHolder(ObjectValue objectValue) {+ this.objectValue = Objects.requireNonNull(objectValue);}- public Optional<Double> getValueAsDecimal() {- return asDecimal(getValue());+ public ObjectValue getObjectValue() {+ return objectValue;}- public Optional<Boolean> getValueAsBoolean() {- return asBoolean(getValue());+ public void clearValue() {+ objectValue.remove(VALUE_FIELD_NAME);}- public Optional<JsonObject> getValueAsJsonObject() {- return asJsonObject(getValue());+ public Optional<Value> getValue() {+ return objectValue.get(VALUE_FIELD_NAME);}- public Optional<JsonArray> getValueAsJsonArray() {- return asJsonArray(getValue());+ public Optional<String> getValueAsString() {+ return objectValue.getString(VALUE_FIELD_NAME);}- public void clearValue() {- jsonObject.remove(VALUE_FIELD_NAME);+ public Optional<Double> getValueAsNumber() {+ return objectValue.getNumber(VALUE_FIELD_NAME);}- public void setValue(String value) {- doSetValue(asJsonValue(value));+ public Optional<Integer> getValueAsInteger() {+ return objectValue.getNumber(VALUE_FIELD_NAME).map(Double::intValue);}- public void setValue(Integer value) {- setValue(asJsonValue(value));+ public Optional<Boolean> getValueAsBoolean() {+ return objectValue.getBoolean(VALUE_FIELD_NAME);}- public void setValue(Double value) {- doSetValue(asJsonValue(value));+ public Optional<ObjectValue> getValueAsObject() {+ return objectValue.getObject(VALUE_FIELD_NAME);}- public void setValue(Boolean value) {- doSetValue(asJsonValue(value));+ public Optional<ArrayValue> getValueAsArray() {+ return objectValue.getArray(VALUE_FIELD_NAME);}/*** @throws IllegalArgumentException if the given value is invalid and failed constraint checking.*/- public void setValue(JsonValue value) throws IllegalArgumentException {- doSetValue(sanitizeJsonValue(value));+ public void setValue(Value value) throws IllegalArgumentException {+ if (!isValidValue(value)) {+ throw new IllegalArgumentException("Invalid value: " + (value != null ? value.toJson() : "null"));+ }+ if (value != null) {+ objectValue.put(VALUE_FIELD_NAME, value);+ } else {+ clearValue();+ }}- /**- * @throws IllegalArgumentException if the given value is invalid and failed constraint checking.- */- public void setValue(Optional<JsonValue> value) {- doSetValue(sanitizeJsonValue(value));+ public void setValue(Value... values) throws IllegalArgumentException {+ setValue(Values.createArray().addAll(values));}- protected void doSetValue(JsonValue jsonValue) throws IllegalArgumentException {- if (!isValidValue(jsonValue)) {- throw new IllegalArgumentException("Invalid value: " + (jsonValue != null ? jsonValue.toJson() : "null"));- }+ public void setValue(String string) throws IllegalArgumentException {+ setValue(Values.create(string));+ }- if (jsonValue != null) {- jsonObject.put(VALUE_FIELD_NAME, jsonValue);- } else {- clearValue();- }+ public void setValue(Double number) throws IllegalArgumentException {+ setValue(Values.create(number));+ }-// value = JsonUtil.replaceJsonNull(value)-// .map(-//-// val -> Json.instance().parse(val.toJson())-// )-// .map(val -> {-// if (!isValidValue(val)) {-// //noinspection ConstantConditions-// throw new IllegalArgumentException("Invalid value of type " + val.getType() + ": " + val.toJson());-// }-// return val;-// });-//-// if (value.isPresent()) {-// jsonObject.put(VALUE_FIELD_NAME, value.get());-// } else {-// clearValue();-// }- }-- public Optional<JsonValue> getValue() {- return Optional.ofNullable(sanitizeJsonValue((JsonValue)jsonObject.get(VALUE_FIELD_NAME)));+ public void setValue(Boolean b) throws IllegalArgumentException {+ setValue(Values.create(b));}/*** Override to implement constraints.*/- public boolean isValidValue(JsonValue value) {+ public boolean isValidValue(Value value) {return true;}- /**- * Indicate that the jsonObject contains the mandatory data for this type of attribute- * override in attribute sub classes as required- */+ public boolean hasValue() {+ return getValue().isPresent();+ }+public boolean isValid() {return true;}@Overridepublic String toString() {- return jsonObject.toJson();- }-- public JsonObject getJsonObject() {- return jsonObject;+ return objectValue.toJson();}}diff --git a/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java b/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.javaindex d1655b00e..3b53cbb5d 100644--- a/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java+++ b/model/src/main/java/org/openremote/model/AbstractValueTimestampHolder.java@@ -19,50 +19,48 @@*/package org.openremote.model;-import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;--import java.util.Optional;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;/**- * Base class for all model classes which have to internally store data in a- * {@link JsonObject} that has a <code>value</code> field that accepts any- * {@link JsonValue} and a <code>valueTimestamp</code> timestamp field, in+ * Base class for all model classes which have to internally store data in an+ * {@link ObjectValue} that has a <code>value</code> field that accepts any+ * {@link Value} and a <code>valueTimestamp</code> timestamp field, in* milliseconds since the Unix epoch, of the most recent value change.*/public abstract class AbstractValueTimestampHolder extends AbstractValueHolder {public static final String VALUE_TIMESTAMP_FIELD_NAME = "valueTimestamp";- public AbstractValueTimestampHolder(JsonObject jsonObject) {- super(jsonObject);+ public AbstractValueTimestampHolder(ObjectValue objectValue) {+ super(objectValue);}public boolean hasValueTimestamp() {- return jsonObject.hasKey(VALUE_TIMESTAMP_FIELD_NAME);+ return getObjectValue().hasKey(VALUE_TIMESTAMP_FIELD_NAME);}/*** @return <code>-1</code> if there is no timestamp.*/public long getValueTimestamp() {- return hasValueTimestamp() ? new Double(jsonObject.getNumber(VALUE_TIMESTAMP_FIELD_NAME)).longValue() : -1L;+ return getObjectValue().getNumber(VALUE_TIMESTAMP_FIELD_NAME).map(Double::longValue).orElse(-1L);}/**- * Sets the value timestamp to current system time.+ * Sets the value timestamp to given time.*/- public void setValueTimestamp() {- setValueTimestamp(System.currentTimeMillis());+ @SuppressWarnings("unchecked")+ public void setValueTimestamp(long timestamp) {+ getObjectValue().put(VALUE_TIMESTAMP_FIELD_NAME, Values.create(timestamp));}/**- * Sets the value timestamp to given time.+ * Sets the value timestamp to current system time.*/- @SuppressWarnings("unchecked")- public void setValueTimestamp(long timestamp) {- jsonObject.put(VALUE_TIMESTAMP_FIELD_NAME, Json.create(timestamp));+ public void setValueTimestamp() {+ setValueTimestamp(System.currentTimeMillis());}/**@@ -75,27 +73,19 @@ public abstract class AbstractValueTimestampHolder extends AbstractValueHolder {}/**- * Sets the value and the timestamp to given time.+ * Sets the value and the timestamp to system time.*/- public void setValue(JsonValue value, long timestamp) throws IllegalArgumentException {- setValue(value);- setValueTimestamp(timestamp);+ @Override+ public void setValue(Value value) throws IllegalArgumentException {+ super.setValue(value);+ setValueTimestamp();}/*** Sets the value and the timestamp to given time.*/- public void setValue(Optional<JsonValue> value, long timestamp) throws IllegalArgumentException {+ public void setValue(Value value, long timestamp) throws IllegalArgumentException {setValue(value);setValueTimestamp(timestamp);}-- /**- * Sets the value and the timestamp to current system time.- */- @Override- public void doSetValue(JsonValue value) throws IllegalArgumentException {- super.doSetValue(value);- setValueTimestamp();- }}diff --git a/model/src/main/java/org/openremote/model/Attribute.java b/model/src/main/java/org/openremote/model/Attribute.javadeleted file mode 100644index 4778e5738..000000000--- a/model/src/main/java/org/openremote/model/Attribute.java+++ /dev/null@@ -1,247 +0,0 @@-/*- * 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;--import com.google.gwt.regexp.shared.RegExp;-import elemental.json.Json;-import elemental.json.JsonArray;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.util.JsonUtil;--import java.util.Objects;-import java.util.Optional;-import java.util.function.Predicate;-import java.util.stream.Stream;--import static org.openremote.model.MetaItem.isMetaNameEqualTo;-import static org.openremote.model.util.JsonUtil.asJsonArray;-import static org.openremote.model.util.JsonUtil.getJsonValueType;-import static org.openremote.model.util.JsonUtil.sanitizeJsonValue;-import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;--/**- * Convenience overlay API for {@link JsonObject}.- */-public abstract class Attribute extends AbstractValueTimestampHolder {-- /**- * Attribute names should be very simple, as we use them in SQL path- * expressions, etc. and must manually escape.- */- public static final String ATTRIBUTE_NAME_PATTERN = "^\\w+$";- public static final RegExp ATTRIBUTE_NAME_REGEXP = RegExp.compile(ATTRIBUTE_NAME_PATTERN);- public static final Predicate<String> ATTRIBUTE_NAME_VALIDATOR =- name -> name != null && name.length() > 0 && ATTRIBUTE_NAME_REGEXP.test(name);-- public static final String TYPE_FIELD_NAME = "type";- public static final String META_FIELD_NAME = "meta";-- protected String name;-- protected Attribute(JsonObject jsonObject) {- super(jsonObject);- }-- protected Attribute(String name) {- this(Json.createObject());- setName(name);- }-- protected Attribute(String name, AttributeType type) {- this(name);- setName(name);- setType(type);- }-- protected Attribute(String name, AttributeType type, JsonValue value) {- this(name, type);- setValue(value);- }-- public boolean hasName() {- return getName().isPresent();- }-- public Optional<String> getName() {- return Optional.ofNullable(name);- }-- public void setName(String name) {- requireNonNullAndNonEmpty(name);- this.name = name;- }-- public boolean hasType() {- return jsonObject.hasKey(TYPE_FIELD_NAME) && JsonUtil.isOfTypeString(jsonObject.get(TYPE_FIELD_NAME));- }-- public Optional<AttributeType> getType() {- return Optional.ofNullable(hasType() ? AttributeType.fromValue(jsonObject.getString(TYPE_FIELD_NAME)) : null);- }-- public void setType(AttributeType type) {- Objects.requireNonNull(type);-- if (getType().orElse(null) == type) {- return;- }-- jsonObject.put(TYPE_FIELD_NAME, Json.create(type.getValue()));-- // Remove the old value and timestamp- jsonObject.remove(VALUE_TIMESTAMP_FIELD_NAME);- clearValue();- }-- public boolean hasMeta() {- return asJsonArray(jsonObject.getArray(META_FIELD_NAME))- .map(jsonArray -> jsonArray.length() > 0)- .orElse(false);- }-- public Meta getMeta() {- if (!hasMeta()) {- // Create array object so don't have to call setMeta- // can just update the collection like normal POJO behaviour- JsonArray metaArray = Json.createArray();- jsonObject.put(META_FIELD_NAME, metaArray);- }-- return new Meta(jsonObject.getArray(META_FIELD_NAME));- }-- public Stream<MetaItem> getMetaStream() {- return getMeta().stream();- }-- public boolean hasMetaItem(String metaName) {- return getMetaItem(metaName).isPresent();- }-- public boolean hasMetaItem(HasMetaName hasMetaName) {- return getMetaItem(hasMetaName).isPresent();- }-- public Optional<MetaItem> getMetaItem(String metaName) {- return getMetaStream()- .filter(isMetaNameEqualTo(metaName))- .findFirst();- }-- public Optional<MetaItem> getMetaItem(HasMetaName hasMetaName) {- return getMetaItem(hasMetaName.getUrn());- }-- // The below methods cause weird behaviour where things will compile- // but will fail at runtime - some weird generics issue-// public <A extends Attribute> A setMeta(List<MetaItem> meta) {-// if (meta != null) {-// Meta metaObj;-// if (meta instanceof Meta) {-// metaObj = (Meta)meta;-// } else {-// metaObj = new Meta();-// metaObj.addAll(meta);-// }-// jsonObject.put(META_FIELD_NAME, metaObj.getJsonArray());-// } else {-// jsonObject.remove(META_FIELD_NAME);-// }-//-// return (A)this;-// }-//-// @SuppressWarnings("unchecked")-// public <A extends Attribute> A setMeta(Meta meta) {-// setMeta((List<MetaItem>)meta);-// return (A)this;-// }-//-// @SuppressWarnings("unchecked")-// public <A extends Attribute> A setMeta(MetaItem... meta) {-// setMeta(Arrays.asList(meta));-// return (A)this;-// }-- @Override- public boolean isValid() {- // TODO: Should value validity be part of the isValid check?- return super.isValid()- && hasName() && ATTRIBUTE_NAME_VALIDATOR.test(name)- && getType()- .isPresent();- }-- @Override- public boolean isValidValue(JsonValue value) {- JsonValue sanitizedValue = sanitizeJsonValue(value);-- return super.isValidValue(sanitizedValue)- && (sanitizedValue == null ||- getType()- .map(type -> type.getJsonType() == getJsonValueType(sanitizedValue))- .orElse(false));- }-- // ----------------------------------------------------// FUNCTIONAL METHODS BELOW-// ----------------------------------------------------- public static <A extends Attribute> boolean equals(A attribute1, A attribute2) {- if (attribute1 == null && attribute2 == null)- return true;-- if (attribute1 == null || attribute2 == null)- return false;-- Optional<String> name = attribute2.getName();- return isAttributeNameEqualTo(attribute1, name.orElse(null))- && JsonUtil.equals(attribute1.getValue().orElse(null), attribute2.getValue().orElse(null));- }-- public static <A extends Attribute> boolean isAttributeNameEqualTo(A attribute, String name) {- if (attribute == null)- return false;-- return attribute- .getName()- .map(attributeName -> attributeName.equals(name))- .orElse(name == null);- }-- public static <A extends Attribute> Predicate<A> isAttributeNameEqualTo(String name) {- return attribute -> isAttributeNameEqualTo(attribute, name);- }-- public static <A extends Attribute> boolean isAttributeTypeEqualTo(A attribute, AttributeType type) {- if (attribute == null)- return false;-- return attribute- .getType()- .map(attributeType -> attributeType == type)- .orElse(type == null);- }-- public static <A extends Attribute> Predicate<A> isAttributeTypeEqualTo(AttributeType type) {- return attribute -> isAttributeTypeEqualTo(attribute, type);- }-}diff --git a/model/src/main/java/org/openremote/model/AttributeState.java b/model/src/main/java/org/openremote/model/AttributeState.javadeleted file mode 100644index 4b7d87659..000000000--- a/model/src/main/java/org/openremote/model/AttributeState.java+++ /dev/null@@ -1,123 +0,0 @@-/*- * 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;--import com.fasterxml.jackson.annotation.JsonAutoDetect;-import com.fasterxml.jackson.annotation.JsonProperty;-import elemental.json.Json;-import elemental.json.JsonArray;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.util.JsonUtil;--import java.util.Objects;-import java.util.Optional;--import static org.openremote.model.util.JsonUtil.*;--/**- * The desired or current or past state of an {@link AttributeRef}.- */-@JsonAutoDetect(- fieldVisibility = JsonAutoDetect.Visibility.ANY,- creatorVisibility= JsonAutoDetect.Visibility.NONE,- getterVisibility= JsonAutoDetect.Visibility.NONE,- setterVisibility= JsonAutoDetect.Visibility.NONE,- isGetterVisibility= JsonAutoDetect.Visibility.NONE-)-public class AttributeState {-- @JsonProperty- protected AttributeRef attributeRef;- @JsonProperty- protected JsonValue jsonValue;-- protected AttributeState() {- }-- public AttributeState(AttributeRef attributeRef) {- this(attributeRef, Optional.empty());- }-- public AttributeState(AttributeRef attributeRef, JsonValue jsonValue) {- this(attributeRef, Optional.ofNullable(jsonValue));- }-- public AttributeState(AttributeRef attributeRef, Optional<JsonValue> jsonValue) {- Objects.requireNonNull(attributeRef);- this.attributeRef = attributeRef;- this.jsonValue = sanitizeJsonValue(jsonValue);- }-- public AttributeRef getAttributeRef() {- return attributeRef;- }-- public Optional<JsonValue> getValue() {- return Optional.ofNullable(jsonValue);- }-- public JsonValue toJsonValue() {- JsonObject jsonObject = Json.createObject();- jsonObject.put("attributeRef", getAttributeRef().toJsonValue());- getValue().ifPresent(- jsonValue -> jsonObject.put("value", sanitizeJsonValue(jsonValue))- );- return jsonObject;- }-- @Override- public String toString() {- JsonValue value = sanitizeJsonValue(getValue());-- return getClass().getSimpleName() + "{" +- "attributeRef=" + attributeRef +- ", value=" + (value != null ? value.toJson() : "null") +- '}';- }-- public static boolean isAttributeState(JsonValue jsonValue) {- return fromJsonValue(jsonValue) != null;- }-- public static Optional<AttributeState> fromJsonValue(JsonValue jsonValue) {- Optional<JsonObject> jsonObject = asJsonObject(jsonValue);- Optional<JsonArray> jsonArray = jsonObject- .flatMap(jsonObj -> asJsonArray((JsonValue)jsonObj.get("attributeRef")));-- if (!jsonObject.isPresent() || !jsonArray.isPresent() || !jsonObject.get().hasKey("value")) {- return Optional.empty();- }-- //noinspection ConstantConditions- return jsonArray- .flatMap(AttributeRef::fromJsonValue)- .map(attributeRef ->- new AttributeState(- attributeRef,- sanitizeJsonValue((JsonValue)jsonObject.get().get("value"))- )- );- }-- public static JsonValue toJsonValue(AttributeState attributeState) {- return attributeState.toJsonValue();- }-}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/AttributeType.java b/model/src/main/java/org/openremote/model/AttributeType.javadeleted file mode 100644index ec896c2d0..000000000--- a/model/src/main/java/org/openremote/model/AttributeType.java+++ /dev/null@@ -1,80 +0,0 @@-/*- * 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;--import elemental.json.JsonType;-import elemental.json.JsonValue;-import org.openremote.model.util.JsonUtil;--/**- * The base type of an {@link Attribute}, how its {@link elemental.json.JsonValue} should be- * interpreted when working with an attribute (e.g. when testing, rendering, or editing- * the value).- *- * Additional constraints and integrity rules upon attribute values can be declared by- * adding arbitrary {@link Meta} to an {@link Attribute}.- */-public enum AttributeType {-- // TODO: Remove old attribute types-- //NULL("Null", JsonType.NULL), // TODO: Decide if 'Null' is a valid AttributeType (i.e. doesn't accept a value)- STRING("String", JsonType.STRING),- OBJECT("Object", JsonType.OBJECT),- INTEGER("Integer", JsonType.NUMBER),- DECIMAL("Decimal", JsonType.NUMBER),- BOOLEAN("Boolean", JsonType.BOOLEAN),- OBJECT_ARRAY("Object[]", JsonType.ARRAY),- STRING_ARRAY("String[]", JsonType.ARRAY),- INTEGER_ARRAY("Integer[]", JsonType.ARRAY),- DECIMAL_ARRAY("Decimal[]", JsonType.ARRAY),- BOOLEAN_ARRAY("Boolean[]", JsonType.ARRAY);-- private String value;- private JsonType jsonType;-- AttributeType(String value, JsonType jsonType) {- this.value = value;- this.jsonType = jsonType;- }-- public String getValue() {- return value;- }-- public JsonType getJsonType() {- return jsonType;- }-- public boolean isValid(JsonValue value) {- return value != null && JsonUtil.isOfType(value, getJsonType());- }-- public static AttributeType fromValue(String value) {- if (value != null && !"".equals(value)) {- AttributeType[] values = AttributeType.values();- for (AttributeType v : values) {- if (v.getValue().equalsIgnoreCase(value))- return v;- }- }- return STRING;- }-}diff --git a/model/src/main/java/org/openremote/model/NewAttributeType.java b/model/src/main/java/org/openremote/model/NewAttributeType.javadeleted file mode 100644index 496dc93f9..000000000--- a/model/src/main/java/org/openremote/model/NewAttributeType.java+++ /dev/null@@ -1,183 +0,0 @@-/*- * 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;--import elemental.json.JsonValue;-import org.openremote.model.value.Value;-import org.openremote.model.value.ValueType;--import java.util.function.Predicate;--/**- * The base type of an {@link Attribute}, how its {@link JsonValue} should be- * interpreted when working with an attribute (e.g. when testing, rendering, or editing- * the value).- *- * Additional constraints and integrity rules upon attribute values can be declared by- * adding arbitrary {@link Meta} to an {@link Attribute}.- */-public enum NewAttributeType {- // TODO: Implement new attribute types- STRING("String", ValueType.STRING),- INTEGER("Integer", ValueType.NUMBER),- DECIMAL("Decimal", ValueType.NUMBER),- BOOLEAN("Boolean", ValueType.BOOLEAN);--/* *//**- * Unix epoch timestamp- *//*- // TODO: Seconds or milliseconds- TIMESTAMP("Timestamp", ValueType.NUMBER),*/-/*- *//**- * ISO 8601, e.g. <code>2012-04-23T18:25:43.511Z</code>- *//*- DATETIME,-- *//**- * RGB integers- *//*- COLOR_RGB,-- *//**- * ARGB integers- *//*- COLOR_ARGB,-- *//**- * HTML Hex Value, e.g. <code>#ffffff</code>- *//*- COLOR_HEX,-- TEMPERATURE_CELCIUS,-- TEMPERATURE_KELVIN,-- TEMPERATURE_FAHRENHEIT,-- DISTANCE_M,-- DISTANCE_CM,-- DISTANCE_MM,-- DISTANCE_IN,-- DISTANCE_FT,-- DISTANCE_YARD,-- CO2_PPM,-- CO2_PERCENTAGE,-- HUMIDITY_PERCENTAGE,-- *//**- * Grams per cubic metre- *//*- HUMIDITY_GPCM,-- POWER_WATTS,-- POWER_KILOWATT,-- POWER_MEGAWATT,-- CHARGE_PERCENTAGE,-- CHARGE_KWH,-- PERCENTAGE,-- ENERGY_KWH,-- ENERGY_JOULE,-- ENERGY_MEGAJOULE,-- *//**- * Litre per minute- *//*- FLOW_LPM,-- *//**- * Cubic metres per second- *//*- FLOW_CMPS,-- *//**- * Standard cubic centimetres per minute- *//*- FLOW_SCCM,-- *//**- * Cubic feet per second- *//*- FLOW_CFPS,-- *//**- * Gallons per minute- *//*- FLOW_GPM;*/-- private String displayName;- private ValueType valueType;- private Predicate<Value> isValid;-- NewAttributeType(String displayName, ValueType valueType) {- this(displayName, valueType, null);- }-- NewAttributeType(String displayName, ValueType valueType, Predicate<Value> isValid) {- this.displayName = displayName;- this.valueType = valueType;- this.isValid = isValid;- }-- public String getDisplayName() {- return displayName;- }-- public ValueType getValueType() {- return valueType;- }-- public boolean isValid(Value value) {- // Check type- if (value == null) {- // TODO: Should we allow nulls for any type?- return true;- }-- return value.getType() == getValueType() && (isValid == null || isValid.test(value));- }-- public static NewAttributeType fromValue(String value) {- if (value != null && !"".equals(value)) {- NewAttributeType[] values = NewAttributeType.values();- for (NewAttributeType v : values) {- if (v.getDisplayName().equalsIgnoreCase(value))- return v;- }- }- return STRING;- }-}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.javaindex 29a84f7f8..d713bfacc 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java@@ -19,14 +19,15 @@*/package org.openremote.model.asset;-import elemental.json.JsonValue;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;-import org.openremote.model.AttributeType;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;import java.util.Date;+import java.util.Optional;import static org.openremote.model.asset.AssetType.CUSTOM;@@ -66,7 +67,7 @@ public abstract class AbstractAssetUpdate {final protected double[] coordinates;- final protected JsonValue oldValue;+ final protected Value oldValue;final protected long oldValueTimestamp;@@ -77,7 +78,7 @@ public abstract class AbstractAssetUpdate {this(asset, attribute, null, 0, false);}- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {+ public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean northbound) {this(attribute,asset.getCreatedOn(),@@ -126,7 +127,7 @@ public abstract class AbstractAssetUpdate {String[] pathFromRoot, String parentId, String parentName, String parentTypeString, AssetType parentType,String realmId, String tenantRealm,double[] coordinates,- JsonValue oldValue,+ Value oldValue,long oldValueTimestamp,boolean northbound) {this.attribute = attribute;@@ -203,7 +204,7 @@ public abstract class AbstractAssetUpdate {return coordinates;}- public JsonValue getOldValue() {+ public Value getOldValue() {return oldValue;}@@ -215,12 +216,32 @@ public abstract class AbstractAssetUpdate {return northbound;}- public JsonValue getValue() {+ public Value getValue() {return attribute.getValue().orElse(null);}- public boolean isValueNull() {- return !attribute.getValue().isPresent();+ public Boolean getValueAsBoolean() {+ return attribute.getValueAsBoolean().orElse(null);+ }++ public Double getValueAsNumber() {+ return attribute.getValueAsNumber().orElse(null);+ }++ public String getValueAsString() {+ return attribute.getValueAsString().orElse(null);+ }++ public ObjectValue getValueAsObject() {+ return attribute.getValueAsObject().orElse(null);+ }++ public ArrayValue getValueAsArray() {+ return attribute.getValueAsArray().orElse(null);+ }++ public AssetAttribute getAttribute() {+ return attribute;}public String getAttributeName() {@@ -235,12 +256,8 @@ public abstract class AbstractAssetUpdate {return attribute.getType().orElse(null);}- public AttributeEvent getStateEvent() {- return new AttributeEvent(new AttributeState(getAttributeRef(), attribute.getValue()), attribute.getValueTimestamp());- }-public boolean isValueChanged() {- return !JsonUtil.equals(attribute.getValue().orElse(null), oldValue);+ return !attribute.getValue().equals(Optional.ofNullable(oldValue));}public AttributeRef getAttributeRef() {@@ -249,7 +266,7 @@ public abstract class AbstractAssetUpdate {public boolean matches(AttributeEvent event) {return event.getAttributeRef().equals(getAttributeRef())- && JsonUtil.equals(getValue(), event.getAttributeState().getValue().orElse(null))+ && Optional.ofNullable(getValue()).equals(event.getAttributeState().getCurrentValue())&& getValueTimestamp() == event.getTimestamp();}@@ -267,19 +284,22 @@ public abstract class AbstractAssetUpdate {AbstractAssetUpdate that = (AbstractAssetUpdate) o;- return id.equals(that.id) &&- getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&- JsonUtil.equals(getValue(), that.getValue()) &&+ return getId().equals(that.getId()) &&+ getAttribute().getName().equals(that.getAttribute().getName()) &&+ getAttribute().getValue().equals(that.getAttribute().getValue()) &&getValueTimestamp() == that.getValueTimestamp() &&- ((oldValue == null && that.oldValue == null) || (oldValue != null && JsonUtil.equals(oldValue, that.oldValue))) &&- oldValueTimestamp == that.oldValueTimestamp;+ Optional.ofNullable(getOldValue()).equals(Optional.ofNullable(that.getOldValue())) &&+ getOldValueTimestamp() == that.getOldValueTimestamp();}@Overridepublic int hashCode() {- return id.hashCode() + getAttributeName().hashCode() + JsonUtil.hashCode(getValue())+ return getId().hashCode()+ + getAttributeName().hashCode()+ + getAttribute().getValue().hashCode()+ Long.hashCode(getValueTimestamp())- + (oldValue != null ? JsonUtil.hashCode(oldValue) : 0) + Long.hashCode(oldValueTimestamp);+ + Optional.ofNullable(getOldValue()).hashCode()+ + Long.hashCode(getOldValueTimestamp());}@Overridediff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex da5426e44..81eeca1e5 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -19,14 +19,15 @@*/package org.openremote.model.asset;-import elemental.json.Json;-import elemental.json.JsonObject;import org.hibernate.annotations.Formula;import org.openremote.model.IdentifiableEntity;+import org.openremote.model.attribute.Attribute;import org.openremote.model.geo.GeoJSON;import org.openremote.model.geo.GeoJSONFeature;import org.openremote.model.geo.GeoJSONGeometry;import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Values;import javax.persistence.*;import javax.validation.constraints.NotNull;@@ -77,9 +78,8 @@ import static org.openremote.model.asset.AssetAttribute.*;* The {@link #coordinates} are a pair of LNG/LAT values with the location of the asset.* <p>* An asset may have dynamically-typed {@link #attributes} with an underlying- * {@link elemental.json.JsonObject} model. Use the {@link org.openremote.model.Attribute}- * etc. class to work with this API. This property can be empty when certain optimized loading- * operations are used.+ * {@link ObjectValue} model. Use the {@link Attribute} etc. class to work with this API.+ * This property can be empty when certain optimized loading operations are used.* <p>* Constructors can filter attributes of an asset as to only contain protected attributes,* and their protected metadata (see {@link AssetMeta#PROTECTED}, {@link AssetMeta.Access}).@@ -272,7 +272,7 @@ public class Asset implements IdentifiableEntity {@Column(name = "ATTRIBUTES", columnDefinition = "jsonb")@org.hibernate.annotations.Type(type = PERSISTENCE_JSON_OBJECT_TYPE)- public JsonObject attributes;+ public ObjectValue attributes;public Asset() {}@@ -316,7 +316,7 @@ public class Asset implements IdentifiableEntity {String id, long version, Date createdOn, String name, String type,String parentId, String parentName, String parentType,String realmId, String tenantRealm, String tenantDisplayName,- String[] path, JsonObject attributes) {+ String[] path, ObjectValue attributes) {this(name, type, null, realmId);this.id = id;this.version = version;@@ -332,7 +332,7 @@ public class Asset implements IdentifiableEntity {this.attributes = attributesToJson(filterProtectedAttributes(attributesFromJson(attributes, id)).collect(Collectors.toList())- ).orElse(Json.createObject());+ ).orElse(Values.createObject());} else {this.attributes = attributes;}@@ -352,7 +352,7 @@ public class Asset implements IdentifiableEntity {throw new IllegalArgumentException("Attribute cannot be null and must have a name and type");attribute.assetId = getId();- attributes.put(attribute.getName().get(), attribute.getJsonObject());+ attributes.put(attribute.getName().get(), attribute.getObjectValue());}public void removeAttribute(String name) {@@ -531,7 +531,7 @@ public class Asset implements IdentifiableEntity {return path != null && Arrays.asList(getPath()).contains(assetId);}- public JsonObject getAttributes() {+ public ObjectValue getAttributes() {return attributes;}@@ -548,15 +548,16 @@ public class Asset implements IdentifiableEntity {}public Optional<AssetAttribute> getAttribute(String name) {- return AssetAttribute.attributeFromJson(attributes.getObject(name), id, name);+ return attributes.getObject(name)+ .flatMap(objectValue -> AssetAttribute.attributeFromJson(objectValue, id, name));}- protected void setAttributes(JsonObject attributes) {+ protected void setAttributes(ObjectValue attributes) {this.attributes = attributes;}public void setAttributes(List<AssetAttribute> attributes) {- this.attributes = attributesToJson(attributes).orElse(Json.createObject());+ this.attributes = attributesToJson(attributes).orElse(Values.createObject());}public void setAttributes(AssetAttribute... attributes) {diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex edbde5a88..be058a130 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -19,18 +19,22 @@*/package org.openremote.model.asset;-import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.*;--import java.util.*;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.attribute.*;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Arrays;+import java.util.Collection;+import java.util.Optional;import java.util.function.Predicate;import java.util.stream.Stream;-import static org.openremote.model.MetaItem.isMetaNameEqualTo;-import static org.openremote.model.MetaItem.replaceMetaByName;import static org.openremote.model.asset.AssetMeta.*;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.attribute.MetaItem.replaceMetaByName;import static org.openremote.model.util.TextUtil.isNullOrEmpty;import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;@@ -39,11 +43,11 @@ public class AssetAttribute extends Attribute {protected String assetId;public AssetAttribute() {- super(Json.createObject());+ super(Values.createObject());}- protected AssetAttribute(JsonObject jsonObject) {- super(jsonObject);+ protected AssetAttribute(ObjectValue objectValue) {+ super(objectValue);}public AssetAttribute(String name) {@@ -54,7 +58,7 @@ public class AssetAttribute extends Attribute {super(name, type);}- public AssetAttribute(String name, AttributeType type, JsonValue value) {+ public AssetAttribute(String name, AttributeType type, Value value) {super(name, type, value);}@@ -68,15 +72,11 @@ public class AssetAttribute extends Attribute {setAssetId(assetId);}- public AssetAttribute(String assetId, String name, AttributeType type, JsonValue value) {+ public AssetAttribute(String assetId, String name, AttributeType type, Value value) {super(name, type, value);setAssetId(assetId);}- public boolean hasAssetId() {- return assetId != null;- }-public Optional<String> getAssetId() {return Optional.ofNullable(assetId);}@@ -86,11 +86,12 @@ public class AssetAttribute extends Attribute {this.assetId = assetId;}- @SuppressWarnings("ConstantConditions")public Optional<AttributeRef> getReference() {- return Optional.ofNullable(hasAssetId() && hasName()- ? new AttributeRef(getAssetId().get(), getName().get())- : null);+ return Optional.ofNullable(+ getAssetId().isPresent() && getName().isPresent()+ ? new AttributeRef(getAssetId().get(), getName().get())+ : null+ );}/**@@ -98,39 +99,22 @@ public class AssetAttribute extends Attribute {* with a standardised exception message.*/public AttributeRef getReferenceOrThrow() {- return getReference()- .orElseThrow(() -> new IllegalStateException("Attribute doesn't have an attribute ref"));+ return getReference().orElseThrow(() -> new IllegalStateException("Attribute doesn't have an attribute ref"));}public Optional<AttributeState> getState() {- return getReference()- .map(ref -> new AttributeState(ref, getValue()));- }-- public AssetAttribute setMeta(List<MetaItem> meta) {- if (meta != null) {- Meta metaObj;- if (meta instanceof Meta) {- metaObj = (Meta)meta;- } else {- metaObj = new Meta();- metaObj.addAll(meta);- }- jsonObject.put(META_FIELD_NAME, metaObj.getJsonArray());- } else {- jsonObject.remove(META_FIELD_NAME);- }-- return this;+ return getReference().map(ref -> new AttributeState(ref, getValue().orElse(null)));}+ @Overridepublic AssetAttribute setMeta(Meta meta) {- setMeta((List<MetaItem>)meta);+ super.setMeta(meta);return this;}+ @Overridepublic AssetAttribute setMeta(MetaItem... meta) {- setMeta(Arrays.asList(meta));+ super.setMeta(meta);return this;}@@ -138,8 +122,7 @@ public class AssetAttribute extends Attribute {* @return The current value and its timestamp represented as an attribute event.*/public Optional<AttributeEvent> getStateEvent() {- return getState()- .map(state -> new AttributeEvent(state, getValueTimestamp()));+ return getState().map(state -> new AttributeEvent(state, getValueTimestamp()));}public boolean hasLabel() {@@ -156,7 +139,7 @@ public class AssetAttribute extends Attribute {public void setLabel(String label) {if (!isNullOrEmpty(label)) {- replaceMetaByName(getMeta(), LABEL, Json.create(label));+ replaceMetaByName(getMeta(), LABEL, Values.create(label));} else {getMeta().removeIf(isMetaNameEqualTo(LABEL));}@@ -172,7 +155,7 @@ public class AssetAttribute extends Attribute {public void setExecutable(boolean executable) {if (executable) {- replaceMetaByName(getMeta(), EXECUTABLE, Json.create(true));+ replaceMetaByName(getMeta(), EXECUTABLE, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(EXECUTABLE));}@@ -188,7 +171,7 @@ public class AssetAttribute extends Attribute {public void setShowOnDashboard(boolean show) {if (show) {- replaceMetaByName(getMeta(), SHOW_ON_DASHBOARD, Json.create(true));+ replaceMetaByName(getMeta(), SHOW_ON_DASHBOARD, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(SHOW_ON_DASHBOARD));}@@ -207,7 +190,7 @@ public class AssetAttribute extends Attribute {public void setFormat(String format) {if (!isNullOrEmpty(format)) {- replaceMetaByName(getMeta(), FORMAT, Json.create(format));+ replaceMetaByName(getMeta(), FORMAT, Values.create(format));} else {getMeta().removeIf(isMetaNameEqualTo(FORMAT));}@@ -226,7 +209,7 @@ public class AssetAttribute extends Attribute {public void setDescription(String description) {if (!isNullOrEmpty(description)) {- replaceMetaByName(getMeta(), DESCRIPTION, Json.create(description));+ replaceMetaByName(getMeta(), DESCRIPTION, Values.create(description));} else {getMeta().removeIf(isMetaNameEqualTo(DESCRIPTION));}@@ -245,7 +228,7 @@ public class AssetAttribute extends Attribute {public void setEnabled(boolean enabled) {if (!enabled) {- replaceMetaByName(getMeta(), ENABLED, Json.create(false));+ replaceMetaByName(getMeta(), ENABLED, Values.create(false));} else {getMeta().removeIf(isMetaNameEqualTo(ENABLED));}@@ -261,7 +244,7 @@ public class AssetAttribute extends Attribute {public void setProtected(boolean protect) {if (protect) {- replaceMetaByName(getMeta(), PROTECTED, Json.create(true));+ replaceMetaByName(getMeta(), PROTECTED, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(PROTECTED));}@@ -277,7 +260,7 @@ public class AssetAttribute extends Attribute {public void setReadOnly(boolean readOnly) {if (readOnly) {- replaceMetaByName(getMeta(), READ_ONLY, Json.create(true));+ replaceMetaByName(getMeta(), READ_ONLY, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(READ_ONLY));}@@ -293,7 +276,7 @@ public class AssetAttribute extends Attribute {public void setStoreDatapoints(boolean storeDatapoints) {if (storeDatapoints) {- replaceMetaByName(getMeta(), STORE_DATA_POINTS, Json.create(true));+ replaceMetaByName(getMeta(), STORE_DATA_POINTS, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(STORE_DATA_POINTS));}@@ -309,7 +292,7 @@ public class AssetAttribute extends Attribute {public void setRuleState(boolean ruleState) {if (ruleState) {- replaceMetaByName(getMeta(), RULE_STATE, Json.create(true));+ replaceMetaByName(getMeta(), RULE_STATE, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(RULE_STATE));}@@ -325,7 +308,7 @@ public class AssetAttribute extends Attribute {public void setRuleEvent(boolean ruleEvent) {if (ruleEvent) {- replaceMetaByName(getMeta(), RULE_EVENT, Json.create(true));+ replaceMetaByName(getMeta(), RULE_EVENT, Values.create(true));} else {getMeta().removeIf(isMetaNameEqualTo(RULE_EVENT));}@@ -340,16 +323,14 @@ public class AssetAttribute extends Attribute {public void setRuleEventExpires(String expiry) {if (!isNullOrEmpty(expiry)) {- replaceMetaByName(getMeta(), RULE_EVENT_EXPIRES, Json.create(expiry));+ replaceMetaByName(getMeta(), RULE_EVENT_EXPIRES, Values.create(expiry));} else {getMeta().removeIf(isMetaNameEqualTo(RULE_EVENT_EXPIRES));}}- public AssetAttribute copy() {- AssetAttribute copy = new AssetAttribute(- Json.parse(getJsonObject().toJson())- );+ public AssetAttribute deepCopy() {+ AssetAttribute copy = new AssetAttribute(getObjectValue().deepCopy());copy.assetId = assetId;copy.name = name;return copy;@@ -368,47 +349,48 @@ public class AssetAttribute extends Attribute {public static Stream<AssetAttribute> filterProtectedAttributes(Stream<AssetAttribute> attributes) {return attributes == null ? Stream.empty() : attributes.filter(AssetAttribute::isProtected)- .map(AssetAttribute::copy)- .peek(attribute -> attribute.getMeta().removeIf(((Predicate<MetaItem>)AssetMeta::isMetaItemProtectedReadable).negate()));+ .map(AssetAttribute::deepCopy)+ .peek(attribute -> attribute.getMeta().removeIf(((Predicate<MetaItem>) AssetMeta::isMetaItemProtectedReadable).negate()));}- public static Optional<AssetAttribute> attributeFromJson(JsonObject jsonObject, String assetId, String name) {- if (jsonObject == null || jsonObject.keys().length == 0 || isNullOrEmpty(assetId) || isNullOrEmpty(name)) {+ public static Optional<AssetAttribute> attributeFromJson(ObjectValue objectValue, String assetId, String name) {+ if (objectValue == null || objectValue.keys().length == 0 || isNullOrEmpty(assetId) || isNullOrEmpty(name)) {return Optional.empty();}- AssetAttribute attribute = new AssetAttribute(jsonObject);+ AssetAttribute attribute = new AssetAttribute(objectValue);attribute.setAssetId(assetId);attribute.setName(name);return Optional.of(attribute);}- public static Stream<AssetAttribute> attributesFromJson(JsonObject jsonObject, String assetId) {- if (jsonObject == null || jsonObject.keys().length == 0 || isNullOrEmpty(assetId)) {+ public static Stream<AssetAttribute> attributesFromJson(ObjectValue objectValue, String assetId) {+ if (objectValue == null || objectValue.keys().length == 0 || isNullOrEmpty(assetId)) {return Stream.empty();}-return Arrays- .stream(jsonObject.keys())- .map(key -> attributeFromJson(jsonObject.getObject(key), assetId, key))+ .stream(objectValue.keys())+ .map(key -> new Pair<>(key, objectValue.getObject(key)))+ .filter(pair -> pair.value.isPresent())+ .map(pair -> attributeFromJson(pair.value.get(), assetId, pair.key)).filter(Optional::isPresent).map(Optional::get);}/**- * Maps the attribute stream to a {@link JsonObject}, duplicate attribute names are not- * allowed (internally this is a hash map in Elemental, thus not allowing duplicate- * JSON object property names).+ * Maps the attribute stream to a {@link ObjectValue}, duplicate attribute names are not+ * allowed (internally this is a hash map, thus not allowing duplicate JSON object property+ * names).*/- public static <A extends Attribute> Optional<JsonObject> attributesToJson(Collection<A> attributes) {+ public static <A extends Attribute> Optional<ObjectValue> attributesToJson(Collection<A> attributes) {if (attributes.size() == 0)return Optional.empty();- JsonObject jsonObject = Json.createObject();+ ObjectValue objectValue = Values.createObject();for (A attribute : attributes) {if (attribute.getName().isPresent())- jsonObject.put(attribute.getName().get(), attribute.getJsonObject());+ objectValue.put(attribute.getName().get(), attribute.getObjectValue());}- return Optional.of(jsonObject);+ return Optional.of(objectValue);}}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 92cd9e085..ad6ae3614 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -19,10 +19,10 @@*/package org.openremote.model.asset;-import elemental.json.JsonType;-import org.openremote.model.MetaItem;-import org.openremote.model.HasMetaName;-import org.openremote.model.units.AttributeUnits;+import org.openremote.model.attribute.AttributeExecuteStatus;+import org.openremote.model.attribute.HasMetaName;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.ValueType;import java.util.ArrayList;import java.util.Comparator;@@ -44,79 +44,72 @@ public enum AssetMeta implements HasMetaName {* Links the attribute to an agent's {@link org.openremote.model.asset.agent.ProtocolConfiguration}, connecting it* to a sensor and/or actuator.*/- AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink", new Access(false, false, true), JsonType.ARRAY),+ AGENT_LINK(ASSET_META_NAMESPACE + ":agentLink", new Access(false, false, true), ValueType.ARRAY),/*** A human-friendly string that can be displayed in UI instead of the raw attribute name.*/- LABEL(ASSET_META_NAMESPACE + ":label", new Access(true, true, true), JsonType.STRING),+ LABEL(ASSET_META_NAMESPACE + ":label", new Access(true, true, true), ValueType.STRING),/*** If there is a dashboard, some kind of attribute overview, should this attribute be shown.*/- SHOW_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard", new Access(true, true, true), JsonType.BOOLEAN),+ SHOW_ON_DASHBOARD(ASSET_META_NAMESPACE + ":showOnDashboard", new Access(true, true, true), ValueType.BOOLEAN),/*** Format string that can be used to render the attribute value, see https://github.com/alexei/sprintf.js.*/- FORMAT(ASSET_META_NAMESPACE + ":format", new Access(true, false, true), JsonType.STRING),+ FORMAT(ASSET_META_NAMESPACE + ":format", new Access(true, false, true), ValueType.STRING),/*** A human-friendly string describing the purpose of an attribute, useful when rendering editors.*/- DESCRIPTION(ASSET_META_NAMESPACE + ":description", new Access(true, false, true), JsonType.STRING),+ DESCRIPTION(ASSET_META_NAMESPACE + ":description", new Access(true, false, true), ValueType.STRING),/*** Points to semantic description of the attribute, typically a URI.*/- ABOUT(ASSET_META_NAMESPACE + ":about", new Access(true, false, true), JsonType.STRING),+ ABOUT(ASSET_META_NAMESPACE + ":about", new Access(true, false, true), ValueType.STRING),/*** Marks the attribute as read-only.*/- READ_ONLY(ASSET_META_NAMESPACE + ":readOnly", new Access(true, false, true), JsonType.BOOLEAN),+ READ_ONLY(ASSET_META_NAMESPACE + ":readOnly", new Access(true, false, true), ValueType.BOOLEAN),/*** Marks the attribute as protected and accessible to restricted users, see {@link UserAsset}.*/- PROTECTED(ASSET_META_NAMESPACE + ":protected", new Access(false, false, true), JsonType.BOOLEAN),+ PROTECTED(ASSET_META_NAMESPACE + ":protected", new Access(false, false, true), ValueType.BOOLEAN),/*** Default value that might be used when editing an attribute.*/- DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), JsonType.STRING),+ DEFAULT(ASSET_META_NAMESPACE + ":default", new Access(false, false, false), ValueType.STRING),/*** Minimum range constraint for numeric attribute values.*/- RANGE_MIN(ASSET_META_NAMESPACE + ":rangeMin", new Access(true, false, true), JsonType.NUMBER),+ RANGE_MIN(ASSET_META_NAMESPACE + ":rangeMin", new Access(true, false, true), ValueType.NUMBER),/*** Maximum range constraint for numeric attribute values.*/- RANGE_MAX(ASSET_META_NAMESPACE + ":rangeMax", new Access(true, false, true), JsonType.NUMBER),+ RANGE_MAX(ASSET_META_NAMESPACE + ":rangeMax", new Access(true, false, true), ValueType.NUMBER),/*** Step increment/decrement constraint for numeric attribute values.*/- STEP(ASSET_META_NAMESPACE + ":step", new Access(true, false, true), JsonType.NUMBER),+ STEP(ASSET_META_NAMESPACE + ":step", new Access(true, false, true), ValueType.NUMBER),/*** Regex (Java syntax) constraint for string attribute values.*/- PATTERN(ASSET_META_NAMESPACE + ":pattern", new Access(true, false, true), JsonType.STRING),-- /**- * Indicates the units (data sub-type) of the attribute value (should be a valid- * {@link AttributeUnits} string representation).- */- // TODO: Remove this- UNITS(ASSET_META_NAMESPACE + ":units", new Access(true, false, true), JsonType.STRING),+ PATTERN(ASSET_META_NAMESPACE + ":pattern", new Access(true, false, true), ValueType.STRING),/*** Should attribute values be stored in time series database*/- STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), JsonType.BOOLEAN),+ STORE_DATA_POINTS(ASSET_META_NAMESPACE + ":storeDataPoints", new Access(true, false, true), ValueType.BOOLEAN),/*** Should attribute writes be processed by the rules engines as facts in knowledge sessions, with a lifecycle@@ -124,7 +117,7 @@ public enum AssetMeta implements HasMetaName {* in sync with asset changes). If you want two types of facts in your rules knowledge session for a single* attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.*/- RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), JsonType.BOOLEAN),+ RULE_STATE(ASSET_META_NAMESPACE + ":ruleState", new Access(true, false, true), ValueType.BOOLEAN),/*** Should attribute writes be processed by the rules engines as events in knowledge sessions with limited@@ -133,30 +126,30 @@ public enum AssetMeta implements HasMetaName {* by time operations). If you want two types of facts in your rules knowledge session for a single attribute,* with state and event behavior, combine this with {@link #RULE_STATE\}.*/- RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), JsonType.BOOLEAN),+ RULE_EVENT(ASSET_META_NAMESPACE + ":ruleEvent", new Access(true, false, true), ValueType.BOOLEAN),/*** Override rules event expiration, for example "1h30m". Remove {@link AssetEvent}* facts from the rules sessions if they are older than this value (using event source timestamp, not event* processing time).*/- RULE_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":ruleEventExpires", new Access(true, false, true), JsonType.STRING),+ RULE_EVENT_EXPIRES(ASSET_META_NAMESPACE + ":ruleEventExpires", new Access(true, false, true), ValueType.STRING),/*** Enable flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})*/- ENABLED(ASSET_META_NAMESPACE + ":enabled", new Access(true, false, true), JsonType.BOOLEAN),+ ENABLED(ASSET_META_NAMESPACE + ":enabled", new Access(true, false, true), ValueType.BOOLEAN),/**- * Marks an attribute as being executable so it then supports values of type {@link org.openremote.model.AttributeExecuteStatus}.+ * Marks an attribute as being executable so it then supports values of type {@link AttributeExecuteStatus}.*/- EXECUTABLE(ASSET_META_NAMESPACE + ":executable", new Access(true, false, true), JsonType.BOOLEAN);+ EXECUTABLE(ASSET_META_NAMESPACE + ":executable", new Access(true, false, true), ValueType.BOOLEAN);final protected String urn;final protected Access access;- final protected JsonType valueType;+ final protected ValueType valueType;- AssetMeta(String urn, Access access, JsonType valueType) {+ AssetMeta(String urn, Access access, ValueType valueType) {this.urn = urn;this.access = access;this.valueType = valueType;@@ -170,7 +163,7 @@ public enum AssetMeta implements HasMetaName {return access;}- public JsonType getValueType() {+ public ValueType getValueType() {return valueType;}@@ -240,19 +233,19 @@ public enum AssetMeta implements HasMetaName {* types we can edit/have editor UI for. We inspect the actual JSON value and*/public enum EditableType {- STRING("String", JsonType.STRING),- NUMBER("Number", JsonType.NUMBER),- BOOLEAN("Boolean", JsonType.BOOLEAN);+ STRING("String", ValueType.STRING),+ NUMBER("Number", ValueType.NUMBER),+ BOOLEAN("Boolean", ValueType.BOOLEAN);- EditableType(String label, JsonType valueType) {+ EditableType(String label, ValueType valueType) {this.label = label;this.valueType = valueType;}public final String label;- public final JsonType valueType;+ public final ValueType valueType;- public static EditableType byValueType(JsonType valueType) {+ public static EditableType byValueType(ValueType valueType) {for (EditableType vt : values()) {if (vt.valueType == valueType)return vt;diff --git a/model/src/main/java/org/openremote/model/asset/AssetQuery.java b/model/src/main/java/org/openremote/model/asset/AssetQuery.javaindex 6b5ad57a3..dd2be50b1 100644--- a/model/src/main/java/org/openremote/model/asset/AssetQuery.java+++ b/model/src/main/java/org/openremote/model/asset/AssetQuery.java@@ -19,7 +19,7 @@*/package org.openremote.model.asset;-import org.openremote.model.AttributeRef;+import org.openremote.model.attribute.AttributeRef;import java.util.Locale;diff --git a/model/src/main/java/org/openremote/model/asset/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.javaindex b23a83804..c99c462fb 100644--- a/model/src/main/java/org/openremote/model/asset/AssetState.java+++ b/model/src/main/java/org/openremote/model/asset/AssetState.java@@ -19,7 +19,7 @@*/package org.openremote.model.asset;-import elemental.json.JsonValue;+import org.openremote.model.value.Value;/*** An asset attribute value update, capturing that asset state at a point in time.@@ -65,7 +65,7 @@ public class AssetState extends AbstractAssetUpdate {super(asset, attribute);}- public AssetState(Asset asset, AssetAttribute attribute, JsonValue oldValue, long oldValueTimestamp, boolean northbound) {+ public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, boolean northbound) {super(asset, attribute, oldValue, oldValueTimestamp, northbound);}@@ -88,22 +88,7 @@ public class AssetState extends AbstractAssetUpdate {// GETTERS AND SETTERS BELOW CAN ONLY BE USED WHEN STATUS IS NOT COMPLETED/////////////////////////////////////////////////////////////////- public AssetAttribute getAttribute() {- if (!isCompleted()) {- return attribute;- }- throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);- }-- public void setValue(JsonValue value) {- if (!isCompleted()) {- attribute.setValue(value);- } else {- throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);- }- }-- public void setValueUnchecked(JsonValue value) {+ public void setValue(Value value) {if (!isCompleted()) {attribute.setValue(value);} else {diff --git a/model/src/main/java/org/openremote/model/asset/AssetType.java b/model/src/main/java/org/openremote/model/asset/AssetType.javaindex a0949f721..6f5f2491e 100644--- a/model/src/main/java/org/openremote/model/asset/AssetType.java+++ b/model/src/main/java/org/openremote/model/asset/AssetType.java@@ -19,17 +19,17 @@*/package org.openremote.model.asset;-import elemental.json.Json;-import org.openremote.model.AttributeType;-import org.openremote.model.MetaItem;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.MetaItem;+import org.openremote.model.value.Values;import java.util.*;import java.util.stream.Stream;-import static org.openremote.model.AttributeType.INTEGER;-import static org.openremote.model.AttributeType.STRING;import static org.openremote.model.Constants.ASSET_NAMESPACE;import static org.openremote.model.asset.AssetMeta.*;+import static org.openremote.model.attribute.AttributeType.INTEGER;+import static org.openremote.model.attribute.AttributeType.STRING;/*** Asset type is an arbitrary string. It should be URI. This enum contains@@ -44,29 +44,29 @@ public enum AssetType {BUILDING(ASSET_NAMESPACE + ":building", "building", Arrays.asList(new AssetAttribute("area", INTEGER).setMeta(- new MetaItem(LABEL, Json.create("Surface area")),- new MetaItem(DESCRIPTION, Json.create("Floor area of building measured in m²")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/area"))+ new MetaItem(LABEL, Values.create("Surface area")),+ new MetaItem(DESCRIPTION, Values.create("Floor area of building measured in m²")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/area"))),new AssetAttribute("geoStreet", STRING).setMeta(- new MetaItem(LABEL, Json.create("Street")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoStreet"))+ new MetaItem(LABEL, Values.create("Street")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoStreet"))),new AssetAttribute("geoPostalCode", AttributeType.INTEGER).setMeta(- new MetaItem(LABEL, Json.create("Postal Code")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoPostalCode"))+ new MetaItem(LABEL, Values.create("Postal Code")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoPostalCode"))),new AssetAttribute("geoCity", STRING).setMeta(- new MetaItem(LABEL, Json.create("City")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCity"))+ new MetaItem(LABEL, Values.create("City")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCity"))),new AssetAttribute("geoCountry", STRING).setMeta(- new MetaItem(LABEL, Json.create("Country")),- new MetaItem(ABOUT, Json.create("http://project-haystack.org/tag/geoCountry"))+ new MetaItem(LABEL, Values.create("Country")),+ new MetaItem(ABOUT, Values.create("http://project-haystack.org/tag/geoCountry"))))),FLOOR(ASSET_NAMESPACE + ":floor", "server", null),diff --git a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.javaindex 13879795f..a84913a27 100644--- a/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java+++ b/model/src/main/java/org/openremote/model/asset/ReadAssetAttributesEvent.java@@ -19,7 +19,7 @@*/package org.openremote.model.asset;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.event.shared.SharedEvent;import java.util.Arrays;diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.javaindex 652805b71..f4cfe8fe1 100644--- a/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentLink.java@@ -20,15 +20,15 @@package org.openremote.model.asset.agent;import org.openremote.model.AbstractValueHolder;-import org.openremote.model.Attribute;-import org.openremote.model.AttributeRef;-import org.openremote.model.MetaItem;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.MetaItem;import org.openremote.model.asset.AssetMeta;import java.util.Optional;-import static org.openremote.model.MetaItem.isMetaNameEqualTo;-import static org.openremote.model.MetaItem.replaceMetaByName;+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;+import static org.openremote.model.attribute.MetaItem.replaceMetaByName;import static org.openremote.model.asset.AssetMeta.AGENT_LINK;/**@@ -54,14 +54,14 @@ final public class AgentLink {}public static MetaItem asAgentLinkMetaItem(AttributeRef attributeRef) {- return new MetaItem(AGENT_LINK, attributeRef.toJsonValue());+ return new MetaItem(AGENT_LINK, attributeRef.toArrayValue());}public static <A extends Attribute> Optional<AttributeRef> getAgentLink(A attribute) {return attribute == null ? Optional.empty() :attribute.getMetaItem(AGENT_LINK).flatMap(AbstractValueHolder::getValue)- .flatMap(AttributeRef::fromJsonValue);+ .flatMap(AttributeRef::fromValue);}public static <A extends Attribute> void setAgentLink(A attribute, AttributeRef attributeRef) {diff --git a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.javaindex 6c939e419..cba6ee0bc 100644--- a/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java+++ b/model/src/main/java/org/openremote/model/asset/agent/ProtocolConfiguration.java@@ -19,11 +19,11 @@*/package org.openremote.model.asset.agent;-import elemental.json.Json;-import org.openremote.model.AttributeType;import org.openremote.model.Constants;-import org.openremote.model.Meta;import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.attribute.Meta;+import org.openremote.model.value.Values;import java.util.Locale;import java.util.Optional;@@ -56,8 +56,8 @@ final public class ProtocolConfiguration {isValidProtocolNameOrThrow(protocolName);attribute.setEnabled(true);- attribute.setType(AttributeType.STRING);- attribute.setValue(Json.create(protocolName));+ attribute.setTypeAndClearValue(AttributeType.STRING);+ attribute.setValue(Values.create(protocolName));return attribute;}@@ -96,7 +96,7 @@ final public class ProtocolConfiguration {return null;}isValidProtocolNameOrThrow(protocolName);- attribute.setValue(Json.create(protocolName));+ attribute.setValue(Values.create(protocolName));return attribute;}diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.javanew file mode 100644index 000000000..0f71817d9--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java@@ -0,0 +1,205 @@+/*+ * 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.attribute;++import com.google.gwt.regexp.shared.RegExp;+import org.openremote.model.AbstractValueTimestampHolder;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Arrays;+import java.util.List;+import java.util.Objects;+import java.util.Optional;+import java.util.function.Predicate;+import java.util.stream.Stream;++import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;++/**+ * Convenience wrapper API for {@link ObjectValue}.+ */+public abstract class Attribute extends AbstractValueTimestampHolder {++ /**+ * Attribute names should be very simple, as we use them in SQL path+ * expressions, etc. and must manually escape.+ */+ public static final String ATTRIBUTE_NAME_PATTERN = "^\\w+$";+ public static final RegExp ATTRIBUTE_NAME_REGEXP = RegExp.compile(ATTRIBUTE_NAME_PATTERN);+ public static final Predicate<String> ATTRIBUTE_NAME_VALIDATOR =+ name -> name != null && name.length() > 0 && ATTRIBUTE_NAME_REGEXP.test(name);++ public static final String TYPE_FIELD_NAME = "type";+ public static final String META_FIELD_NAME = "meta";++ protected String name;++ protected Attribute(ObjectValue objectValue) {+ super(objectValue);+ }++ protected Attribute(String name) {+ super(Values.createObject());+ setName(name);+ }++ protected Attribute(String name, AttributeType type) {+ this(name);+ setName(name);+ setTypeAndClearValue(type);+ }++ protected Attribute(String name, AttributeType type, Value value) {+ this(name, type);+ setValue(value);+ }++ public Optional<String> getName() {+ return Optional.ofNullable(name);+ }++ public void setName(String name) {+ requireNonNullAndNonEmpty(name);+ this.name = name;+ }++ public Optional<AttributeType> getType() {+ return getObjectValue().getString(TYPE_FIELD_NAME).flatMap(AttributeType::optionalValueOf);+ }++ public void setTypeAndClearValue(AttributeType type) {+ Objects.requireNonNull(type);+ getObjectValue().put(TYPE_FIELD_NAME, Values.create(type.name()));++ // Remove existing value and timestamp+ clearValue();+ }++ public boolean hasMetaItems() {+ return getObjectValue().getArray(META_FIELD_NAME)+ .filter(arrayValue -> arrayValue.length() > 0)+ .isPresent();+ }++ public Meta getMeta() {+ if (!getObjectValue().hasKey(META_FIELD_NAME)) {+ // Create array object so don't have to call setMeta+ // can just update the collection like normal POJO behaviour+ getObjectValue().put(META_FIELD_NAME, Values.createArray());+ }+ return new Meta(getObjectValue()+ .getArray(META_FIELD_NAME)+ .orElseThrow(() -> new IllegalStateException("Attribute " + META_FIELD_NAME + "' field is not an array"))+ );+ }++ public Stream<MetaItem> getMetaStream() {+ return getMeta().stream();+ }++ public boolean hasMetaItem(String metaName) {+ return getMetaItem(metaName).isPresent();+ }++ public boolean hasMetaItem(HasMetaName metaName) {+ return getMetaItem(metaName).isPresent();+ }++ public Optional<MetaItem> getMetaItem(String metaName) {+ return getMetaStream()+ .filter(metaItem -> metaItem.getName().filter(s -> s.equals(metaName)).isPresent())+ .findFirst();+ }++ public Optional<MetaItem> getMetaItem(HasMetaName hasMetaName) {+ return getMetaItem(hasMetaName.getUrn());+ }++ public void setMeta(List<MetaItem> metaItems) {+ if (metaItems != null) {+ Meta meta;+ if (metaItems instanceof Meta) {+ meta = (Meta) metaItems;+ } else {+ meta = new Meta();+ meta.addAll(metaItems);+ }+ getObjectValue().put(META_FIELD_NAME, meta.getArrayValue());+ } else {+ getObjectValue().remove(META_FIELD_NAME);+ }+ }++ public Attribute setMeta(Meta meta) {+ setMeta((List<MetaItem>) meta);+ return this;+ }++ public Attribute setMeta(MetaItem... meta) {+ setMeta(Arrays.asList(meta));+ return this;+ }++ @Override+ public boolean isValid() {+ return super.isValid()+ // Must have a valid name+ && getName().isPresent()+ && ATTRIBUTE_NAME_VALIDATOR.test(getName().get()) && (+ // and either have no value+ !getValue().isPresent()+ // or have a timestamp and a type that validates the value+ || (hasValueTimestamp() && isValidValue(getValue().get()))+ );+ }++ public boolean isValidValue(Value value) {+ return getType().filter(type -> type.isValid(value)).isPresent();+ }++ // ---------------------------------------------------+ // FUNCTIONAL METHODS BELOW+ // ---------------------------------------------------++ public static <A extends Attribute> boolean isAttributeNameEqualTo(A attribute, String name) {+ return attribute != null+ && attribute.getName().filter(attributeName -> attributeName.equals(name)).isPresent();+ }++ public static <A extends Attribute> Predicate<A> isAttributeNameEqualTo(String name) {+ return attribute -> isAttributeNameEqualTo(attribute, name);+ }++ public static <A extends Attribute> boolean isAttributeTypeEqualTo(A attribute, AttributeType type) {+ if (attribute == null)+ return false;++ return attribute+ .getType()+ .map(attributeType -> attributeType == type)+ .orElse(type == null);+ }++ public static <A extends Attribute> Predicate<A> isAttributeTypeEqualTo(AttributeType type) {+ return attribute -> isAttributeTypeEqualTo(attribute, type);+ }+}diff --git a/model/src/main/java/org/openremote/model/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.javasimilarity index 93%rename from model/src/main/java/org/openremote/model/AttributeEvent.javarename to model/src/main/java/org/openremote/model/attribute/AttributeEvent.javaindex a70816db7..79cdfed93 100644--- a/model/src/main/java/org/openremote/model/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java@@ -17,11 +17,11 @@* 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;+package org.openremote.model.attribute;-import elemental.json.JsonValue;import org.openremote.model.event.shared.EventFilter;import org.openremote.model.event.shared.SharedEvent;+import org.openremote.model.value.Value;import java.util.Objects;import java.util.Optional;@@ -98,15 +98,15 @@ public class AttributeEvent extends SharedEvent {protected AttributeEvent() {}- public AttributeEvent(String entityId, String attributeName, JsonValue value) {+ public AttributeEvent(String entityId, String attributeName, Value value) {this(new AttributeState(new AttributeRef(entityId, attributeName), value));}- public AttributeEvent(String entityId, String attributeName, JsonValue value, long timestamp) {+ public AttributeEvent(String entityId, String attributeName, Value value, long timestamp) {this(new AttributeState(new AttributeRef(entityId, attributeName), value), timestamp);}- public AttributeEvent(AttributeRef attributeRef, JsonValue value) {+ public AttributeEvent(AttributeRef attributeRef, Value value) {this(new AttributeState(attributeRef, value));}@@ -136,8 +136,8 @@ public class AttributeEvent extends SharedEvent {return getAttributeRef().getAttributeName();}- public Optional<JsonValue> getValue() {- return getAttributeState().getValue();+ public Optional<Value> getValue() {+ return getAttributeState().getCurrentValue();}@Overridediff --git a/model/src/main/java/org/openremote/model/AttributeExecuteStatus.java b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.javasimilarity index 82%rename from model/src/main/java/org/openremote/model/AttributeExecuteStatus.javarename to model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.javaindex b46b3513d..05004f1ef 100644--- a/model/src/main/java/org/openremote/model/AttributeExecuteStatus.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeExecuteStatus.java@@ -17,10 +17,12 @@* 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;+package org.openremote.model.attribute;-import elemental.json.Json;-import elemental.json.JsonValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Optional;public enum AttributeExecuteStatus {@@ -67,19 +69,19 @@ public enum AttributeExecuteStatus {this.write = write;}- public JsonValue asJsonValue() {- return Json.create(this.toString());+ public Value asValue() {+ return Values.create(this.toString());}public boolean isWrite() {return write;}- public static AttributeExecuteStatus fromString(String value) {+ public static Optional<AttributeExecuteStatus> fromString(String value) {for (AttributeExecuteStatus status : copyOfValues) {if (status.name().equalsIgnoreCase(value))- return status;+ return Optional.of(status);}- return null;+ return Optional.empty();}}diff --git a/model/src/main/java/org/openremote/model/AttributeRef.java b/model/src/main/java/org/openremote/model/attribute/AttributeRef.javasimilarity index 58%rename from model/src/main/java/org/openremote/model/AttributeRef.javarename to model/src/main/java/org/openremote/model/attribute/AttributeRef.javaindex b042989e2..f0830a221 100644--- a/model/src/main/java/org/openremote/model/AttributeRef.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeRef.java@@ -17,19 +17,15 @@* 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;+package org.openremote.model.attribute;-import com.fasterxml.jackson.annotation.JsonCreator;-import com.fasterxml.jackson.annotation.JsonProperty;-import elemental.json.Json;-import elemental.json.JsonArray;-import elemental.json.JsonValue;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Optional;-import static org.openremote.model.util.JsonUtil.asJsonArray;-import static org.openremote.model.util.JsonUtil.isOfTypeString;-/*** A reference to an entity and an {@link Attribute}.* <p>@@ -44,10 +40,8 @@ public class AttributeRef {protected String entityId;protected String attributeName;- /**- * Needed for deserialisation- */- protected AttributeRef() {}+ protected AttributeRef() {+ }public AttributeRef(String entityId, String attributeName) {this.entityId = entityId;@@ -85,40 +79,32 @@ public class AttributeRef {'}';}- public JsonArray toJsonValue() {- JsonArray jsonArray = Json.createArray();- jsonArray.set(0, Json.create(getEntityId()));- jsonArray.set(1, Json.create(getAttributeName()));- return jsonArray;+ public ArrayValue toArrayValue() {+ ArrayValue arrayValue = Values.createArray();+ arrayValue.set(0, Values.create(getEntityId()));+ arrayValue.set(1, Values.create(getAttributeName()));+ return arrayValue;}public static boolean isAttributeRef(AbstractValueHolder valueHolder) {- return valueHolder != null && valueHolder.getValueAsJsonArray()- .map(AttributeRef::isAttributeRef)- .orElse(false);+ return valueHolder != null+ && valueHolder.getValueAsArray().filter(AttributeRef::isAttributeRef).isPresent();}- public static boolean isAttributeRef(JsonValue jsonValue) {- return asJsonArray(jsonValue)- .map(jsonArray ->- jsonArray.length() == 2- && isOfTypeString(jsonArray.get(0))- && isOfTypeString(jsonArray.get(1))- && !jsonArray.getString(0).isEmpty()- && !jsonArray.getString(1).isEmpty()- )- .orElse(false);+ public static boolean isAttributeRef(Value value) {+ return Values.getArray(value)+ .filter(arrayValue ->+ arrayValue.length() == 2+ && arrayValue.getString(0).filter(s -> !s.isEmpty()).isPresent()+ && arrayValue.getString(1).filter(s -> !s.isEmpty()).isPresent()+ ).isPresent();}- public static Optional<AttributeRef> fromJsonValue(JsonValue jsonValue) {- return asJsonArray(jsonValue)- .map(jsonArray -> !isAttributeRef(jsonArray)- ? null- : new AttributeRef(jsonArray.getString(0), jsonArray.getString(1))+ public static Optional<AttributeRef> fromValue(Value value) {+ return Values.getArray(value)+ .filter(AttributeRef::isAttributeRef)+ .map(arrayValue ->+ new AttributeRef(arrayValue.getString(0).get(), arrayValue.getString(1).get()));}-- public static JsonValue toJsonValue(AttributeRef attributeRef) {- return attributeRef.toJsonValue();- }}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/attribute/AttributeState.java b/model/src/main/java/org/openremote/model/attribute/AttributeState.javanew file mode 100644index 000000000..d9dbcd86d--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeState.java@@ -0,0 +1,91 @@+/*+ * 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.attribute;++import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Objects;+import java.util.Optional;++/**+ * The desired or current or past state of an {@link AttributeRef}.+ */+public class AttributeState {++ protected AttributeRef attributeRef;+ protected Value value;++ protected AttributeState() {+ }++ /**+ * @param value can be <code>null</code> if the attribute has no value.+ */+ public AttributeState(AttributeRef attributeRef, Value value) {+ this.attributeRef = Objects.requireNonNull(attributeRef);+ this.value = value;+ }++ public AttributeRef getAttributeRef() {+ return attributeRef;+ }++ // TODO GWT Jackson does not like fields that have a getter with a different type than the field, so rename getter+ public Optional<Value> getCurrentValue() {+ return Optional.ofNullable(value);+ }++ public ObjectValue toObjectValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("attributeRef", getAttributeRef().toArrayValue());+ getCurrentValue().ifPresent(v -> objectValue.put("value", value));+ return objectValue;+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "attributeRef=" + attributeRef ++ ", value=" + value ++ '}';+ }++ public static boolean isAttributeState(Value value) {+ return Values.getObject(value)+ .flatMap(objectValue -> objectValue.get("attributeRef"))+ .filter(AttributeRef::isAttributeRef)+ .isPresent();+ }++ public static Optional<AttributeState> fromValue(Value value) {+ return Values.getObject(value)+ .filter(AttributeState::isAttributeState)+ .map(objectValue -> new Pair<>(+ AttributeRef.fromValue(objectValue.get("attributeRef").get()),+ objectValue.get("value")+ )+ )+ .filter(pair -> pair.key.isPresent())+ .map(pair -> new AttributeState(pair.key.get(), pair.value.orElse(null)));+ }+}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/attribute/AttributeType.java b/model/src/main/java/org/openremote/model/attribute/AttributeType.javanew file mode 100644index 000000000..bf579038e--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeType.java@@ -0,0 +1,150 @@+/*+ * 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.attribute;++import org.openremote.model.value.Value;+import org.openremote.model.value.ValueType;++import java.util.Optional;+import java.util.function.Function;++/**+ * The type of an {@link Attribute}, how its {@link Value} should be+ * interpreted when working with an attribute (e.g. when testing, rendering,+ * or editing the value).+ * <p>+ * Additional constraints and integrity rules upon attribute values can be declared by+ * adding arbitrary {@link Meta} to an {@link Attribute}.+ */+public enum AttributeType {++ // TODO Implement validator functions!++ STRING("String", ValueType.STRING, value -> Optional.empty()),++ INTEGER("Integer", ValueType.NUMBER, value -> Optional.empty()),++ DECIMAL("Decimal", ValueType.NUMBER, value -> Optional.empty()),++ BOOLEAN("Boolean", ValueType.BOOLEAN, value -> Optional.empty()),++ PERCENTAGE("Percentage", ValueType.NUMBER, value -> Optional.empty()),++ TIMESTAMP_MILLIS("Timestamp milliseconds", ValueType.NUMBER, value -> Optional.empty()),++ DATETIME("Timestamp in ISO 8601", ValueType.STRING, value -> Optional.empty()),++ COLOR_RGB("Color RGB", ValueType.ARRAY, value -> Optional.empty()),++ COLOR_ARGB("Color ARGB", ValueType.ARRAY, value -> Optional.empty()),++ COLOR_HEX("Color HEX", ValueType.STRING, value -> Optional.empty()),++ TEMPERATURE_CELCIUS("Temperature in Celcius", ValueType.NUMBER, value -> Optional.empty()),++ TEMPERATURE_KELVIN("Temperature in Kelvin", ValueType.NUMBER, value -> Optional.empty()),++ TEMPERATURE_FAHRENHEIT("Temperature in Fahrenheit", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_M("Distance in meters", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_CM("Distance in centimeters", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_MM("Distance in millimeters", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_IN("Distance in inch", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_FT("Distance in feet", ValueType.NUMBER, value -> Optional.empty()),++ DISTANCE_YARD("Dinstance in yard", ValueType.NUMBER, value -> Optional.empty()),++ CO2_PPM("CO2 Level in PPM", ValueType.NUMBER, value -> Optional.empty()),++ HUMIDITY_PERCENTAGE("Humidity percentage", ValueType.NUMBER, value -> Optional.empty()),++ HUMIDITY_GPCM("Humidity in grams per cubic meter", ValueType.NUMBER, value -> Optional.empty()),++ POWER_WATT("Power in watt", ValueType.NUMBER, value -> Optional.empty()),++ POWER_KILOWATT("Power in kilowatt", ValueType.NUMBER, value -> Optional.empty()),++ POWER_MEGAWATT("Power in megawatt", ValueType.NUMBER, value -> Optional.empty()),++ CHARGE_PERCENTAGE("Charge percentage", ValueType.NUMBER, value -> Optional.empty()),++ CHARGE_KWH("Charge in kilowatt-hours", ValueType.NUMBER, value -> Optional.empty()),++ ENERGY_KWH("Energy in kilowatt-hours", ValueType.NUMBER, value -> Optional.empty()),++ ENERGY_JOULE("Energy in joule", ValueType.NUMBER, value -> Optional.empty()),++ ENERGY_MEGAJOULE("Energy in megajoule", ValueType.NUMBER, value -> Optional.empty()),++ FLOW_LPM("Flow in litre per minute", ValueType.NUMBER, value -> Optional.empty()),++ FLOW_CMPS("Flow in cubic metres per second", ValueType.NUMBER, value -> Optional.empty()),++ FLOW_SCCM("Flow in cubic centimetres per minute", ValueType.NUMBER, value -> Optional.empty()),++ FLOW_CFPS("Flow in cubic feet per second", ValueType.NUMBER, value -> Optional.empty()),++ FLOW_GPM("Flow in gallons per minute", ValueType.NUMBER, value -> Optional.empty());++ protected String displayName;+ protected ValueType valueType;+ protected Function<Value, Optional<String>> validator;++ AttributeType(String displayName, ValueType valueType, Function<Value, Optional<String>> validator) {+ this.displayName = displayName;+ this.valueType = valueType;++ this.validator = value -> {+ // Always perform some basic validation+ if (value != null && getValueType() != value.getType())+ return Optional.of("Value is " + value.getType() + ", but must be " + getValueType());++ // Custom attribute type validation+ return validator.apply(value);+ };+ }++ public String getDisplayName() {+ return displayName;+ }++ public ValueType getValueType() {+ return valueType;+ }++ public boolean isValid(Value value) {+ return !getValidationFailure(value).isPresent();+ }+ public Optional<String> getValidationFailure(Value value) {+ return validator.apply(value);+ }++ public static Optional<AttributeType> optionalValueOf(String name) {+ try {+ return Optional.of(valueOf(name));+ } catch (Exception ex) {+ return Optional.empty();+ }+ }+}diff --git a/model/src/main/java/org/openremote/model/units/ColorRGB.java b/model/src/main/java/org/openremote/model/attribute/ColorRGB.javasimilarity index 71%rename from model/src/main/java/org/openremote/model/units/ColorRGB.javarename to model/src/main/java/org/openremote/model/attribute/ColorRGB.javaindex 7ec6d76ee..c5c7009eb 100644--- a/model/src/main/java/org/openremote/model/units/ColorRGB.java+++ b/model/src/main/java/org/openremote/model/attribute/ColorRGB.java@@ -17,10 +17,10 @@* 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.units;+package org.openremote.model.attribute;-import elemental.json.Json;-import elemental.json.JsonArray;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Values;public class ColorRGB {@@ -34,11 +34,15 @@ public class ColorRGB {this.blue = blue;}- public ColorRGB(JsonArray jsonArray) {+ public ColorRGB(double red, double green, double blue) {+ this(new Double(red).intValue(), new Double(green).intValue(), new Double(blue).intValue());+ }++ public ColorRGB(ArrayValue arrayValue) {this(- (int)jsonArray.get(0).asNumber(),- (int)jsonArray.get(1).asNumber(),- (int)jsonArray.get(2).asNumber()+ arrayValue.getNumber(0).orElseThrow(() -> new IllegalArgumentException("Element 0 must be a number")),+ arrayValue.getNumber(1).orElseThrow(() -> new IllegalArgumentException("Element 1 must be a number")),+ arrayValue.getNumber(2).orElseThrow(() -> new IllegalArgumentException("Element 2 must be a number")));}@@ -54,11 +58,11 @@ public class ColorRGB {return blue;}- public JsonArray asJsonValue() {- JsonArray array = Json.createArray();- array.set(0, Json.create(getRed()));- array.set(1, Json.create(getGreen()));- array.set(2, Json.create(getBlue()));+ public ArrayValue asArrayValue() {+ ArrayValue array = Values.createArray();+ array.set(0, Values.create(getRed()));+ array.set(1, Values.create(getGreen()));+ array.set(2, Values.create(getBlue()));return array;}diff --git a/model/src/main/java/org/openremote/model/HasMetaName.java b/model/src/main/java/org/openremote/model/attribute/HasMetaName.javasimilarity index 95%rename from model/src/main/java/org/openremote/model/HasMetaName.javarename to model/src/main/java/org/openremote/model/attribute/HasMetaName.javaindex 595cc83d9..3d5675240 100644--- a/model/src/main/java/org/openremote/model/HasMetaName.java+++ b/model/src/main/java/org/openremote/model/attribute/HasMetaName.java@@ -17,7 +17,7 @@* 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;+package org.openremote.model.attribute;/*** This is an interface for indicating that a typediff --git a/model/src/main/java/org/openremote/model/Meta.java b/model/src/main/java/org/openremote/model/attribute/Meta.javasimilarity index 57%rename from model/src/main/java/org/openremote/model/Meta.javarename to model/src/main/java/org/openremote/model/attribute/Meta.javaindex e8f0e6d61..68367fb2a 100644--- a/model/src/main/java/org/openremote/model/Meta.java+++ b/model/src/main/java/org/openremote/model/attribute/Meta.java@@ -17,85 +17,94 @@* 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;+package org.openremote.model.attribute;-import elemental.json.Json;-import elemental.json.JsonArray;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Values;import java.util.AbstractList;import java.util.Collections;+import java.util.NoSuchElementException;+import java.util.Objects;/**- * A {@link java.util.List} of {@link MetaItem} elements.+ * A {@link java.util.List} of {@link MetaItem} elements, wrapping an {@link ArrayValue}.* <p>* Note that duplicate item names are allowed for multi-valued elements.- **/public class Meta extends AbstractList<MetaItem> {- final protected JsonArray jsonArray;+ final protected ArrayValue arrayValue;public Meta() {- this(Json.createArray());+ this(Values.createArray());}public Meta(MetaItem... items) {- this(Json.createArray());+ this(Values.createArray());Collections.addAll(this, items);}- public Meta(JsonArray jsonArray) {- this.jsonArray = jsonArray;+ public Meta(ArrayValue arrayValue) {+ this.arrayValue = Objects.requireNonNull(arrayValue);}- public JsonArray getJsonArray() {- return jsonArray;+ public ArrayValue getArrayValue() {+ return arrayValue;}@Overridepublic int size() {- return getJsonArray().length();+ return arrayValue.length();}+ /**+ * @throws IndexOutOfBoundsException if the index is out of bounds.+ * @throws NoSuchElementException if there is no value at the given index.+ */@Overridepublic MetaItem get(int index) {checkBounds(index);- return new MetaItem(jsonArray.getObject(index));+ return new MetaItem(+ arrayValue.getObject(index)+ .orElseThrow(() -> new NoSuchElementException("At index: " + index))+ );}@Overridepublic MetaItem set(int index, MetaItem metaItem) {checkBounds(index);- jsonArray.set(index, metaItem.getJsonObject());-+ arrayValue.set(index, metaItem.getObjectValue());return super.set(index, metaItem);}@Overridepublic void add(int index, MetaItem item) {- checkBounds(index-1);- jsonArray.set(index, item.getJsonObject());+ checkBounds(index == 0 ? 0 : index-1);+ arrayValue.add(index, item.getObjectValue());}@Overridepublic MetaItem remove(int index) {checkBounds(index);MetaItem item = get(index);- jsonArray.remove(index);+ arrayValue.remove(index);return item;}public Meta copy() {- return new Meta((JsonArray) Json.parse(getJsonArray().toJson()));+ return new Meta(getArrayValue().deepCopy());}@Overridepublic String toString() {- return jsonArray.toJson();+ return getClass().getSimpleName() + "{" ++ getArrayValue().toJson() ++ '}';}protected void checkBounds(int index) {- if (index >= size())+ if (index != 0 && (index < 0 || index >= size()))throw new IndexOutOfBoundsException("Index out of bounds: " + index);}}diff --git a/model/src/main/java/org/openremote/model/MetaItem.java b/model/src/main/java/org/openremote/model/attribute/MetaItem.javasimilarity index 68%rename from model/src/main/java/org/openremote/model/MetaItem.javarename to model/src/main/java/org/openremote/model/attribute/MetaItem.javaindex 18f5ca4e8..1654a5a2c 100644--- a/model/src/main/java/org/openremote/model/MetaItem.java+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java@@ -17,47 +17,45 @@* 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;+package org.openremote.model.attribute;-import elemental.json.Json;-import elemental.json.JsonObject;-import elemental.json.JsonValue;-import org.openremote.model.util.JsonUtil;+import org.openremote.model.AbstractValueHolder;import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;import java.util.Collection;import java.util.Objects;import java.util.Optional;import java.util.function.Predicate;-import static org.openremote.model.util.JsonUtil.sanitizeJsonValue;-/**- * A named arbitrary {@link JsonValue}.+ * A named arbitrary {@link Value}.* <p>* Name should be a URI, thus avoiding collisions and representing "ownership" of the meta item.*/public class MetaItem extends AbstractValueHolder {public MetaItem() {- this(Json.createObject());+ this(Values.createObject());}- public MetaItem(JsonObject jsonObject) {- super(jsonObject);+ public MetaItem(ObjectValue objectValue) {+ super(objectValue);}public MetaItem(String name) {this(name, null);}- public MetaItem(String name, JsonValue value) {- super(Json.createObject());+ public MetaItem(String name, Value value) {+ super(Values.createObject());setName(name);setValue(value);}- public MetaItem(HasMetaName hasMetaName, JsonValue value) {+ public MetaItem(HasMetaName hasMetaName, Value value) {this(hasMetaName.getUrn(), value);}@@ -66,18 +64,11 @@ public class MetaItem extends AbstractValueHolder {}public Optional<String> getName() {- if (jsonObject == null) {- return Optional.empty();- }-- return JsonUtil- .asString((JsonValue)jsonObject.get("name"))- .map(str -> str.isEmpty() ? null : str);+ return getObjectValue().getString("name");}public void setName(String name) {- TextUtil.requireNonNullAndNonEmpty(name);- jsonObject.put("name", name);+ getObjectValue().put("name", TextUtil.requireNonNullAndNonEmpty(name));}@Override@@ -86,7 +77,7 @@ public class MetaItem extends AbstractValueHolder {}public MetaItem copy() {- return new MetaItem(Json.parse(getJsonObject().toJson()));+ return new MetaItem(getObjectValue().deepCopy());}@Override@@ -102,31 +93,20 @@ public class MetaItem extends AbstractValueHolder {}MetaItem metaItem = (MetaItem) o;- return Objects.equals(getName(), metaItem.getName()) &&- JsonUtil.equals(getValue().orElse(null), metaItem.getValue().orElse(null));+ return Objects.equals(getName(), metaItem.getName())+ && getValue().equals(metaItem.getValue());}@Overridepublic String toString() {- return "MetaItem{" +- jsonObject.toJson() ++ return getClass().getSimpleName() + "{" ++ getObjectValue().toJson() +'}';}-// ----------------------------------------------------// FUNCTIONAL METHODS BELOW-// ----------------------------------------------------- public static boolean equals(MetaItem item1, MetaItem item2) {- if (item1 == null && item2 == null)- return true;-- if (item1 == null || item2 == null)- return false;-- Optional<String> name = item2.getName();- return isMetaNameEqualTo(item1, name.orElse(null)) && JsonUtil.equals(item1.getValue().orElse(null), item2.getValue().orElse(null));- }+ // ---------------------------------------------------+ // FUNCTIONAL METHODS BELOW+ // ---------------------------------------------------public static boolean isMetaNameEqualTo(MetaItem item, String name) {if (item == null)@@ -148,14 +128,14 @@ public class MetaItem extends AbstractValueHolder {return metaItem -> isMetaNameEqualTo(metaItem, hasMetaName);}-// STREAM AND COLLECTION METHODS BELOW+ // STREAM AND COLLECTION METHODS BELOWpublic static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, String name, MetaItem newMetaItem) {metaItems.removeIf(isMetaNameEqualTo(name));metaItems.add(newMetaItem);}- public static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, String name, JsonValue newValue) {+ public static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, String name, Value newValue) {metaItems.removeIf(isMetaNameEqualTo(name));metaItems.add(new MetaItem(name, newValue));}@@ -165,7 +145,7 @@ public class MetaItem extends AbstractValueHolder {metaItems.addAll(newMetaItems);}- public static <T extends Collection<MetaItem>, V extends Collection<JsonValue>> void replaceMetaByNameWithValues(T metaItems, String name, V newValues) {+ public static <T extends Collection<MetaItem>, V extends Collection<Value>> void replaceMetaByNameWithValues(T metaItems, String name, V newValues) {metaItems.removeIf(isMetaNameEqualTo(name));newValues.stream()@@ -177,7 +157,7 @@ public class MetaItem extends AbstractValueHolder {replaceMetaByName(metaItems, hasMetaName.getUrn(), newMetaItem);}- public static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, HasMetaName hasMetaName, JsonValue newValue) {+ public static <T extends Collection<MetaItem>> void replaceMetaByName(T metaItems, HasMetaName hasMetaName, Value newValue) {replaceMetaByName(metaItems, hasMetaName.getUrn(), newValue);}@@ -185,7 +165,7 @@ public class MetaItem extends AbstractValueHolder {replaceMetaByName(metaItems, hasMetaName.getUrn(), newMetaItems);}- public static <T extends Collection<MetaItem>, V extends Collection<JsonValue>> void replaceMetaByNameWithValues(T metaItems, HasMetaName hasMetaName, V newValues) {+ public static <T extends Collection<MetaItem>, V extends Collection<Value>> void replaceMetaByNameWithValues(T metaItems, HasMetaName hasMetaName, V newValues) {replaceMetaByNameWithValues(metaItems, hasMetaName.getUrn(), newValues);}}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.javaindex 60b795bdb..70ac9154a 100644--- a/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java+++ b/model/src/main/java/org/openremote/model/datapoint/AssetDatapoint.java@@ -19,10 +19,10 @@*/package org.openremote.model.datapoint;-import elemental.json.JsonValue;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;import javax.persistence.Entity;import javax.persistence.Table;@@ -47,19 +47,19 @@ public class AssetDatapoint extends Datapoint {super(attributeState, timestamp);}- public AssetDatapoint(AttributeRef attributeRef, JsonValue value) {+ public AssetDatapoint(AttributeRef attributeRef, Value value) {super(attributeRef, value);}- public AssetDatapoint(AttributeRef attributeRef, JsonValue value, long timestamp) {+ public AssetDatapoint(AttributeRef attributeRef, Value value, long timestamp) {super(attributeRef, value, timestamp);}- public AssetDatapoint(String entityId, String attributeName, JsonValue value) {+ public AssetDatapoint(String entityId, String attributeName, Value value) {super(entityId, attributeName, value);}- public AssetDatapoint(String entityId, String attributeName, JsonValue value, long timestamp) {+ public AssetDatapoint(String entityId, String attributeName, Value value, long timestamp) {super(entityId, attributeName, value, timestamp);}}diff --git a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java b/model/src/main/java/org/openremote/model/datapoint/Datapoint.javaindex 7e85fd501..c4ff915e0 100644--- a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java+++ b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java@@ -19,10 +19,10 @@*/package org.openremote.model.datapoint;-import elemental.json.JsonValue;-import org.openremote.model.AttributeEvent;-import org.openremote.model.AttributeRef;-import org.openremote.model.AttributeState;+import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.value.Value;import javax.persistence.Column;import javax.persistence.Id;@@ -56,13 +56,13 @@ public abstract class Datapoint implements Serializable {@Id@Column(name = "VALUE", columnDefinition = "jsonb", nullable = false)@org.hibernate.annotations.Type(type = PERSISTENCE_JSON_VALUE_TYPE)- protected JsonValue value;+ protected Value value;public Datapoint() {}public Datapoint(AttributeState attributeState) {- this(attributeState.getAttributeRef(), attributeState.getValue().orElse(null));+ this(attributeState.getAttributeRef(), attributeState.getCurrentValue().orElse(null));}public Datapoint(AttributeEvent stateEvent) {@@ -70,22 +70,22 @@ public abstract class Datapoint implements Serializable {}public Datapoint(AttributeState attributeState, long timestamp) {- this(attributeState.getAttributeRef(), attributeState.getValue().orElse(null), timestamp);+ this(attributeState.getAttributeRef(), attributeState.getCurrentValue().orElse(null), timestamp);}- public Datapoint(AttributeRef attributeRef, JsonValue value) {+ public Datapoint(AttributeRef attributeRef, Value value) {this(attributeRef.getEntityId(), attributeRef.getAttributeName(), value);}- public Datapoint(AttributeRef attributeRef, JsonValue value, long timestamp) {+ public Datapoint(AttributeRef attributeRef, Value value, long timestamp) {this(attributeRef.getEntityId(), attributeRef.getAttributeName(), value, timestamp);}- public Datapoint(String entityId, String attributeName, JsonValue value) {+ public Datapoint(String entityId, String attributeName, Value value) {this(entityId, attributeName, value, System.currentTimeMillis());}- public Datapoint(String entityId, String attributeName, JsonValue value, long timestamp) {+ public Datapoint(String entityId, String attributeName, Value value, long timestamp) {this.entityId = entityId;this.attributeName = attributeName;this.timestamp = timestamp;@@ -116,11 +116,11 @@ public abstract class Datapoint implements Serializable {this.timestamp = timestamp;}- public JsonValue getValue() {+ public Value getValue() {return value;}- public void setValue(JsonValue value) {+ public void setValue(Value value) {this.value = value;}diff --git a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java b/model/src/main/java/org/openremote/model/event/shared/EventFilter.javaindex d783255b3..0ee3badc5 100644--- a/model/src/main/java/org/openremote/model/event/shared/EventFilter.java+++ b/model/src/main/java/org/openremote/model/event/shared/EventFilter.java@@ -22,7 +22,7 @@ package org.openremote.model.event.shared;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.asset.AssetTreeModifiedEvent;/**diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.javaindex 587c1ece0..90c12841a 100644--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java@@ -22,7 +22,7 @@ package org.openremote.model.event.shared;import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.asset.ReadAssetAttributesEvent;import org.openremote.model.asset.AssetTreeModifiedEvent;import org.openremote.model.event.Event;diff --git a/model/src/main/java/org/openremote/model/notification/AlertAction.java b/model/src/main/java/org/openremote/model/notification/AlertAction.javaindex 7813b5839..adbfcea60 100644--- a/model/src/main/java/org/openremote/model/notification/AlertAction.java+++ b/model/src/main/java/org/openremote/model/notification/AlertAction.java@@ -1,22 +1,24 @@package org.openremote.model.notification;-import elemental.json.Json;-import elemental.json.JsonObject;+import org.openremote.model.AbstractTypeHolder;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Values;-public class AlertAction {+/**+ * Wraps {@link ObjectValue}.+ */+public class AlertAction extends AbstractTypeHolder {- private JsonObject jsonObject ;public AlertAction() {- jsonObject = Json.createObject();-+ super(Values.createObject());}- public AlertAction(String title, ActionType type,String assetId, String attributeName, String rawJson) {+ public AlertAction(String title, ActionType type, String assetId, String attributeName, String rawJson) {this();setTitle(title);- setType(type);+ setActionType(type);setAssetId(assetId);setAttributeName(attributeName);setRawJson(rawJson);@@ -24,61 +26,45 @@ public class AlertAction {private void setRawJson(String rawJson) {if (rawJson != null) {- jsonObject.put("rawJson", Json.create(rawJson));- } else if (jsonObject.hasKey("rawJson")) {- jsonObject.remove("rawJson");+ objectValue.put("rawJson", Values.create(rawJson));+ } else if (objectValue.hasKey("rawJson")) {+ objectValue.remove("rawJson");}}private void setAttributeName(String attributeName) {if (attributeName != null) {- jsonObject.put("attributeName", Json.create(attributeName));- } else if (jsonObject.hasKey("attributeName")) {- jsonObject.remove("attributeName");+ objectValue.put("attributeName", Values.create(attributeName));+ } else if (objectValue.hasKey("attributeName")) {+ objectValue.remove("attributeName");}}public String getTitle() {- if (jsonObject.hasKey("title")) {- return jsonObject.getString("title");- } else {- return null;- }+ return objectValue.getString("title").orElse(null);}public void setTitle(String title) {if (title != null) {- jsonObject.put("title", Json.create(title));- } else if (jsonObject.hasKey("title")) {- jsonObject.remove("title");- }- }-- public ActionType getType() {- if (jsonObject.hasKey("type")) {- return ActionType.valueOf(jsonObject.getString("type"));- } else {- return null;+ objectValue.put("title", Values.create(title));+ } else if (objectValue.hasKey("title")) {+ objectValue.remove("title");}}- public void setType(ActionType type) {- if (type != null) {- jsonObject.put("type", Json.create(type.name()));- } else if (jsonObject.hasKey("type")) {- jsonObject.remove("type");- }+ public ActionType getActionType() {+ return getType().map(ActionType::valueOf).orElse(null);}- public JsonObject getValue() {- return jsonObject;+ public void setActionType(ActionType type) {+ setType(type != null ? type.name() : null);}public void setAssetId(String assetId) {if (assetId != null) {- jsonObject.put("assetId", Json.create(assetId));- } else if (jsonObject.hasKey("assetId")) {- jsonObject.remove("assetId");+ objectValue.put("assetId", Values.create(assetId));+ } else if (objectValue.hasKey("assetId")) {+ objectValue.remove("assetId");}}}diff --git a/model/src/main/java/org/openremote/model/notification/AlertNotification.java b/model/src/main/java/org/openremote/model/notification/AlertNotification.javaindex ca924c032..adc28b3c9 100644--- a/model/src/main/java/org/openremote/model/notification/AlertNotification.java+++ b/model/src/main/java/org/openremote/model/notification/AlertNotification.java@@ -1,14 +1,11 @@package org.openremote.model.notification;-import elemental.json.Json;-import elemental.json.JsonArray;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Values;import javax.persistence.*;import javax.validation.constraints.NotNull;-import java.util.ArrayList;-import java.util.List;-import static org.openremote.model.Constants.PERSISTENCE_JSON_ARRAY_TYPE;import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;@@ -31,7 +28,7 @@ public class AlertNotification {@Column(name = "ACTIONS", columnDefinition = "jsonb")@org.hibernate.annotations.Type(type = PERSISTENCE_JSON_ARRAY_TYPE)- private JsonArray actions = Json.createArray();+ private ArrayValue actions = Values.createArray();@NotNull@Column(name = "APP_URL", nullable = false)@@ -72,27 +69,16 @@ public class AlertNotification {this.message = message;}- public void setActions(JsonArray actions) {+ public void setActions(ArrayValue actions) {this.actions = actions;}- public JsonArray getActions() {-- return actions;- }-- public List<AlertAction> getActionsAsList() {- List actions = new ArrayList<>(this.actions.length());- for (int i = 0; i < actions.size(); i++) {- actions.add(this.actions.get(i).toNative());-- }-+ public ArrayValue getActions() {return actions;}public void addAction(AlertAction action) {- this.actions.set(this.actions.length(), action.getValue());+ this.actions.set(this.actions.length(), action.getObjectValue());}public String getAppUrl() {diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.javaindex 3f6082b80..aad23ade9 100644--- a/model/src/main/java/org/openremote/model/rules/Assets.java+++ b/model/src/main/java/org/openremote/model/rules/Assets.java@@ -19,7 +19,7 @@*/package org.openremote.model.rules;-import org.openremote.model.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.asset.AssetQuery;import java.util.List;diff --git a/model/src/main/java/org/openremote/model/units/AttributeUnits.java b/model/src/main/java/org/openremote/model/units/AttributeUnits.javadeleted file mode 100644index 2013e874f..000000000--- a/model/src/main/java/org/openremote/model/units/AttributeUnits.java+++ /dev/null@@ -1,133 +0,0 @@-/*- * 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.units;--import org.openremote.model.value.Value;-import org.openremote.model.value.ValueType;--import java.util.function.Function;--/**- * The well-known attribute units (attribute sub-type) we can depend on- * in our platform. Together with the {@link org.openremote.model.AttributeType}- * of an {@link org.openremote.model.Attribute}, you can use units in attribute- * metadata to discriminate rendering, testing, and editing of attribute values.- */-// TODO: Remove Attribute Units-public enum AttributeUnits {-- /**- * Unix epoch timestamp- */- // TODO: Seconds or milliseconds- TIMESTAMP,-- /**- * ISO 8601, e.g. <code>2012-04-23T18:25:43.511Z</code>- */- DATETIME,-- /**- * RGB integers- */- COLOR_RGB,-- /**- * ARGB integers- */- COLOR_ARGB,-- /**- * HTML Hex Value, e.g. <code>#ffffff</code>- */- COLOR_HEX,-- TEMPERATURE_CELCIUS,-- TEMPERATURE_KELVIN,-- TEMPERATURE_FAHRENHEIT,-- DISTANCE_M,-- DISTANCE_CM,-- DISTANCE_MM,-- DISTANCE_IN,-- DISTANCE_FT,-- DISTANCE_YARD,-- CO2_PPM,-- CO2_PERCENTAGE,-- HUMIDITY_PERCENTAGE,-- /**- * Grams per cubic metre- */- HUMIDITY_GPCM,-- POWER_WATTS,-- POWER_KILOWATT,-- POWER_MEGAWATT,-- CHARGE_PERCENTAGE,-- CHARGE_KWH,-- PERCENTAGE,-- ENERGY_KWH,-- ENERGY_JOULE,-- ENERGY_MEGAJOULE,-- /**- * Litre per minute- */- FLOW_LPM,-- /**- * Cubic metres per second- */- FLOW_CMPS,-- /**- * Standard cubic centimetres per minute- */- FLOW_SCCM,-- /**- * Cubic feet per second- */- FLOW_CFPS,-- /**- * Gallons per minute- */- FLOW_GPM-}diff --git a/model/src/main/java/org/openremote/model/util/JsonUtil.java b/model/src/main/java/org/openremote/model/util/JsonUtil.javadeleted file mode 100644index b70e8466c..000000000--- a/model/src/main/java/org/openremote/model/util/JsonUtil.java+++ /dev/null@@ -1,434 +0,0 @@-/*- * 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.google.gwt.core.shared.GWT;-import elemental.json.*;--import java.util.HashMap;-import java.util.List;-import java.util.Map;-import java.util.Optional;-import java.util.stream.Collectors;--/**- * Elemental issues:- * <p>- * <ul>- * <li>Equality checking for {@link JsonObject} does not use {@link JsonValue#jsEquals(JsonValue)}- * {@link JsonValue#jsEquals(JsonValue)} isn't null safe- * <li>Coerces types into other types implicitly- * <li>Returns primitives rather than objects, relates to coercion (e.g. {@link JsonValue#asBoolean()})- * <li>Strange boxing/unboxing behaviour which means a primitive isn't always recognised as the correct type- * when calling {@link JsonValue#getType()}- * <li>For primitives {@link JsonObject#get(String)} has different behaviour to for example- * {@link JsonObject#getBoolean(String)}- * <li>JsonValue of primitive with default value is null (on client side) <a href="https://github.com/gwtproject/gwt/issues/9484">- * https://github.com/gwtproject/gwt/issues/9484</a>- * <li>Primitives on client side will cause CCS exception if casting to JsonValue (this affects {@link Optional#get()})- * <p>- *- * When working with JsonValue it is advised to use the {@link #replaceJsonNull(JsonValue)} methods which eliminate- * JsonNull and instead use plain old null, method returns an optional. If JsonNull didn't exist then obviously- * could just use {@link Optional#ofNullable(Object)} directly.- *- */-public class JsonUtil {-- // JRE implementation uses same reference for all JSON Null objects- // so reference equality checking is fine and works on client also- protected static JsonNull JSON_NULL = Json.createNull();-- /**- * 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}.- */- 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;- }-- public static boolean isOfType(JsonValue jsonValue, JsonType type) {- return type != null && getJsonValueType(jsonValue) == type;- }-- public static boolean isOfTypeString(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.STRING);- }-- public static boolean isOfTypeNumber(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.NUMBER);- }-- public static boolean isOfTypeBoolean(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.BOOLEAN);- }-- public static boolean isOfTypeJsonArray(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.ARRAY);- }-- public static boolean isOfTypeJsonObject(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.OBJECT);- }-- public static boolean isOfTypeDecimal(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.NUMBER) && !isInteger(jsonValue.asNumber());- }-- public static boolean isOfTypeInteger(JsonValue jsonValue) {- return isOfType(jsonValue, JsonType.NUMBER) && isInteger(jsonValue.asNumber());- }-- public static boolean isTrue(JsonValue jsonValue) {- return asBoolean(jsonValue)- .orElse(false);- }-- public static boolean isFalse(JsonValue jsonValue) {- return !isTrue(jsonValue);- }-- public static boolean isInteger(JsonValue jsonValue) {- return asDecimal(jsonValue)- .map(JsonUtil::isInteger)- .orElse(false);- }-- // TODO: Should this only return a value for JsonType.STRING values or should it work for any data type?- public static Optional<String> asString(JsonValue value) {- JsonValue jsonValue = replaceJsonNull(value);- return Optional.ofNullable(jsonValue != null ? jsonValue.asString() : null);- }-- public static Optional<String> asString(Optional<JsonValue> value) {- return asString(unwrapJsonValue(value));- }-- public static Optional<Double> asDecimal(JsonValue value) {- return Optional.ofNullable(isOfTypeNumber(value) ? ((JsonNumber)value).getNumber() : null);- }-- public static Optional<Double> asDecimal(Optional<JsonValue> value) {- return asDecimal(unwrapJsonValue(value));- }-- public static Optional<Boolean> asBoolean(JsonValue value) {- return Optional.ofNullable(isOfTypeBoolean(value) ? ((JsonBoolean)value).getBoolean() : null);- }-- public static Optional<Boolean> asBoolean(Optional<JsonValue> value) {- return asBoolean(unwrapJsonValue(value));- }-- public static Optional<JsonArray> asJsonArray(JsonValue value) {- return Optional.ofNullable(isOfTypeJsonArray(value) ? (JsonArray)value : null);- }-- public static Optional<JsonArray> asJsonArray(Optional<JsonValue> value) {- return asJsonArray(unwrapJsonValue(value));- }-- public static Optional<JsonObject> asJsonObject(JsonValue value) {- return Optional.ofNullable(isOfTypeJsonObject(value) ? (JsonObject)value : null);- }-- public static Optional<JsonObject> asJsonObject(Optional<JsonValue> value) {- return asJsonObject(unwrapJsonValue(value));- }-- public static Optional<Integer> asInteger(JsonValue value) {- return asDecimal(value)- .map(dbl -> isInteger(dbl) ? (int)Math.floor(dbl) : null);- }-- public static Optional<Integer> asInteger(Optional<JsonValue> value) {- return asInteger(unwrapJsonValue(value));- }-- public static String asJson(JsonValue value) {- return value == null ? "" : value.toJson();- }-- public static String asJson(Optional<JsonValue> value) {- return asJson(unwrapJsonValue(value));- }-- protected static boolean isInteger(double value) {- return (value == Math.floor(value)) && !Double.isInfinite(value);- }-- // --------------------------------------------- // BELOW ARE JUST TO DEAL WITH CRAPPY ELEMENTAL- // ---------------------------------------------- public static JsonValue asJsonValue(Boolean bool) {- return bool == null ? null : Json.create(bool);- }-- public static JsonValue asJsonValue(String str) {- return str == null ? null : Json.create(str);- }-- public static JsonValue asJsonValue(Double dbl) {- return dbl == null ? null : Json.create(dbl);- }-- public static JsonValue asJsonValue(Integer integer) {- return integer == null ? null : Json.create(integer);- }-- /**- * Prevent JsonNull instances from being used; when the type is removed- * from elemental then this will be un-necessary.- * <p>- * All instances of JsonNull have been removed from the codebase- * but this is here in case others get introduced.- */- // TODO: Fix elemental and remove this- public static JsonValue replaceJsonNull(JsonValue jsonValue) {- return jsonValue == JSON_NULL ? null : jsonValue;- }-- /**- * Fixes issues relating to un-boxed primitives on client side- * should be called by client side code rather than using the- * JsonValue directly.- */- // TODO: Fix elemental and remove this- public static JsonValue sanitizeJsonValue(JsonValue jsonValue) {- return fixBoxingUnBoxing(jsonValue);- }-- /**- * Fixes issues relating to un-boxed primitives on client side- * should be called by client side code rather than using the- * JsonValue directly.- */- // TODO: Fix elemental and remove this- public static JsonValue sanitizeJsonValue(Optional<JsonValue> jsonValue) {- return unwrapJsonValue(jsonValue);- }-- /**- * This ensures that primitives are correctly boxed into JsonValue type- */- // TODO: Fix elemental and remove this- protected static JsonValue fixBoxingUnBoxing(Object obj) {- if (obj == JSON_NULL) {- return null;- }-- JsonValue jsonValue = null;-- if (obj instanceof JsonValue) {- // Server side will only ever reach here- jsonValue = (JsonValue)obj;- } else if(obj instanceof String) {- // Elemental doesn't box strings and primitive- // strings cannot be cast to JsonValue so box- jsonValue = boxString((String)obj);- } else if (obj instanceof Double) {- jsonValue = Json.create((Double)obj);- } else if (obj instanceof Boolean) {- jsonValue = Json.create((Boolean)obj);- }-- return jsonValue;- }-- /**- * JsJsonValue implementation is not tolerant of boxed primitives for- * getType call (it assumes everything is un-boxed).- * <p>- * This replacement method is tolerant of boxed primitives.- */- // TODO: Fix elemental and remove this- public static JsonType getJsonValueType(JsonValue jsonValue) {- jsonValue = sanitizeJsonValue(jsonValue);-- if (jsonValue == null) {- return JsonType.NULL;- }-- if (!GWT.isScript()) {- return jsonValue.getType();- } else {- String jsType = getJsNativeType(jsonValue);- switch (jsType) {- case "number":- return JsonType.NUMBER;- case "boolean":- return JsonType.BOOLEAN;- case "string":- return JsonType.STRING;- default:- return jsonValue.getType();- }- }- }-- // TODO: Fix elemental and remove this- @SuppressWarnings({"ConstantConditions", "OptionalIsPresent"})- protected static JsonValue unwrapJsonValue(Optional<JsonValue> jsonValueOptional) {- return jsonValueOptional.isPresent() ? fixBoxingUnBoxing(jsonValueOptional.get()) : null;- }-- // TODO: Fix elemental and remove this- @SuppressWarnings("EqualityComparisonWithCoercionJS")- private native static String getJsNativeType(Object o) /*-{- var type = typeof o;- if (type == 'object') {- return typeof (o.valueOf());- } else {- return type;- }- }-*/;-- // TODO: Fix elemental and remove this- private native static JsonString boxString(String str) /*-{- return Object(str);- }-*/;-}diff --git a/model/src/main/java/org/openremote/model/Pair.java b/model/src/main/java/org/openremote/model/util/Pair.javasimilarity index 97%rename from model/src/main/java/org/openremote/model/Pair.javarename to model/src/main/java/org/openremote/model/util/Pair.javaindex 523eb3840..34e230c66 100644--- a/model/src/main/java/org/openremote/model/Pair.java+++ b/model/src/main/java/org/openremote/model/util/Pair.java@@ -17,7 +17,7 @@* 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;+package org.openremote.model.util;import java.io.Serializable;import java.util.Objects;diff --git a/model/src/main/java/org/openremote/model/Triplet.java b/model/src/main/java/org/openremote/model/util/Triplet.javasimilarity index 98%rename from model/src/main/java/org/openremote/model/Triplet.javarename to model/src/main/java/org/openremote/model/util/Triplet.javaindex b6c97c0bb..24cc5c55c 100644--- a/model/src/main/java/org/openremote/model/Triplet.java+++ b/model/src/main/java/org/openremote/model/util/Triplet.java@@ -17,7 +17,7 @@* 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;+package org.openremote.model.util;import java.io.Serializable;import java.util.Objects;diff --git a/model/src/main/java/org/openremote/model/value/ArrayValue.java b/model/src/main/java/org/openremote/model/value/ArrayValue.javaindex 5caf76fb7..82764ee1c 100644--- a/model/src/main/java/org/openremote/model/value/ArrayValue.java+++ b/model/src/main/java/org/openremote/model/value/ArrayValue.java@@ -16,7 +16,6 @@package org.openremote.model.value;import java.util.Optional;-import java.util.stream.Stream;public interface ArrayValue extends Value {@@ -34,13 +33,21 @@ public interface ArrayValue extends Value {int length();- void remove(int index);+ ArrayValue remove(int index);- void set(int index, Value value);+ ArrayValue set(int index, Value value);- void set(int index, String string);+ ArrayValue set(int index, String string);- void set(int index, double number);+ ArrayValue set(int index, double number);- void set(int index, boolean bool);+ ArrayValue set(int index, boolean bool);++ ArrayValue add(Value value);++ ArrayValue add(int index, Value value);++ ArrayValue addAll(Value... values);++ ArrayValue deepCopy();}diff --git a/model/src/main/java/org/openremote/model/value/ObjectValue.java b/model/src/main/java/org/openremote/model/value/ObjectValue.javaindex 04e6484ab..69abac59b 100644--- a/model/src/main/java/org/openremote/model/value/ObjectValue.java+++ b/model/src/main/java/org/openremote/model/value/ObjectValue.java@@ -15,7 +15,10 @@*/package org.openremote.model.value;+import org.openremote.model.util.Pair;+import java.util.Optional;+import java.util.stream.Stream;/*** Object values can not have duplicate keys. For equality operations, objects@@ -26,27 +29,48 @@ public interface ObjectValue extends Value {Optional<Value> get(String key);+ /**+ * A <code>String</code> or if the value type is not {@link ValueType#STRING}, an empty {@link Optional}.+ */Optional<String> getString(String key);+ /**+ * A <code>String</code> or if the value type is not {@link ValueType#BOOLEAN}, an empty {@link Optional}.+ */Optional<Boolean> getBoolean(String key);+ /**+ * A <code>Double</code> or if the value type is not {@link ValueType#NUMBER}, an empty {@link Optional}.+ */Optional<Double> getNumber(String key);+ /**+ * An <code>ArrayValue</code> or if the value type is not {@link ValueType#ARRAY}, an empty {@link Optional}.+ */Optional<ArrayValue> getArray(String key);+ /**+ * An <code>ObjectValue</code> or if the value type is not {@link ValueType#OBJECT}, an empty {@link Optional}.+ */Optional<ObjectValue> getObject(String key);String[] keys();- void put(String key, Value value);+ Stream<Pair<String, Value>> stream();- void put(String key, String value);+ boolean hasKey(String key);- void put(String key, double value);+ ObjectValue put(String key, Value value);- void put(String key, boolean bool);+ ObjectValue put(String key, String value);- boolean hasKey(String key);+ ObjectValue put(String key, double value);++ ObjectValue put(String key, boolean bool);++ ObjectValue remove(String key);++ ObjectValue deepCopy();- void remove(String key);+ boolean equalsIgnoreKeys(ObjectValue that, String... ignoreKeys);}diff --git a/model/src/main/java/org/openremote/model/value/ValueType.java b/model/src/main/java/org/openremote/model/value/ValueType.javaindex 5b6e0767a..c4f31a5da 100644--- a/model/src/main/java/org/openremote/model/value/ValueType.java+++ b/model/src/main/java/org/openremote/model/value/ValueType.java@@ -19,5 +19,20 @@ package org.openremote.model.value;* Represents the type of the underlying value, the same as in JSON.*/public enum ValueType {- OBJECT, ARRAY, STRING, NUMBER, BOOLEAN;++ OBJECT(ObjectValue.class),+ ARRAY(ArrayValue.class),+ STRING(StringValue.class),+ NUMBER(NumberValue.class),+ BOOLEAN(BooleanValue.class);++ protected final Class<? extends Value> modelType;++ ValueType(Class<? extends Value> type) {+ this.modelType = type;+ }++ public Class getModelType() {+ return modelType;+ }}diff --git a/model/src/main/java/org/openremote/model/value/Values.java b/model/src/main/java/org/openremote/model/value/Values.javaindex c3948e253..3e93d665c 100644--- a/model/src/main/java/org/openremote/model/value/Values.java+++ b/model/src/main/java/org/openremote/model/value/Values.java@@ -51,4 +51,32 @@ public class Values {public static <T extends Value> Optional<T> parse(String jsonString) throws ValueException {return instance().parse(jsonString);}++ @SuppressWarnings("unchecked")+ public static <T extends Value> Optional<T> cast(Class<T> type, Value value) {+ return value != null && value.getType().getModelType() == type+ ? Optional.of((T) value)+ : Optional.empty();+ }++ public static Optional<String> getString(Value value) {+ return cast(StringValue.class, value).map(StringValue::getString);+ }++ public static Optional<Double> getNumber(Value value) {+ return cast(NumberValue.class, value).map(NumberValue::getNumber);+ }++ public static Optional<Boolean> getBoolean(Value value) {+ return cast(BooleanValue.class, value).map(BooleanValue::getBoolean);+ }++ public static Optional<ObjectValue> getObject(Value value) {+ return cast(ObjectValue.class, value);+ }++ public static Optional<ArrayValue> getArray(Value value) {+ return cast(ArrayValue.class, value);+ }+}diff --git a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.javaindex 8a1badd9d..ded8b6679 100644--- a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java@@ -18,7 +18,6 @@ package org.openremote.model.value.impl;import org.openremote.model.value.*;import java.util.ArrayList;-import java.util.List;import java.util.Optional;public class ArrayValueImpl extends ValueImpl implements ArrayValue {@@ -39,44 +38,35 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {public Optional<String> getString(int index) {return get(index).filter(value -> value.getType() == ValueType.STRING && value instanceof StringValue)- .map(value -> ((StringValue)value).getString());+ .map(value -> ((StringValue) value).getString());}@Overridepublic Optional<Boolean> getBoolean(int index) {return get(index).filter(value -> value.getType() == ValueType.BOOLEAN && value instanceof BooleanValue)- .map(value -> ((BooleanValue)value).getBoolean());+ .map(value -> ((BooleanValue) value).getBoolean());}@Overridepublic Optional<Double> getNumber(int index) {return get(index).filter(value -> value.getType() == ValueType.NUMBER && value instanceof NumberValue)- .map(value -> ((NumberValue)value).getNumber());+ .map(value -> ((NumberValue) value).getNumber());}@Overridepublic Optional<ArrayValue> getArray(int index) {return get(index).filter(value -> value.getType() == ValueType.ARRAY && value instanceof ArrayValue)- .map(value -> ((ArrayValue)value));+ .map(value -> ((ArrayValue) value));}@Overridepublic Optional<ObjectValue> getObject(int index) {return get(index).filter(value -> value.getType() == ValueType.OBJECT && value instanceof ObjectValue)- .map(value -> ((ObjectValue)value));- }-- @Override- public List<Object> asObject() {- List<Object> objs = new ArrayList<>();- for (Value val : values) {- objs.add(((ValueImpl) val).asObject());- }- return objs;+ .map(value -> ((ObjectValue) value));}@Override@@ -90,34 +80,66 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {}@Override- public void remove(int index) {+ public ArrayValue remove(int index) {values.remove(index);+ return this;}@Override- public void set(int index, Value value) {+ public ArrayValue set(int index, Value value) {if (value == null && index >= 0 && index < values.size()) {values.remove(index);} else if (index == values.size()) {- values.add(index, value);+ values.add(value);} else {values.set(index, value);}+ return this;}@Override- public void set(int index, String string) {+ public ArrayValue set(int index, String string) {set(index, factory.create(string));+ return this;}@Override- public void set(int index, double number) {+ public ArrayValue set(int index, double number) {set(index, factory.create(number));+ return this;}@Override- public void set(int index, boolean bool) {+ public ArrayValue set(int index, boolean bool) {set(index, factory.create(bool));+ return this;+ }++ @Override+ public ArrayValue add(Value value) {+ values.add(value);+ return this;+ }++ @Override+ public ArrayValue add(int index, Value value) {+ values.add(index, value);+ return this;+ }++ @Override+ public ArrayValue addAll(Value... values) {+ if (values != null) {+ for (Value value : values) {+ set(length(), value);+ }+ }+ return this;+ }++ @Override+ public ArrayValue deepCopy() {+ return Values.<ArrayValue>parse(toJson()).orElseThrow(() -> new IllegalStateException("Error copying array value"));}@Override@@ -170,4 +192,8 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {return result;}+ @Override+ public String toString() {+ return toJson();+ }}diff --git a/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.javaindex 53f89dd96..801b5b5bf 100644--- a/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/BooleanValueImpl.java@@ -31,11 +31,6 @@ public class BooleanValueImpl extends ValueImpl implements BooleanValue {return bool;}- @Override- public Boolean asObject() {- return getBoolean();- }-@Overridepublic ValueType getType() {return ValueType.BOOLEAN;@@ -67,4 +62,9 @@ public class BooleanValueImpl extends ValueImpl implements BooleanValue {result = result * 7 + (getBoolean() ? 1 : 0);return result;}++ @Override+ public String toString() {+ return toJson();+ }}diff --git a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.javaindex d57afb510..7f0de658f 100644--- a/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/NumberValueImpl.java@@ -31,11 +31,6 @@ public class NumberValueImpl extends ValueImpl implements NumberValue {return number;}- @Override- public Double asObject() {- return getNumber();- }-@Overridepublic ValueType getType() {return ValueType.NUMBER;@@ -74,4 +69,9 @@ public class NumberValueImpl extends ValueImpl implements NumberValue {result = result * 11 + Double.hashCode(getNumber());return result;}++ @Override+ public String toString() {+ return toJson();+ }}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 d4943961b..abf700069 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@@ -15,9 +15,11 @@*/package org.openremote.model.value.impl;+import org.openremote.model.util.Pair;import org.openremote.model.value.*;import java.util.*;+import java.util.stream.Stream;public class ObjectValueImpl extends ValueImpl implements ObjectValue {@@ -50,94 +52,90 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {@Overridepublic Optional<String> getString(String key) {- return get(key)- .filter(value -> value.getType() == ValueType.STRING && value instanceof StringValue)- .map(value -> ((StringValue)value).getString());+ return get(key).flatMap(Values::getString);}@Overridepublic Optional<Boolean> getBoolean(String key) {- return get(key)- .filter(value -> value.getType() == ValueType.BOOLEAN && value instanceof BooleanValue)- .map(value -> ((BooleanValue)value).getBoolean());+ return get(key).flatMap(Values::getBoolean);}@Overridepublic Optional<Double> getNumber(String key) {- return get(key)- .filter(value -> value.getType() == ValueType.NUMBER && value instanceof NumberValue)- .map(value -> ((NumberValue)value).getNumber());+ return get(key).flatMap(Values::getNumber);}@Overridepublic Optional<ArrayValue> getArray(String key) {- return get(key)- .filter(value -> value.getType() == ValueType.ARRAY && value instanceof ArrayValue)- .map(value -> ((ArrayValue)value));+ return get(key).flatMap(Values::getArray);}@Overridepublic Optional<ObjectValue> getObject(String key) {- return get(key)- .filter(value -> value.getType() == ValueType.OBJECT && value instanceof ObjectValue)- .map(value -> ((ObjectValue)value));+ return get(key).flatMap(Values::getObject);}@Override- public Map<String, Object> asObject() {- Map<String, Object> obj = new HashMap<>();- for (Map.Entry<String, Value> e : map.entrySet()) {- obj.put(e.getKey(), ((ValueImpl) e.getValue()).asObject());- }- return obj;+ public ValueType getType() {+ return ValueType.OBJECT;}@Override- public ValueType getType() {- return ValueType.OBJECT;+ public String[] keys() {+ return map.keySet().toArray(new String[map.size()]);}@Override- public boolean hasKey(String key) {- return map.containsKey(key);+ public Stream<Pair<String, Value>> stream() {+ return Arrays.stream(keys()).map(key -> new Pair<>(key, get(key).get()));}@Override- public String[] keys() {- return map.keySet().toArray(new String[map.size()]);+ public boolean hasKey(String key) {+ return map.containsKey(key);}@Override- public void put(String key, Value value) {+ public ObjectValue put(String key, Value value) {if (value == null) {map.remove(key);} else {map.put(key, value);}+ return this;}@Override- public void put(String key, String value) {+ public ObjectValue put(String key, String value) {if (value == null) {remove(key);} else {put(key, factory.create(value));}+ return this;}@Override- public void put(String key, double value) {+ public ObjectValue put(String key, double value) {put(key, factory.create(value));+ return this;}@Override- public void put(String key, boolean bool) {+ public ObjectValue put(String key, boolean bool) {put(key, factory.create(bool));+ return this;}@Override- public void remove(String key) {+ public ObjectValue remove(String key) {map.remove(key);+ return this;+ }++ @Override+ public ObjectValue deepCopy() {+ return Values.<ObjectValue>parse(toJson()).orElseThrow(() -> new IllegalStateException("Error copying object value"));}@Override@@ -173,13 +171,31 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {if (!(o instanceof ObjectValueImpl))return false;ObjectValueImpl that = (ObjectValueImpl) o;+ return equalsIgnoreKeys(that);+ }++ @Override+ public int hashCode() {+ int result = 31;+ result = result * 3;+ result = result * map.hashCode();+ return result;+ }- if (!this.map.keySet().equals(that.map.keySet()))+ @Override+ public boolean equalsIgnoreKeys(ObjectValue that, String... ignoreKeys) {+ if (!(that instanceof ObjectValueImpl))+ return false;+ ObjectValueImpl objectValueImpl = (ObjectValueImpl)that;++ if (!this.map.keySet().equals(objectValueImpl.map.keySet()))return false;for (Map.Entry<String, Value> entry : this.map.entrySet()) {+ if (Arrays.asList(ignoreKeys).contains(entry.getKey()))+ continue;Value mapAValue = entry.getValue();- Value mapBValue = that.map.get(entry.getKey());+ Value mapBValue = objectValueImpl.map.get(entry.getKey());if (!mapAValue.equals(mapBValue)) {return false;}@@ -188,11 +204,7 @@ public class ObjectValueImpl extends ValueImpl implements ObjectValue {}@Override- public int hashCode() {- int result = 31;- result = result * 3;- result = result * asObject().hashCode();- return result;+ public String toString() {+ return toJson();}-}diff --git a/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.javaindex 0dc4f76fb..6a3fbd132 100644--- a/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/StringValueImpl.java@@ -27,11 +27,6 @@ public class StringValueImpl extends ValueImpl implements StringValue {this.string = string;}- @Override- public String asObject() {- return getString();- }-@Overridepublic String getString() {return string;@@ -67,4 +62,9 @@ public class StringValueImpl extends ValueImpl implements StringValue {result = result * 13 + getString().hashCode();return result;}++ @Override+ public String toString() {+ return getString();+ }}diff --git a/model/src/main/java/org/openremote/model/value/impl/ValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ValueImpl.javaindex 841385c40..e5cf8fe8c 100644--- a/model/src/main/java/org/openremote/model/value/impl/ValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/ValueImpl.java@@ -31,14 +31,6 @@ public abstract class ValueImpl implements Value {throw new ValueException("Not a GWT/JavaScript runtime environment");}- @Override- public String toString() {- Object o = asObject();- return o != null ? o.toString() : "null";- }-- public abstract Object asObject();-public abstract void traverse(ValueVisitor visitor, ValueContext ctx) throws ValueException;}