Skip to content

armgit / core

Public Imported from GitHub
0

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

Asset validation and model cleanup (#1117)

Rich Turner3b82f8fd0385
diff --git a/.github/workflows/ci_cd.yml b/.github/workflows/ci_cd.yml
index 311123286..65029bdc3 100644
--- a/.github/workflows/ci_cd.yml
+++ b/.github/workflows/ci_cd.yml
@@ -657,7 +657,7 @@ jobs:
fi
# Make temp dir and set mask to 777 as docker seems to run as root
- mkdir tmp
+ mkdir -p tmp
chmod 777 tmp
# Define cleanup command
diff --git a/README.md b/README.md
index e2cd7b450..5a412e343 100644
--- a/README.md
+++ b/README.md
@@ -61,7 +61,8 @@ Try creating assets, agents, rules, users, realms, etc. using the Manager UI, pl
## Where's the data stored?
Persistent data is stored in a PostgreSQL DB which is stored in the `openremote_postgresql-data` docker volume which is durably stored independently of the running containers (see all with `docker volume ls`).
-If you want to create a backup of your installation, just make a copy of this volume.
+Note that historical attribute data is purged daily based on value of `OR_DATA_POINTS_MAX_AGE_DAYS`; this value can also be overridden for individual attributes by using the `dataPointsMaxAgeDays` configuration item.
+See the [Developer Guide](https://github.com/openremote/openremote/wiki/Developer-Guide%3A-Useful-commands-and-queries#backuprestore-openremote-db) for details on making backups of the database.
## Contributing to OpenRemote
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AgentModelProvider.java b/agent/src/main/java/org/openremote/agent/protocol/AgentModelProvider.java
index ca5d6ca19..77b7bdc18 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/AgentModelProvider.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/AgentModelProvider.java
@@ -20,14 +20,6 @@
package org.openremote.agent.protocol;
import org.openremote.model.AssetModelProvider;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.MetaItemDescriptor;
-import org.openremote.model.value.ValueDescriptor;
-
-import java.util.List;
-import java.util.Map;
/**
* Enables scanning of descriptors in the agent module
@@ -37,28 +29,4 @@ public class AgentModelProvider implements AssetModelProvider {
public boolean useAutoScan() {
return true;
}
-
- @Override
- public AssetDescriptor<?>[] getAssetDescriptors() {
- return new AssetDescriptor<?>[0];
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<ValueDescriptor<?>>> getValueDescriptors() {
- return null;
- }
-
- @Override
- public void onAssetModelFinished() {
- }
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetProtocol.java
index 3de490643..c43ea67c9 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetProtocol.java
@@ -1,7 +1,6 @@
package org.openremote.agent.protocol.artnet;
import io.netty.channel.ChannelHandler;
-import org.openremote.agent.protocol.io.AbstractIOClientProtocol;
import org.openremote.agent.protocol.io.AbstractNettyIOClient;
import org.openremote.agent.protocol.io.AbstractNettyIOClientProtocol;
import org.openremote.agent.protocol.udp.UDPIOClient;
@@ -90,7 +89,7 @@ public class ArtnetProtocol extends AbstractNettyIOClientProtocol<ArtnetProtocol
// if(lightId != -1 && groupId != -1 && universe != -1 && amountOfLeds != -1 && requiredKeysField != null)
// {
// String[] requiredKeys = requiredKeysField.split(",");
-// ArtnetLightState state = new ArtnetLightState(lightId, new LinkedHashMap<String, Integer>(), 100, true);
+// ArtnetLightState state = new ArtnetLightState(lightId, new HashMap<String, Integer>(), 100, true);
// for(String key : requiredKeys)
// state.getReceivedValues().put(key, 0);
// ArtnetLight lightToCreate = new ArtnetLight(lightId, groupId, universe, amountOfLeds, requiredKeys, state, null);
@@ -146,7 +145,7 @@ public class ArtnetProtocol extends AbstractNettyIOClientProtocol<ArtnetProtocol
// ArtnetLightState oldLightState = updatedLight.getLightState();
// //UPDATE LIGHT VALUES (R,G,B FOR EXAMPLE)
// if(event.getAttributeRef().getAttributeName().equalsIgnoreCase("Values")) {
-// Map<String, Integer> valuesToUpdate = new LinkedHashMap<>();
+// Map<String, Integer> valuesToUpdate = new HashMap<>();
// for(String requiredKey : updatedLight.getRequiredValues()) {
// try {
// JsonNode node = ValueUtil.JSON.readTree(processedValue.toJson());
@@ -222,7 +221,7 @@ public class ArtnetProtocol extends AbstractNettyIOClientProtocol<ArtnetProtocol
//
// private void syncLightsToMemory(List<ArtnetLight> lights) {
// for(ArtnetLight light : new ArrayList<ArtnetLight>(artnetLightMemory)) {
-// ArtnetLightState state = new ArtnetLightState(light.getLightId(), new LinkedHashMap<String, Integer>(), 100, true);
+// ArtnetLightState state = new ArtnetLightState(light.getLightId(), new HashMap<String, Integer>(), 100, true);
// for(String key : light.getRequiredValues())
// state.getReceivedValues().put(key, 0);
// light.setLightState(state);
@@ -244,7 +243,7 @@ public class ArtnetProtocol extends AbstractNettyIOClientProtocol<ArtnetProtocol
// }
// }
// for(ArtnetLight light : lights) {
-// ArtnetLightState state = new ArtnetLightState(light.getLightId(), new LinkedHashMap<String, Integer>(), 100, true);
+// ArtnetLightState state = new ArtnetLightState(light.getLightId(), new HashMap<String, Integer>(), 100, true);
// for(String key : light.getRequiredValues())
// state.getReceivedValues().put(key, 0);
// light.setLightState(state);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java
index 6abb304e4..24cc7ccf6 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/BluetoothMeshProtocol.java
@@ -19,37 +19,24 @@
*/
package org.openremote.agent.protocol.bluetooth.mesh;
-import com.welie.blessed.BluetoothCentralManager;
-import com.welie.blessed.BluetoothCentralManagerCallback;
-import com.welie.blessed.BluetoothCommandStatus;
-import com.welie.blessed.BluetoothPeripheral;
-import com.welie.blessed.ScanResult;
+import com.welie.blessed.*;
import org.openremote.agent.protocol.AbstractProtocol;
import org.openremote.agent.protocol.bluetooth.mesh.models.SigModelParser;
import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.model.Container;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetTreeNode;
import org.openremote.model.asset.agent.ConnectionStatus;
-import org.openremote.model.asset.impl.ThingAsset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
-import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.protocol.ProtocolAssetDiscovery;
import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.value.MetaItemType;
-import org.openremote.model.value.ValueFormat;
-import org.openremote.model.value.ValueType;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
@@ -57,7 +44,6 @@ import java.util.function.Consumer;
import java.util.logging.Logger;
import static org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty;
-import static org.openremote.model.value.MetaItemType.AGENT_LINK;
public class BluetoothMeshProtocol extends AbstractProtocol<BluetoothMeshAgent, BluetoothMeshAgentLink> {
@@ -299,7 +285,7 @@ public class BluetoothMeshProtocol extends AbstractProtocol<BluetoothMeshAgent,
"Linking Bluetooth Mesh attribute: [address: '" + String.format("0x%04X", address) + "', model: '" +
modelName + "', appKeyIndex: '" + appKeyIndex + "'] - " + attributeRef
);
- Class<?> clazz = (attribute == null ? null : attribute.getType().getType());
+ Class<?> clazz = attribute.getTypeClass();
Consumer<Object> sensorValueConsumer = value -> updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, clazz)));
sensorValueConsumerMap.put(attributeRef, sensorValueConsumer);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java
index cfb1c6b77..8353635bc 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ConfigCompositionDataStatus.java
@@ -27,7 +27,7 @@ import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshParserUtils;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-import java.util.LinkedHashMap;
+import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Logger;
@@ -51,7 +51,7 @@ public class ConfigCompositionDataStatus extends ConfigStatusMessage{
private boolean proxyFeatureSupported;
private boolean friendFeatureSupported;
private boolean lowPowerFeatureSupported;
- private Map<Integer, Element> mElements = new LinkedHashMap<>();
+ private Map<Integer, Element> mElements = new HashMap<>();
/**
* Constructs the ConfigCompositionDataStatus mMessage.
@@ -130,7 +130,7 @@ public class ConfigCompositionDataStatus extends ConfigStatusMessage{
int counter = 0;
int elementAddress = 0;
while (tempOffset < accessPayload.length) {
- final Map<Integer, MeshModel> models = new LinkedHashMap<>();
+ final Map<Integer, MeshModel> models = new HashMap<>();
final int locationDescriptor = accessPayload[tempOffset + 1] << 8 | accessPayload[tempOffset];
LOG.info("Location identifier: " + String.format(Locale.US, "%04X", locationDescriptor));
diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java
index ee46c6060..d31cb8fe7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/MeshModel.java
@@ -21,12 +21,7 @@ package org.openremote.agent.protocol.bluetooth.mesh.transport;
import org.openremote.agent.protocol.bluetooth.mesh.utils.MeshAddress;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
+import java.util.*;
/**
* Base mesh model class
@@ -41,7 +36,7 @@ public abstract class MeshModel {
final List<Integer> mBoundAppKeyIndexes = new ArrayList<>();
- final Map<Integer, String> mBoundAppKeys = new LinkedHashMap<>();
+ final Map<Integer, String> mBoundAppKeys = new HashMap<>();
final List<Integer> subscriptionAddresses = new ArrayList<>();
diff --git a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java
index 63fb758ed..1f5f58601 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/bluetooth/mesh/transport/ProvisionedBaseMeshNode.java
@@ -67,7 +67,7 @@ abstract class ProvisionedBaseMeshNode {
List<NodeKey> mAddedNetKeys = new ArrayList<>();
List<NodeKey> mAddedAppKeys = new ArrayList<>();
byte[] mFlags;
- Map<Integer, Element> mElements = new LinkedHashMap<>();
+ Map<Integer, Element> mElements = new HashMap<>();
boolean excluded = false;
int nodeIdentityState;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgent.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgent.java
index 07f615457..e480fa74c 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgent.java
@@ -35,7 +35,7 @@ public class KNXAgent extends Agent<KNXAgent, KNXProtocol, KNXAgentLink> {
@Pattern(regexp = "^\\d\\.\\d\\.\\d$")
public static final ValueDescriptor<String> SOURCE_ADDRESS_VALUE = new ValueDescriptor<>("kNXMessageSourceAddress", String.class);
- public static final AttributeDescriptor<String> GATEWAY = HOST.withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
public static final AttributeDescriptor<Boolean> NAT_MODE = new AttributeDescriptor<>("NATMode", ValueType.BOOLEAN);
public static final AttributeDescriptor<Boolean> ROUTING_MODE = new AttributeDescriptor<>("routingMode", ValueType.BOOLEAN);
public static final AttributeDescriptor<String> MESSAGE_SOURCE_ADDRESS = new AttributeDescriptor<>("messageSourceAddress", SOURCE_ADDRESS_VALUE);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
index a3b35f0e8..fa492ee45 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mail/AbstractMailAgent.java
@@ -33,11 +33,11 @@ public abstract class AbstractMailAgent<T extends AbstractMailAgent<T, U, V>, U
@NotNull
public static final AttributeDescriptor<String> PROTOCOL = new AttributeDescriptor<>("protocol", ValueType.TEXT);
@NotNull
- public static final AttributeDescriptor<UsernamePassword> USERNAME_AND_PASSWORD = new AttributeDescriptor<>("usernamePassword", ValueType.USERNAME_AND_PASSWORD).withOptional(false);
+ public static final AttributeDescriptor<UsernamePassword> USERNAME_AND_PASSWORD = Agent.USERNAME_AND_PASSWORD.withOptional(false);
@NotNull
- public static final AttributeDescriptor<String> HOST = new AttributeDescriptor<>("host", ValueType.HOSTNAME_OR_IP_ADDRESS).withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
@NotNull
- public static final AttributeDescriptor<Integer> PORT = new AttributeDescriptor<>("port", ValueType.PORT).withOptional(false);
+ public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);
public static final AttributeDescriptor<Integer> CHECK_INTERVAL_SECONDS = new AttributeDescriptor<>("checkIntervalSeconds", ValueType.POSITIVE_INTEGER).withOptional(true);
public static final AttributeDescriptor<Boolean> DELETE_PROCESSED_MAIL = new AttributeDescriptor<>("deleteProcessedMail", ValueType.BOOLEAN).withOptional(true);
public static final AttributeDescriptor<Boolean> PREFER_HTML = new AttributeDescriptor<>("preferHTML", ValueType.BOOLEAN).withOptional(true);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
index 9cb082165..b82d28cbc 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTAgent.java
@@ -19,20 +19,20 @@
*/
package org.openremote.agent.protocol.mqtt;
-import com.fasterxml.jackson.databind.node.BaseJsonNode;
+import jakarta.persistence.Entity;
import org.openremote.agent.protocol.io.IOAgent;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
-import jakarta.persistence.Entity;
import java.util.Optional;
@Entity
public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {
- public static final AttributeDescriptor<String> MQTT_HOST = HOST.withOptional(false);
- public static final AttributeDescriptor<Integer> MQTT_PORT = PORT.withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
+ public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);
public static final AttributeDescriptor<String> CLIENT_ID = new AttributeDescriptor<>("clientId", ValueType.TEXT);
public static final AttributeDescriptor<Boolean> SECURE_MODE = new AttributeDescriptor<>("secureMode", ValueType.BOOLEAN);
public static final AttributeDescriptor<Boolean> RESUME_SESSION = new AttributeDescriptor<>("resumeSession", ValueType.BOOLEAN);
@@ -40,7 +40,7 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {
public static final AttributeDescriptor<String> WEBSOCKET_PATH = new AttributeDescriptor<>("websocketPath", ValueType.TEXT);
public static final AttributeDescriptor<String> WEBSOCKET_QUERY = new AttributeDescriptor<>("websocketQuery", ValueType.TEXT);
public static final AttributeDescriptor<String> LAST_WILL_TOPIC = new AttributeDescriptor<>("lastWillTopic", ValueType.TEXT);
- public static final AttributeDescriptor<BaseJsonNode> LAST_WILL_PAYLOAD = new AttributeDescriptor<>("lastWillPayload", ValueType.JSON);
+ public static final AttributeDescriptor<String> LAST_WILL_PAYLOAD = new AttributeDescriptor<>("lastWillPayload", ValueType.TEXT);
public static final AttributeDescriptor<Boolean> LAST_WILL_RETAIN = new AttributeDescriptor<>("lastWillRetain", ValueType.BOOLEAN);
public static final AgentDescriptor<MQTTAgent, MQTTProtocol, MQTTAgentLink> DESCRIPTOR = new AgentDescriptor<>(
@@ -125,11 +125,11 @@ public class MQTTAgent extends IOAgent<MQTTAgent, MQTTProtocol, MQTTAgentLink> {
return this;
}
- public Optional<BaseJsonNode> getLastWillPayload() {
+ public Optional<String> getLastWillPayload() {
return getAttributes().getValue(LAST_WILL_PAYLOAD);
}
- public MQTTAgent setLastWillPayload(BaseJsonNode lastWillPayload) {
+ public MQTTAgent setLastWillPayload(String lastWillPayload) {
getAttributes().getOrCreate(LAST_WILL_PAYLOAD).setValue(lastWillPayload);
return this;
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTLastWill.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTLastWill.java
index 0689654e4..c56ce1b45 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTLastWill.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTLastWill.java
@@ -27,11 +27,11 @@ import com.fasterxml.jackson.databind.JsonNode;
*/
public class MQTTLastWill {
String topic;
- JsonNode payload;
+ String payload;
boolean retain;
@JsonCreator
- public MQTTLastWill(String topic, JsonNode payload, boolean retain) {
+ public MQTTLastWill(String topic, String payload, boolean retain) {
this.topic = topic;
this.payload = payload;
this.retain = retain;
@@ -41,7 +41,7 @@ public class MQTTLastWill {
return topic;
}
- public JsonNode getPayload() {
+ public String getPayload() {
return payload;
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
index 633337ffb..bcc0e662b 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/mqtt/MQTTProtocol.java
@@ -19,7 +19,6 @@
*/
package org.openremote.agent.protocol.mqtt;
-import com.fasterxml.jackson.databind.node.BaseJsonNode;
import org.apache.http.client.utils.URIBuilder;
import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.model.attribute.Attribute;
@@ -104,7 +103,7 @@ public class MQTTProtocol extends AbstractMQTTClientProtocol<MQTTProtocol, MQTTA
if (agent.getLastWillTopic().isPresent()) {
String topic = agent.getLastWillTopic().get();
- BaseJsonNode payload = agent.getLastWillPayload().orElse(null);
+ String payload = agent.getLastWillPayload().orElse(null);
boolean retain = agent.isLastWillRetain().orElse(false);
lastWill = new MQTTLastWill(topic, payload, retain);
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialProtocol.java
index 708083cba..c079828e0 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialProtocol.java
@@ -96,7 +96,7 @@ public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, Seria
@Override
protected String createWriteMessage(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
- if (attribute.getType().equals(ValueType.EXECUTION_STATUS)) {
+ if (ValueType.EXECUTION_STATUS.equals(attribute.getType())) {
AttributeExecuteStatus status = event.getValue()
.flatMap(ValueUtil::getString)
.flatMap(AttributeExecuteStatus::fromString)
diff --git a/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgent.java
index 45b905d0d..b4a2ca949 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgent.java
@@ -37,8 +37,8 @@ public class SNMPAgent extends Agent<SNMPAgent, SNMPProtocol, SNMPAgentLink> {
public static final ValueDescriptor<SNMPVersion> VALUE_SNMP_VERSION = new ValueDescriptor<>("SNMPVersion", SNMPVersion.class);
public static final AttributeDescriptor<SNMPVersion> SNMP_VERSION = new AttributeDescriptor<>("SNMPVersionValue", VALUE_SNMP_VERSION);
- public static final AttributeDescriptor<String> SNMP_BIND_HOST = BIND_HOST.withOptional(false);
- public static final AttributeDescriptor<Integer> SNMP_BIND_PORT = BIND_PORT.withOptional(false);
+ public static final AttributeDescriptor<String> SNMP_BIND_HOST = Agent.BIND_HOST.withOptional(false);
+ public static final AttributeDescriptor<Integer> SNMP_BIND_PORT = Agent.BIND_PORT.withOptional(false);
public static final AgentDescriptor<SNMPAgent, SNMPProtocol, SNMPAgentLink> DESCRIPTOR = new AgentDescriptor<>(
diff --git a/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPProtocol.java
index 2f4929ff4..05d1b4c2e 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPProtocol.java
@@ -1,6 +1,5 @@
package org.openremote.agent.protocol.snmp;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.snmp.SnmpMessage;
import org.openremote.agent.protocol.AbstractProtocol;
@@ -11,7 +10,6 @@ import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.ValueUtil;
import org.snmp4j.PDU;
import java.util.HashMap;
@@ -74,7 +72,7 @@ public class SNMPProtocol extends AbstractProtocol<SNMPAgent, SNMPAgentLink> {
AttributeRef wildCardAttributeRef;
if ((wildCardAttributeRef = oidMap.get("*")) != null) {
- ObjectNode wildCardValue = ValueUtil.createJsonObject();
+ Map<String, Object> wildCardValue = new HashMap<>();
pdu.getVariableBindings().forEach(variableBinding -> {
wildCardValue.put(variableBinding.getOid().format(), variableBinding.toValueString());
});
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPAgent.java
index bf46675ea..02794902c 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPAgent.java
@@ -20,6 +20,7 @@
package org.openremote.agent.protocol.tcp;
import org.openremote.agent.protocol.io.IOAgent;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.value.AttributeDescriptor;
@@ -29,8 +30,8 @@ import jakarta.persistence.Entity;
@Entity
public class TCPAgent extends IOAgent<TCPAgent, TCPProtocol, DefaultAgentLink> {
- public static final AttributeDescriptor<String> TCP_HOST = HOST.withOptional(false);
- public static final AttributeDescriptor<Integer> TCP_PORT = PORT.withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
+ public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);
public static final AgentDescriptor<TCPAgent, TCPProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
TCPAgent.class, TCPProtocol.class, DefaultAgentLink.class
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java
index d5ddff1f3..d573b6e7b 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriProtocol.java
@@ -17,10 +17,10 @@ import org.openremote.model.attribute.MetaItem;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.ValueHolder;
import java.util.*;
import java.util.logging.Logger;
-import java.util.stream.Collectors;
import static org.openremote.model.asset.impl.LightAsset.BRIGHTNESS;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
@@ -155,13 +155,13 @@ public class TradfriProtocol extends AbstractProtocol<TradfriAgent, DefaultAgent
List<String> obsoleteAssetIds = childAssets.stream()
.map(asset -> {
- Integer deviceId = asset.getAttributes().getValueOrDefault(TradfriAsset.DEVICE_ID);
+ Integer deviceId = asset.getAttribute(TradfriAsset.DEVICE_ID).flatMap(ValueHolder::getValue).orElse(null);
boolean isObsolete = deviceId != null && Arrays.stream(devices)
.noneMatch(device -> deviceId.equals(device.getInstanceId()));
return isObsolete ? asset.getId() : null;
})
.filter(Objects::nonNull)
- .collect(Collectors.toList());
+ .toList();
if (!obsoleteAssetIds.isEmpty()) {
LOG.finest("Removing " + obsoleteAssetIds.size() + " obsolete asset(s): " + this);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/UDPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPAgent.java
index 1b1aa6510..912d66afd 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/udp/UDPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPAgent.java
@@ -20,6 +20,7 @@
package org.openremote.agent.protocol.udp;
import org.openremote.agent.protocol.io.IOAgent;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.value.AttributeDescriptor;
@@ -29,8 +30,8 @@ import jakarta.persistence.Entity;
@Entity
public class UDPAgent extends IOAgent<UDPAgent, UDPProtocol, DefaultAgentLink> {
- public static final AttributeDescriptor<String> UDP_HOST = HOST.withOptional(false);
- public static final AttributeDescriptor<Integer> UDP_PORT = PORT.withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
+ public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);
public static final AgentDescriptor<UDPAgent, UDPProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
UDPAgent.class, UDPProtocol.class, DefaultAgentLink.class
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialAgent.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialAgent.java
index 03fff8ac5..30c5345f2 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusSerialAgent.java
@@ -19,6 +19,7 @@
*/
package org.openremote.agent.protocol.velbus;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.value.AttributeDescriptor;
@@ -27,7 +28,7 @@ import jakarta.persistence.Entity;
@Entity
public class VelbusSerialAgent extends VelbusAgent<VelbusSerialAgent, VelbusSerialProtocol> {
- public static final AttributeDescriptor<String> VELBUS_SERIAL_PORT = SERIAL_PORT.withOptional(false);
+ public static final AttributeDescriptor<String> SERIAL_PORT = Agent.SERIAL_PORT.withOptional(false);
public static final AgentDescriptor<VelbusSerialAgent, VelbusSerialProtocol, VelbusAgentLink> DESCRIPTOR = new AgentDescriptor<>(
VelbusSerialAgent.class, VelbusSerialProtocol.class, VelbusAgentLink.class
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTCPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTCPAgent.java
index 2454bc2af..5c462ded1 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTCPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusTCPAgent.java
@@ -19,6 +19,7 @@
*/
package org.openremote.agent.protocol.velbus;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.value.AttributeDescriptor;
@@ -27,8 +28,8 @@ import jakarta.persistence.Entity;
@Entity
public class VelbusTCPAgent extends VelbusAgent<VelbusTCPAgent, VelbusTCPProtocol> {
- public static final AttributeDescriptor<String> VELBUS_HOST = HOST.withOptional(false);
- public static final AttributeDescriptor<Integer> VELBUS_PORT = PORT.withOptional(false);
+ public static final AttributeDescriptor<String> HOST = Agent.HOST.withOptional(false);
+ public static final AttributeDescriptor<Integer> PORT = Agent.PORT.withOptional(false);
public static final AgentDescriptor<VelbusTCPAgent, VelbusTCPProtocol, VelbusAgentLink> DESCRIPTOR = new AgentDescriptor<>(
VelbusTCPAgent.class, VelbusTCPProtocol.class, VelbusAgentLink.class
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/device/AnalogOutputProcessor.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/device/AnalogOutputProcessor.java
index bfb510a82..cce8d9015 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/device/AnalogOutputProcessor.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/device/AnalogOutputProcessor.java
@@ -26,6 +26,7 @@ import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.ValueDescriptor;
import org.openremote.model.value.ValueType;
+import java.lang.reflect.Array;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
@@ -424,21 +425,23 @@ public class AnalogOutputProcessor extends OutputChannelProcessor {
}
if (ValueUtil.isArray(value.getClass())) {
- return ValueUtil.asJSONArray(value)
- .map(arr -> {
- Optional<Integer> level = ValueUtil.getIntegerCoerced(arr.get(0));
- Optional<Integer> speed = ValueUtil.getIntegerCoerced(arr.get(1));
- return level.isPresent() && speed.isPresent() ? new Pair<>(level.get(), speed.get()) : null;
- });
+ if (Array.getLength(value) != 2) {
+ return Optional.empty();
+ }
+ Object level = Array.get(value, 0);
+ Object speed = Array.get(value, 1);
+ if ((level instanceof Integer) && (speed instanceof Integer)) {
+ return Optional.of(new Pair<>((int) level, (int) speed));
+ }
}
- if (ValueUtil.isObject(value.getClass())) {
- return ValueUtil.asJSONObject(value)
- .map(obj -> {
- Optional<Integer> level = ValueUtil.getIntegerCoerced(obj.get("level"));
- Optional<Integer> speed = ValueUtil.getIntegerCoerced(obj.get("speed"));
- return level.isPresent() && speed.isPresent() ? new Pair<>(level.get(), speed.get()) : null;
- });
+ if (ValueUtil.isMap(value.getClass())) {
+ Map map = (Map)value;
+ Object level = map.get("level");
+ Object speed = map.get("speed");
+ if ((level instanceof Integer) && (speed instanceof Integer)) {
+ return Optional.of(new Pair<>((int) level, (int) speed));
+ }
}
return Optional.empty();
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
index 3735eeaac..e8a9e7ab8 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentProtocol.java
@@ -118,7 +118,7 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
@Override
protected String createWriteMessage(Attribute<?> attribute, WebsocketAgentLink agentLink, AttributeEvent event, Object processedValue) {
- if (attribute.getType().equals(ValueType.EXECUTION_STATUS)) {
+ if (ValueType.EXECUTION_STATUS.equals(attribute.getType())) {
boolean isRequestStart = event.getValue()
.flatMap(v -> ValueUtil.getValue(v, AttributeExecuteStatus.class))
.map(status -> status == AttributeExecuteStatus.REQUEST_START)
@@ -147,7 +147,7 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
Optional<ValueType.MultivaluedStringMap> headers = agent.getConnectHeaders();
Optional<WebsocketSubscription[]> subscriptions = agent.getConnectSubscriptions();
- if (!oAuthGrant.isPresent() && usernameAndPassword.isPresent()) {
+ if (oAuthGrant.isEmpty() && usernameAndPassword.isPresent()) {
String authValue = BasicAuthHelper.createHeader(usernameAndPassword.get().getUsername(), usernameAndPassword.get().getPassword());
headers = Optional.of(headers.map(h -> {
h.remove(HttpHeaders.AUTHORIZATION);
@@ -261,8 +261,7 @@ public class WebsocketAgentProtocol extends AbstractNettyIOClientProtocol<Websoc
}
protected void doSubscription(Map<String, List<String>> headers, WebsocketSubscription subscription) {
- if (subscription instanceof WebsocketHTTPSubscription) {
- WebsocketHTTPSubscription httpSubscription = (WebsocketHTTPSubscription)subscription;
+ if (subscription instanceof WebsocketHTTPSubscription httpSubscription) {
if (TextUtil.isNullOrEmpty(httpSubscription.uri)) {
LOG.warning("Websocket subscription missing or empty URI so skipping: " + subscription);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java
index f52ff7336..000ed1924 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/TypeMapper.java
@@ -32,10 +32,10 @@ import static org.openremote.model.Constants.*;
public class TypeMapper {
public static final class TypeInfo {
- protected ValueDescriptor<?> valueDescriptor;
- protected String[] units;
- protected ValueConstraint[] constraints;
- protected ValueFormat valueFormat;
+ private ValueDescriptor<?> valueDescriptor;
+ private String[] units;
+ private ValueConstraint[] constraints;
+ private ValueFormat valueFormat;
public TypeInfo(ValueDescriptor<?> valueDescriptor) {
this.valueDescriptor = valueDescriptor;
@@ -70,7 +70,7 @@ public class TypeMapper {
typeMap.put(ChannelType.NUMBER, new TypeInfo(ValueType.NUMBER));
typeMap.put(ChannelType.STRING, new TypeInfo(ValueType.TEXT));
typeMap.put(ChannelType.BOOLEAN, new TypeInfo(ValueType.BOOLEAN));
- typeMap.put(ChannelType.ARRAY, new TypeInfo(ValueType.JSON_OBJECT.asArray()));
+ typeMap.put(ChannelType.ARRAY, new TypeInfo(null));
// COMMAND_CLASS_SENSOR_MULTILEVEL
@@ -246,23 +246,13 @@ public class TypeMapper {
format = typeInfo.valueFormat;
units = typeInfo.units;
} else {
- switch(channelType.getValueType()) {
- case INTEGER:
- valueType = ValueType.INTEGER;
- break;
- case NUMBER:
- valueType = ValueType.NUMBER;
- break;
- case BOOLEAN:
- valueType = ValueType.BOOLEAN;
- break;
- case STRING:
- valueType = ValueType.TEXT;
- break;
- case ARRAY:
- valueType = ValueDescriptor.UNKNOWN.asArray();
- break;
- }
+ valueType = switch (channelType.getValueType()) {
+ case INTEGER -> ValueType.INTEGER;
+ case NUMBER -> ValueType.NUMBER;
+ case BOOLEAN -> ValueType.BOOLEAN;
+ case STRING -> ValueType.TEXT;
+ default -> valueType;
+ };
}
Attribute<?> attribute = new Attribute<>(name, valueType);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgent.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgent.java
index 162e98b78..21a605887 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgent.java
@@ -28,7 +28,7 @@ import jakarta.persistence.Entity;
@Entity
public class ZWaveAgent extends Agent<ZWaveAgent, ZWaveProtocol, ZWaveAgentLink> {
- public static final AttributeDescriptor<String> ZWAVE_SERIAL_PORT = SERIAL_PORT.withOptional(false);
+ public static final AttributeDescriptor<String> SERIAL_PORT = Agent.SERIAL_PORT.withOptional(false);
public static AgentDescriptor<ZWaveAgent, ZWaveProtocol, ZWaveAgentLink> DESCRIPTOR = new AgentDescriptor<>(
ZWaveAgent.class, ZWaveProtocol.class, ZWaveAgentLink.class, null
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveProtocol.java
index 03697cfb4..7646907b0 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveProtocol.java
@@ -32,10 +32,7 @@ import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.value.impl.ColourRGB;
import org.openremote.protocol.zwave.model.commandclasses.channel.value.Value;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.function.Consumer;
@@ -104,7 +101,7 @@ public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgentLink>
String linkName = agentLink.getDeviceValue().orElse("");
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
- Class<?> clazz = (attribute == null ? null : attribute.getType().getType());
+ Class<?> clazz = attribute.getTypeClass();
Consumer<Value> sensorValueConsumer = value ->
updateLinkedAttribute(new AttributeState(attributeRef, toAttributeValue(value, clazz)));
@@ -169,19 +166,18 @@ public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgentLink>
retValue = value.getNumber();
} else if (clazz == Integer.class) {
retValue = value.getInteger();
- } else if (clazz == ColourRGB.class && value instanceof org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue) {
- org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue zwArray = (org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue) value;
+ } else if (clazz == ColourRGB.class && value instanceof org.openremote.protocol.zwave.model.commandclasses.channel.value.ArrayValue zwArray) {
if (zwArray.length() >= 3) {
List<Object> values = new ArrayList<>(zwArray.length());
for (int i = 0; i < zwArray.length(); i++) {
values.add(toAttributeValue(zwArray.get(i), Integer.class));
}
- if (values.stream().anyMatch(val -> val == null)) {
+ if (values.stream().anyMatch(Objects::isNull)) {
return null;
}
int offset = (zwArray.length() == 3 ? 0 : 1); // RGB : ARGB
retValue = new ColourRGB(
- (Integer) values.get(0 + offset), (Integer) values.get(1 + offset), (Integer) values.get(2 + offset)
+ (Integer) values.get(offset), (Integer) values.get(1 + offset), (Integer) values.get(2 + offset)
);
}
} else {
diff --git a/container/build.gradle b/container/build.gradle
index 0c9f2de46..d1fe82c9b 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -33,7 +33,7 @@ dependencies {
api "org.postgresql:postgresql:$postgresJdbcVersion"
api "org.flywaydb:flyway-core:$flywaydbVersion"
- api "org.hibernate:hibernate-core:$hibernateVersion"
+ api "org.hibernate.orm:hibernate-core:$hibernateVersion"
api "org.hibernate.orm:hibernate-hikaricp:$hibernateVersion"
api "org.hibernate.validator:hibernate-validator:$hibernateValidatorVersion"
api "com.zaxxer:HikariCP:$hikaricpVersion"
@@ -47,7 +47,6 @@ dependencies {
api "org.apache.camel:camel-health:$camelVersion"
api "org.apache.camel:camel-management:$camelVersion"
api "com.fasterxml.uuid:java-uuid-generator:$uuidGeneratorVersion"
- api "com.vladmihalcea:hibernate-types-60:$hibernateTypesVersion"
api "org.apache.camel:camel-micrometer:$camelVersion"
api "io.micrometer:micrometer-registry-prometheus:$micrometerVersion"
}
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index fb17985a8..6fa8a879f 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -98,10 +98,6 @@ public class Container implements org.openremote.model.Container {
this.devMode = getBoolean(this.config, OR_DEV_MODE, OR_DEV_MODE_DEFAULT);
- if (this.devMode) {
- ValueUtil.JSON.enable(SerializationFeature.INDENT_OUTPUT);
- }
-
boolean metricsEnabled = getBoolean(getConfig(), OR_METRICS_ENABLED, OR_METRICS_ENABLED_DEFAULT);
LOG.log(INFO, "Metrics enabled: " + metricsEnabled);
@@ -158,6 +154,14 @@ public class Container implements org.openremote.model.Container {
LOG.log(INFO, "Initializing service: " + service.getClass().getName());
service.init(Container.this);
}
+
+ // Initialise the asset model
+ ValueUtil.initialise(this);
+
+ if (this.devMode) {
+ ValueUtil.JSON.enable(SerializationFeature.INDENT_OUTPUT);
+ }
+
for (ContainerService service : getServices()) {
LOG.log(INFO, "Starting service: " + service.getClass().getName());
service.start(Container.this);
@@ -211,7 +215,7 @@ public class Container implements org.openremote.model.Container {
@Override
public ContainerService[] getServices() {
synchronized (services) {
- return services.values().toArray(new ContainerService[services.size()]);
+ return services.values().toArray(new ContainerService[0]);
}
}
@@ -231,7 +235,7 @@ public class Container implements org.openremote.model.Container {
@Override
public <T extends ContainerService> boolean hasService(Class<T> type) {
- return getServices(type).size() > 0;
+ return !getServices(type).isEmpty();
}
@Override
diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
index e9a9957c3..bce027618 100644
--- a/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerService.java
@@ -20,12 +20,9 @@
package org.openremote.container.message;
import io.micrometer.core.instrument.MeterRegistry;
-import io.micrometer.core.instrument.Tags;
-import io.micrometer.core.instrument.binder.jvm.ExecutorServiceMetrics;
import org.apache.camel.FluentProducerTemplate;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.DefaultErrorHandlerBuilder;
-import org.apache.camel.component.micrometer.spi.TimedScheduledExecutorService;
import org.apache.camel.component.snmp.SnmpComponent;
import org.apache.camel.health.HealthCheckRegistry;
import org.apache.camel.impl.DefaultCamelContext;
@@ -54,8 +51,6 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;
-import static org.openremote.container.util.MapAccess.getString;
-
public class MessageBrokerService implements ContainerService {
private static final Logger LOG = Logger.getLogger(MessageBrokerService.class.getName());
@@ -168,7 +163,7 @@ public class MessageBrokerService implements ContainerService {
checkRegistry.register(new RoutesHealthCheckRepository());
checkRegistry.register(new ConsumersHealthCheckRepository());
checkRegistry.register(new ContextHealthCheck());
- context.setExtension(HealthCheckRegistry.class, checkRegistry);
+ context.getCamelContextExtension().addContextPlugin(HealthCheckRegistry.class, checkRegistry);
// Force a quick shutdown of routes with in-flight exchanges
context.getShutdownStrategy().setTimeout(5);
@@ -179,7 +174,7 @@ public class MessageBrokerService implements ContainerService {
streamCachingStrategy.setSpoolThreshold(524288); // Half megabyte
context.setStreamCachingStrategy(streamCachingStrategy);
- context.setErrorHandlerFactory(new DefaultErrorHandlerBuilder());
+ context.getCamelContextExtension().setErrorHandlerFactory(new DefaultErrorHandlerBuilder());
((SimpleRegistry)((DefaultRegistry)context.getRegistry()).getFallbackRegistry()).put("OpenRemote", Map.of(Container.class, container));
diff --git a/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperJsonSerializer.java b/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperJsonSerializer.java
deleted file mode 100644
index 0f9323acc..000000000
--- a/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperJsonSerializer.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright 2020, 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.persistence;
-
-import com.vladmihalcea.hibernate.type.util.ObjectMapperWrapper;
-import org.hibernate.internal.util.SerializationHelper;
-import org.openremote.model.util.ValueUtil;
-
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Map;
-
-public class CustomObjectMapperJsonSerializer extends com.vladmihalcea.hibernate.type.util.ObjectMapperJsonSerializer {
-
- // super class field is private
- protected static ObjectMapperWrapper objectMapperWrapper = new ObjectMapperWrapper(ValueUtil.JSON);
-
- public CustomObjectMapperJsonSerializer() {
- super(objectMapperWrapper);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public <T> T clone(T object) {
-
- boolean useStandardSerialisation = false;
-
- // Bug in default implementation means it cannot cope with subclasses of parameterized types that don't have type params
- if (object instanceof Collection && object.getClass().getTypeParameters().length == 0) {
- Object firstElement = ValueUtil.findFirstNonNullElement((Collection<?>) object);
-
- if (firstElement != null && !(firstElement instanceof Serializable)) {
- return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), (Class<T>)object.getClass());
- } else {
- useStandardSerialisation = true;
- }
- }
-
- if (object instanceof Map && object.getClass().getTypeParameters().length == 0) {
- Map.Entry<?,?> firstEntry = ValueUtil.findFirstNonNullEntry((Map<?,?>) object);
- if (firstEntry != null) {
- Object key = firstEntry.getKey();
- Object value = firstEntry.getValue();
- if (!(key instanceof Serializable) || !(value instanceof Serializable)) {
- return objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), (Class<T>)object.getClass());
- } else {
- useStandardSerialisation = true;
- }
- }
- }
-
- if (useStandardSerialisation) {
- return object instanceof Serializable ?
- (T) SerializationHelper.clone((Serializable) object) :
- objectMapperWrapper.fromBytes(objectMapperWrapper.toBytes(object), (Class<T>) object.getClass());
- }
-
- return super.clone(object);
- }
-}
diff --git a/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperSupplier.java b/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperSupplier.java
deleted file mode 100644
index 279c2ea1c..000000000
--- a/container/src/main/java/org/openremote/container/persistence/CustomObjectMapperSupplier.java
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright 2020, 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.persistence;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.vladmihalcea.hibernate.type.util.ObjectMapperSupplier;
-import org.openremote.model.util.ValueUtil;
-
-public class CustomObjectMapperSupplier implements ObjectMapperSupplier {
-
- @Override
- public ObjectMapper get() {
- return ValueUtil.JSON;
- }
-}
diff --git a/container/src/main/java/org/openremote/container/persistence/Database.java b/container/src/main/java/org/openremote/container/persistence/Database.java
index 5d57bdb59..4488242fb 100644
--- a/container/src/main/java/org/openremote/container/persistence/Database.java
+++ b/container/src/main/java/org/openremote/container/persistence/Database.java
@@ -52,8 +52,7 @@ public interface Database {
@Override
public Properties createProperties() {
- Properties properties = new Properties();
- return properties;
+ return new Properties();
}
@Override
@@ -61,6 +60,7 @@ public interface Database {
return "postgresql";
}
+ @SuppressWarnings("deprecation")
@Override
public void open(Properties properties, String connectionUrl, String username, String password, int connectionTimeoutSeconds, int minIdle, int maxPoolSize) {
hikariConfig = new HikariConfig();
@@ -71,13 +71,14 @@ public interface Database {
hikariConfig.addDataSourceProperty("url", connectionUrl);
hikariConfig.setUsername(username);
hikariConfig.setPassword(password);
- hikariConfig.setConnectionTimeout(connectionTimeoutSeconds * 1000);
- hikariConfig.setInitializationFailTimeout(connectionTimeoutSeconds * 1000);
+ hikariConfig.setConnectionTimeout(connectionTimeoutSeconds * 1000L);
+ hikariConfig.setInitializationFailTimeout(connectionTimeoutSeconds * 1000L);
hikariConfig.setMinimumIdle(minIdle);
hikariConfig.setMaximumPoolSize(maxPoolSize);
hikariDataSource = new HikariDataSource(hikariConfig);
+ // TODO: Change when hikariCP is updated to look for new property
properties.put(AvailableSettings.DATASOURCE, hikariDataSource);
}
diff --git a/container/src/main/java/org/openremote/container/persistence/FlushEntityEventListener.java b/container/src/main/java/org/openremote/container/persistence/FlushEntityEventListener.java
index a8cf453ba..f47fae781 100644
--- a/container/src/main/java/org/openremote/container/persistence/FlushEntityEventListener.java
+++ b/container/src/main/java/org/openremote/container/persistence/FlushEntityEventListener.java
@@ -28,7 +28,7 @@ import org.hibernate.type.Type;
/**
* This listener will only push the dirty properties through to the interceptor's onFlushDirty.
- *
+ * <p>
* Unfortunately there are internal and private dependencies which makes extending not ideal but it is fine for our
* use case.
*/
@@ -77,18 +77,4 @@ public class FlushEntityEventListener extends DefaultFlushEntityEventListener {
.getInterceptor()
.onFlushDirty(entity, entry.getId(), dirtyPropertiesValues, loadedPropertiesValues, dirtyPropertiesNames, dirtyPropertiesTypes);
}
-
- /**
- * This method was replaced with the invokeInterceptor(SessionImplementor session, FlushEntityEvent event)
- * method.
- *
- * @deprecated
- */
- @Deprecated
- @Override
- protected boolean invokeInterceptor(SessionImplementor session, Object entity, EntityEntry entry,
- final Object[] values, EntityPersister persister) {
- throw new UnsupportedOperationException(
- "Since this method was replaced with another one it was not suppose to be invoked.");
- }
}
diff --git a/container/src/main/java/org/openremote/container/persistence/JsonFormatMapper.java b/container/src/main/java/org/openremote/container/persistence/JsonFormatMapper.java
new file mode 100644
index 000000000..5921e438d
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/persistence/JsonFormatMapper.java
@@ -0,0 +1,41 @@
+package org.openremote.container.persistence;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import org.hibernate.type.descriptor.WrapperOptions;
+import org.hibernate.type.descriptor.java.JavaType;
+import org.hibernate.type.format.FormatMapper;
+import org.openremote.model.util.ValueUtil;
+
+/**
+ * A {@link FormatMapper} that uses our own {@link com.fasterxml.jackson.databind.ObjectMapper}
+ */
+@SuppressWarnings("unchecked")
+public class JsonFormatMapper implements FormatMapper {
+
+ @Override
+ public <T> T fromString(CharSequence charSequence, JavaType<T> javaType, WrapperOptions wrapperOptions) {
+ if ( javaType.getJavaType() == String.class ) {
+ return (T) charSequence.toString();
+ }
+ try {
+ return ValueUtil.JSON.readValue( charSequence.toString(), ValueUtil.JSON.constructType( javaType.getJavaType() ) );
+ }
+ catch (JsonProcessingException e) {
+ throw new IllegalArgumentException( "Could not deserialize string to java type: " + javaType, e );
+ }
+ }
+
+ @Override
+ public <T> String toString(T value, JavaType<T> javaType, WrapperOptions wrapperOptions) {
+ if ( javaType.getJavaType() == String.class ) {
+ return (String) value;
+ }
+ try {
+ return ValueUtil.JSON.writerFor( ValueUtil.JSON.constructType( javaType.getJavaType() ) )
+ .writeValueAsString( value );
+ }
+ catch (JsonProcessingException e) {
+ throw new IllegalArgumentException( "Could not serialize object of java type: " + javaType, e );
+ }
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
index 565e462f2..1d6543469 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEventInterceptor.java
@@ -23,12 +23,11 @@ import jakarta.transaction.Status;
import jakarta.transaction.Synchronization;
import org.apache.camel.CamelExecutionException;
import org.hibernate.CallbackException;
-import org.hibernate.EmptyInterceptor;
+import org.hibernate.Interceptor;
import org.hibernate.Transaction;
import org.hibernate.type.Type;
import org.openremote.model.PersistenceEvent;
-import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
@@ -38,7 +37,7 @@ import java.util.logging.Logger;
/**
* Intercept Hibernate lifecycle events and publish a message.
*/
-public class PersistenceEventInterceptor extends EmptyInterceptor {
+public class PersistenceEventInterceptor implements Interceptor {
private static final Logger LOG = Logger.getLogger(PersistenceEventInterceptor.class.getName());
protected Consumer<PersistenceEvent<?>> eventConsumer;
@@ -49,7 +48,8 @@ public class PersistenceEventInterceptor extends EmptyInterceptor {
}
@Override
- public boolean onSave(Object entity, Serializable id,
+ public boolean onSave(Object entity,
+ Object id,
Object[] state, String[] propertyNames, Type[] types)
throws CallbackException {
persistenceEvents.add(new PersistenceEvent<>(
@@ -62,7 +62,8 @@ public class PersistenceEventInterceptor extends EmptyInterceptor {
}
@Override
- public boolean onFlushDirty(Object entity, Serializable id,
+ public boolean onFlushDirty(Object entity,
+ Object id,
Object[] currentState, Object[] previousState,
String[] propertyNames, Type[] types)
throws CallbackException {
@@ -77,7 +78,8 @@ public class PersistenceEventInterceptor extends EmptyInterceptor {
}
@Override
- public void onDelete(Object entity, Serializable id,
+ public void onDelete(Object entity,
+ Object id,
Object[] state,
String[] propertyNames,
Type[] types) {
@@ -121,8 +123,4 @@ public class PersistenceEventInterceptor extends EmptyInterceptor {
}
});
}
-
- @Override
- public void afterTransactionCompletion(Transaction tx) {
- }
}
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceHealthStatusProvider.java b/container/src/main/java/org/openremote/container/persistence/PersistenceHealthStatusProvider.java
index 80e69d7e7..adaac901f 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceHealthStatusProvider.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceHealthStatusProvider.java
@@ -19,18 +19,16 @@
*/
package org.openremote.container.persistence;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import com.zaxxer.hikari.HikariPoolMXBean;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
+import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -42,11 +40,6 @@ public class PersistenceHealthStatusProvider implements HealthStatusProvider {
public static final String NAME = "db";
protected PersistenceService persistenceService;
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
persistenceService = container.getService(PersistenceService.class);
@@ -87,13 +80,11 @@ public class PersistenceHealthStatusProvider implements HealthStatusProvider {
int totalConnections = poolMBean.getTotalConnections();
int threadsWaiting = poolMBean.getThreadsAwaitingConnection();
- ObjectNode value = ValueUtil.JSON.createObjectNode();
- value.put("idleConnections", idleConnections);
- value.put("activeConnections", activeConnections);
- value.put("totalConnections", totalConnections);
- value.put("threadsWaiting", threadsWaiting);
-
- return value;
+ return Map.<String, Object>of(
+ "idleConnections", idleConnections,
+ "activeConnections", activeConnections,
+ "totalConnections", totalConnections,
+ "threadsWaiting", threadsWaiting);
} catch (MalformedObjectNameException e) {
LOG.log(Level.SEVERE, "Failed to get hikari connection pool status", e);
}
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
index 95a03ee83..39cb14de7 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -292,6 +292,10 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
);
}
+ persistenceUnitProperties.put(AvailableSettings.JSON_FORMAT_MAPPER, JsonFormatMapper.class.getName());
+ // Disable JPA validation as it triggers on select for entities with JSON columns - we do our own validation
+ persistenceUnitProperties.put(AvailableSettings.JAKARTA_VALIDATION_MODE, ValidationMode.NONE.name());
+
persistenceUnitProperties.put(AvailableSettings.DEFAULT_SCHEMA, dbSchema);
// Add custom integrator so we can register a custom flush entity event listener
@@ -323,7 +327,19 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
openDatabase(container, database, dbUsername, dbPassword, connectionUrl);
prepareSchema(container, connectionUrl, dbUsername, dbPassword, dbSchema);
+ }
+
+ protected EntityManagerFactory getEntityManagerFactory(Properties properties, List<String> classNames) {
+ PersistenceUnitInfo persistenceUnitInfo = new PersistenceUnitInfo(classNames, properties);
+ return new EntityManagerFactoryBuilderImpl(
+ new PersistenceUnitInfoDescriptor(persistenceUnitInfo), null)
+ .build();
+ }
+
+
+ @Override
+ public void start(Container container) throws Exception {
// Register standard entity classes and also any Entity ClassProviders
List<String> entityClasses = new ArrayList<>(50);
entityClasses.add(Asset.class.getName());
@@ -352,7 +368,7 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
entityClasses.add(UnknownAsset.class.getName()); // This doesn't have an asset descriptor which is why it is specifically added
Arrays.stream(ValueUtil.getAssetDescriptors(null))
.map(AssetDescriptor::getType)
- .filter(assetClass -> assetClass.getAnnotation(Entity.class) != null)
+ .filter(assetClass -> assetClass != null && assetClass.getAnnotation(Entity.class) != null)
.map(Class::getName)
.forEach(entityClasses::add);
@@ -366,20 +382,6 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
//Persistence.createEntityManagerFactory(persistenceUnitName, persistenceUnitProperties);
}
- protected EntityManagerFactory getEntityManagerFactory(Properties properties, List<String> classNames) {
- PersistenceUnitInfo persistenceUnitInfo = new PersistenceUnitInfo(classNames, properties);
-
- return new EntityManagerFactoryBuilderImpl(
- new PersistenceUnitInfoDescriptor(persistenceUnitInfo), null)
- .build();
- }
-
-
- @Override
- public void start(Container container) throws Exception {
-
- }
-
@Override
public void stop(Container container) throws Exception {
if (entityManagerFactory != null) {
@@ -427,7 +429,11 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
} catch (Exception ex) {
if (tx != null && tx.isActive()) {
try {
- LOG.log(Level.FINE, "Rolling back failed transaction, cause follows", ex);
+ if (LOG.isLoggable(Level.FINER)) {
+ LOG.log(Level.FINE, "Rolling back failed transaction, cause follows", ex);
+ } else {
+ LOG.log(Level.FINE, "Rolling back failed transaction");
+ }
tx.rollback();
} catch (RuntimeException rbEx) {
LOG.log(Level.SEVERE, "Rollback of transaction failed!", rbEx);
@@ -459,13 +465,9 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
Field[] propertyFields = getEntityPropertyFields(clazz, includeFields, excludeFields);
switch (cause) {
- case CREATE:
- publishPersistenceEvent(cause, currentEntity, null, null, null);
- break;
- case DELETE:
- publishPersistenceEvent(cause, previousEntity, null, null, null);
- break;
- case UPDATE:
+ case CREATE -> publishPersistenceEvent(cause, currentEntity, null, null, null);
+ case DELETE -> publishPersistenceEvent(cause, previousEntity, null, null, null);
+ case UPDATE -> {
List<String> propertyNames = new ArrayList<>(propertyFields.length);
List<Object> currentState = new ArrayList<>(propertyFields.length);
List<Object> previousState = new ArrayList<>(propertyFields.length);
@@ -479,7 +481,7 @@ public class PersistenceService implements ContainerService, Consumer<Persistenc
}
});
publishPersistenceEvent(cause, currentEntity, propertyNames.toArray(new String[0]), currentState.toArray(), previousState.toArray());
- break;
+ }
}
}
diff --git a/container/src/main/java/org/openremote/container/xml/DOMParser.java b/container/src/main/java/org/openremote/container/xml/DOMParser.java
index 439a67cf1..f055b3384 100644
--- a/container/src/main/java/org/openremote/container/xml/DOMParser.java
+++ b/container/src/main/java/org/openremote/container/xml/DOMParser.java
@@ -45,6 +45,7 @@ import java.io.*;
import java.net.URI;
import java.net.URL;
import java.util.HashMap;
+import java.util.Map;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -77,11 +78,7 @@ public abstract class DOMParser<D extends DOM> implements ErrorHandler, EntityRe
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- schemaFactory.setResourceResolver(new CatalogResourceResolver(
- new HashMap<URI, URL>() {{
- put(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE);
- }}
- ));
+ schemaFactory.setResourceResolver(new CatalogResourceResolver(Map.of(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE)));
if (schemaSources != null) {
schema = schemaFactory.newSchema(schemaSources);
diff --git a/container/src/main/java/org/openremote/container/xml/SAXParser.java b/container/src/main/java/org/openremote/container/xml/SAXParser.java
index de366bf73..2cd3f3338 100644
--- a/container/src/main/java/org/openremote/container/xml/SAXParser.java
+++ b/container/src/main/java/org/openremote/container/xml/SAXParser.java
@@ -28,9 +28,7 @@ import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
-import java.net.URI;
-import java.net.URL;
-import java.util.HashMap;
+import java.util.Map;
import java.util.logging.Logger;
public class SAXParser {
@@ -73,11 +71,7 @@ public class SAXParser {
protected Schema createSchema(Source[] schemaSources) {
try {
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
- schemaFactory.setResourceResolver(new CatalogResourceResolver(
- new HashMap<URI, URL>() {{
- put(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE);
- }}
- ));
+ schemaFactory.setResourceResolver(new CatalogResourceResolver(Map.of(DOM.XML_SCHEMA_NAMESPACE, DOM.XML_SCHEMA_RESOURCE)));
return schemaFactory.newSchema(schemaSources);
} catch (Exception ex) {
throw new RuntimeException(ex);
diff --git a/gradle.properties b/gradle.properties
index 1faec5c7f..c05879140 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -12,11 +12,11 @@ resteasyVersion = 6.2.2.Final
jbossLoggingAnnotationsVersion = 2.0.2.Final
keycloakVersion = 18.0.2
classgraphVersion=4.8.149
-jacksonVersion = 2.13.4
+jacksonVersion = 2.15.2
groovyVersion = 3.0.10
groovySandboxVersion = 4.0.0
sqliteVersion = 3.34.0
-hibernateVersion = 6.1.7.Final
+hibernateVersion = 6.3.1.Final
hibernateValidatorVersion = 8.0.0.Final
hikaricpVersion = 5.0.1
postgresJdbcVersion = 42.6.0
@@ -24,7 +24,7 @@ junitVersion = 4.13.2
spockVersion = 2.0-groovy-3.0
byteBuddyVersion = 1.11.0
objenesisVersion = 3.2
-camelVersion = 3.20.6
+camelVersion = 4.0.1
sunriseSunsetCalculatorVersion = 1.2
easyRulesVersion = 4.1.0
quartzVersion= 2.3.2
@@ -45,7 +45,6 @@ typescriptGeneratorVersion = 3.2.1263
californiumCoreVersion = 2.1.0
californiumScandiumVersion = 3.5.0
zwaveVersion = 3.4.0-SNAPSHOT
-hibernateTypesVersion = 2.21.1
reflectionsVersion=0.9.12
swaggerVersion=2.2.8
jsonSchemaVersion=4.18.0
@@ -56,7 +55,7 @@ failsafeVersion=3.1.0
suncalcVersion=3.5
snapshotsRepoUrl=https://s01.oss.sonatype.org/content/repositories/snapshots/
releasesRepoUrl=https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/
-activeMQVersion = 2.29.0
+activeMQVersion = 2.31.0
jbossLoggingManagerVersion=2.1.19.Final
greenmailVersion=2.0.0
prometheusVersion=0.16.0
diff --git a/manager/build.gradle b/manager/build.gradle
index 4af65e6f5..cf02f5ba4 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -46,7 +46,8 @@ dependencies {
}
implementation("org.quartz-scheduler:quartz:$quartzVersion") {
- exclude group: "c3p0"
+ exclude module: "c3p0"
+ exclude module: "HikariCP-java7"
}
implementation "org.shredzone.commons:commons-suncalc:$suncalcVersion"
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/agent/AgentHealthStatusProvider.java
index 5e039541b..3e7b90106 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentHealthStatusProvider.java
@@ -19,14 +19,14 @@
*/
package org.openremote.manager.agent;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.ConnectionStatus;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
+import java.util.HashMap;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
public class AgentHealthStatusProvider implements HealthStatusProvider {
@@ -34,11 +34,6 @@ public class AgentHealthStatusProvider implements HealthStatusProvider {
public static final String NAME = "agents";
protected AgentService agentService;
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
agentService = container.getService(AgentService.class);
@@ -66,7 +61,7 @@ public class AgentHealthStatusProvider implements HealthStatusProvider {
AtomicInteger errorCount = new AtomicInteger(0);
AtomicInteger otherCount = new AtomicInteger(0);
- ObjectNode objectValue = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> objectValue = new HashMap<>();
objectValue.put("agents", agentService.getAgents().size());
objectValue.put("protocols", agentService.protocolInstanceMap.size());
@@ -75,32 +70,20 @@ public class AgentHealthStatusProvider implements HealthStatusProvider {
if (status != null) {
switch (status) {
-
- case DISCONNECTED:
- case CONNECTING:
- case DISCONNECTING:
- case WAITING:
- otherCount.incrementAndGet();
- break;
- case CONNECTED:
- connectedCount.incrementAndGet();
- break;
- case DISABLED:
- disabledCount.incrementAndGet();
- break;
- case ERROR:
- errorCount.incrementAndGet();
- break;
+ case DISCONNECTED, CONNECTING, DISCONNECTING, WAITING -> otherCount.incrementAndGet();
+ case CONNECTED -> connectedCount.incrementAndGet();
+ case DISABLED -> disabledCount.incrementAndGet();
+ case ERROR -> errorCount.incrementAndGet();
}
} else {
otherCount.incrementAndGet();
}
- ObjectNode agentValue = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> agentValue = new HashMap<>();
agentValue.put("name", agent.getName());
agentValue.put("status", status != null ? status.name() : "null");
agentValue.put("type", agent.getType());
- objectValue.set(agent.getId(), agentValue);
+ objectValue.put(agent.getId(), agentValue);
}
objectValue.put("totalAgents", agentService.getAgents().size());
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
index df6b092d0..a371d537b 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java
@@ -86,7 +86,7 @@ import static org.openremote.model.value.MetaItemType.AGENT_LINK;
public class AgentService extends RouteBuilder implements ContainerService, AssetUpdateProcessor, ProtocolAssetService {
private static final Logger LOG = Logger.getLogger(AgentService.class.getName());
- public static final int PRIORITY = DEFAULT_PRIORITY + 100; // Start quite late to ensure asset model etc. are initialised
+ public static final int PRIORITY = MessageBrokerService.PRIORITY + 100; // Start quite late to ensure asset model etc. are initialised
protected TimerService timerService;
protected ManagerIdentityService identityService;
protected AssetProcessingService assetProcessingService;
@@ -144,7 +144,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
Collection<Agent<?, ?, ?>> agents = getAgents().values();
LOG.fine("Found agent count = " + agents.size());
- agents.stream().forEach(this::doAgentInit);
+ agents.forEach(this::doAgentInit);
}
@Override
@@ -246,20 +246,18 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
Agent<?, ?, ?> agent = persistenceEvent.getEntity();
switch (persistenceEvent.getCause()) {
- case CREATE:
+ case CREATE -> {
agent = addReplaceAgent(agent);
doAgentInit(agent);
- break;
- case UPDATE:
- onAgentUpdated(agent);
- break;
- case DELETE:
+ }
+ case UPDATE -> onAgentUpdated(agent);
+ case DELETE -> {
if (!removeAgent(agent.getId())) {
return;
}
// Unlink any attributes that have an agent link to this agent
stopAgent(agent.getId());
- break;
+ }
}
}
@@ -291,25 +289,21 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
Asset<?> asset = persistenceEvent.getEntity();
switch (persistenceEvent.getCause()) {
- case CREATE:
+ case CREATE ->
// Link any AGENT_LINK attributes to their referenced agent asset
getGroupedAgentLinkAttributes(
asset.getAttributes().stream(),
attribute -> true
).forEach((agent, attributes) -> this.linkAttributes(agent, asset.getId(), attributes));
-
- break;
- case UPDATE:
+ case UPDATE -> {
if (!persistenceEvent.hasPropertyChanged("attributes")) {
return;
}
-
- List<Attribute<?>> oldLinkedAttributes = ((AttributeMap)persistenceEvent.getPreviousState("attributes"))
+ List<Attribute<?>> oldLinkedAttributes = ((AttributeMap) persistenceEvent.getPreviousState("attributes"))
.stream()
.filter(attr -> attr.hasMeta(AGENT_LINK))
.collect(toList());
-
List<Attribute<?>> newLinkedAttributes = ((AttributeMap) persistenceEvent.getCurrentState("attributes"))
.stream()
.filter(attr -> attr.hasMeta(AGENT_LINK))
@@ -317,7 +311,6 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
// Unlink obsolete or modified linked attributes
List<Attribute<?>> obsoleteOrModified = getAddedOrModifiedAttributes(newLinkedAttributes, oldLinkedAttributes).collect(toList());
-
getGroupedAgentLinkAttributes(
obsoleteOrModified.stream(),
attribute -> true
@@ -329,14 +322,12 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
!oldLinkedAttributes.contains(attr) || obsoleteOrModified.contains(attr)),
attribute -> true)
.forEach((agent, attributes) -> linkAttributes(agent, asset.getId(), attributes));
-
- break;
- case DELETE: {
+ }
+ case DELETE -> {
// Unlink any AGENT_LINK attributes from the referenced protocol
getGroupedAgentLinkAttributes(asset.getAttributes().stream(), attribute -> true)
.forEach((agent, attributes) -> unlinkAttributes(agent.getId(), asset.getId(), attributes));
- break;
}
}
@@ -509,7 +500,6 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse
* processing of this event by the processing chain. The protocol should raise sensor updates as
* required (i.e. the protocol is responsible for synchronising state with the database).
*/
- @SuppressWarnings({"unchecked", "rawtypes"})
@Override
public boolean processAssetUpdate(EntityManager entityManager,
Asset<?> asset,
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetModelResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetModelResourceImpl.java
index 7bc29f30c..d18a8f2e0 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetModelResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetModelResourceImpl.java
@@ -29,6 +29,8 @@ import org.openremote.model.asset.AssetTypeInfo;
import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
+import java.util.Map;
+
public class AssetModelResourceImpl extends ManagerWebResource implements AssetModelResource {
protected AssetModelService assetModelService;
@@ -54,12 +56,12 @@ public class AssetModelResourceImpl extends ManagerWebResource implements AssetM
}
@Override
- public ValueDescriptor<?>[] getValueDescriptors(RequestParams requestParams, String parentId) {
+ public Map<String, ValueDescriptor<?>> getValueDescriptors(RequestParams requestParams, String parentId) {
return assetModelService.getValueDescriptors(parentId);
}
@Override
- public MetaItemDescriptor<?>[] getMetaItemDescriptors(RequestParams requestParams, String parentId) {
+ public Map<String, MetaItemDescriptor<?>> getMetaItemDescriptors(RequestParams requestParams, String parentId) {
return assetModelService.getMetaItemDescriptors(parentId);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java b/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java
index 65326e533..2499e7399 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java
@@ -19,33 +19,197 @@
*/
package org.openremote.manager.asset;
+import com.fasterxml.jackson.core.*;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import com.fasterxml.jackson.databind.util.TokenBuffer;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.message.MessageBrokerService;
+import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.event.ClientEventService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.manager.web.ManagerWebService;
+import org.openremote.model.AssetModelProvider;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.asset.AssetDescriptor;
import org.openremote.model.asset.AssetTypeInfo;
+import org.openremote.model.attribute.MetaMap;
+import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
+import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.*;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Function;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES;
+
// TODO: Implement model client event support
/**
* A service for abstracting {@link org.openremote.model.util.ValueUtil} and handling local model requests vs
* {@link org.openremote.model.asset.impl.GatewayAsset} model requests. It also manages the {@link
* org.openremote.model.asset.AssetModelResource} and provides support for model requests via the client event bus.
+ * <p>
+ * Also implements an {@link AssetModelProvider} that loads descriptors from the file system; specifically in
+ * {@link PersistenceService#OR_STORAGE_DIR}/{@link #DIRECTORY_NAME}; file structure should be a JSON representation
+ * of {@link AssetTypeInfo}.
*/
-public class AssetModelService extends RouteBuilder implements ContainerService {
+public class AssetModelService extends RouteBuilder implements ContainerService, AssetModelProvider {
+ protected static ObjectMapper JSON = ValueUtil.JSON.copy()
+ .addMixIn(AssetTypeInfo.class, AssetTypeInfoMixin.class);
+
+ @JsonDeserialize(using = AssetTypeInfoDeserializer.class)
+ private static final class AssetTypeInfoMixin {
+ @JsonDeserialize
+ @JsonSerialize
+ MetaItemDescriptor<?>[] metaItemDescriptors;
+ @JsonDeserialize
+ @JsonSerialize
+ ValueDescriptor<?>[] valueDescriptors;
+
+ //AttributeDescriptor<?>[] getAttributeDescriptors() { return null; }
+ }
+
+ /**
+ * Extracts the {@link ValueDescriptor}s then {@link MetaItemDescriptor}s then {@link AttributeDescriptor}
+ * making each available to the next during deserialization.
+ */
+ private static final class AssetTypeInfoDeserializer extends StdDeserializer<AssetTypeInfo> {
+
+ private static final JavaType VALUE_DESCRIPTOR_TYPE = TypeFactory.defaultInstance().constructType(ValueDescriptor[].class);
+ private static final JavaType META_ITEM_DESCRIPTOR_TYPE = TypeFactory.defaultInstance().constructType(MetaItemDescriptor[].class);
+ private static final JavaType ATTRIBUTE_DESCRIPTOR_TYPE = TypeFactory.defaultInstance().constructType(AttributeDescriptor[].class);
+ private static final JavaType ASSET_DESCRIPTOR_TYPE = TypeFactory.defaultInstance().constructType(AssetDescriptor.class);
+
+ private AssetTypeInfoDeserializer() {
+ super(AssetTypeInfo.class);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public AssetTypeInfo deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JacksonException {
+ if (!jp.isExpectedStartObjectToken()) {
+ throw JsonMappingException.from(jp, "Must be an object");
+ }
+
+ TokenBuffer attributeDescriptorBuffer = null;
+ TokenBuffer metaItemDescriptorBuffer = null;
+ AssetDescriptor<?> assetDescriptor = null;
+ AttributeDescriptor<?>[] attributeDescriptors = null;
+ final AtomicReference<ValueDescriptor[]> valueDescriptors = new AtomicReference<>();
+ final AtomicReference<MetaItemDescriptor[]> metaItemDescriptors = new AtomicReference<>();
+
+ Function<String, ValueDescriptor<?>> valueDescriptorProvider = (name) -> {
+ ValueDescriptor<?> found = null;
+ if (valueDescriptors.get() != null) {
+ found = Arrays.stream(valueDescriptors.get()).filter(vd -> vd.getName().equals(name)).findFirst().orElse(null);
+ }
+ if (found == null) {
+ found = ValueUtil.getValueDescriptor(name).orElse(null);
+ }
+ return found;
+ };
+
+ Function<String, MetaItemDescriptor<?>> metaDescriptorProvider = (name) -> {
+ if (metaItemDescriptors.get() != null) {
+ return Arrays.stream(metaItemDescriptors.get()).filter(mid -> mid.getName().equals(name)).findFirst().orElse(null);
+ }
+ return null;
+ };
+ ctxt.setAttribute(ValueDescriptor.ValueDescriptorDeserializer.VALUE_DESCRIPTOR_PROVIDER, valueDescriptorProvider);
+ ctxt.setAttribute(MetaMap.MetaObjectDeserializer.META_DESCRIPTOR_PROVIDER, metaDescriptorProvider);
+
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String propName = jp.currentName();
+ if (jp.currentToken() == JsonToken.FIELD_NAME) {
+ jp.nextToken();
+ }
+ if (jp.currentToken() == JsonToken.VALUE_NULL) {
+ continue;
+ }
+
+ switch (propName) {
+ case "attributeDescriptors" -> {
+ if (metaItemDescriptors.get() == null) {
+ attributeDescriptorBuffer = new TokenBuffer(jp, ctxt);
+ attributeDescriptorBuffer.copyCurrentStructure(jp);
+ } else {
+ attributeDescriptors = (AttributeDescriptor<?>[])ctxt.findRootValueDeserializer(ATTRIBUTE_DESCRIPTOR_TYPE).deserialize(jp, ctxt);
+ }
+ }
+ case "metaItemDescriptors" -> {
+ if (valueDescriptors.get() == null) {
+ metaItemDescriptorBuffer = new TokenBuffer(jp, ctxt);
+ metaItemDescriptorBuffer.copyCurrentStructure(jp);
+ } else {
+ metaItemDescriptors.set((MetaItemDescriptor<?>[])ctxt.findRootValueDeserializer(META_ITEM_DESCRIPTOR_TYPE).deserialize(jp, ctxt));
+ }
+ }
+ case "valueDescriptors" -> {
+ valueDescriptors.set((ValueDescriptor<?>[]) ctxt.findRootValueDeserializer(VALUE_DESCRIPTOR_TYPE).deserialize(jp, ctxt));
+ }
+ case "assetDescriptor" -> {
+ assetDescriptor = (AssetDescriptor<?>) ctxt.findRootValueDeserializer(ASSET_DESCRIPTOR_TYPE).deserialize(jp, ctxt);
+ }
+ }
+ }
+
+ if (metaItemDescriptorBuffer != null) {
+ JsonParser parser = metaItemDescriptorBuffer.asParser();
+ parser.nextToken();
+ metaItemDescriptors.set((MetaItemDescriptor<?>[])ctxt.findRootValueDeserializer(META_ITEM_DESCRIPTOR_TYPE).deserialize(parser, ctxt));
+ }
+ if (attributeDescriptorBuffer != null) {
+ JsonParser parser = attributeDescriptorBuffer.asParser();
+ parser.nextToken();
+ attributeDescriptors = (AttributeDescriptor<?>[])ctxt.findRootValueDeserializer(ATTRIBUTE_DESCRIPTOR_TYPE).deserialize(parser, ctxt);
+ }
+ if (assetDescriptor == null) {
+ throw new JsonParseException(jp, "Must contain an asset descriptor");
+ }
+ return new AssetTypeInfo(
+ assetDescriptor,
+ attributeDescriptors,
+ metaItemDescriptors.get() != null ? metaItemDescriptors.get() : new MetaItemDescriptor[0],
+ valueDescriptors.get() != null ? valueDescriptors.get() : new ValueDescriptor[0]
+ );
+ }
+ }
+
+ protected static Logger LOG = SyslogCategory.getLogger(MODEL_AND_VALUES, AssetModelService.class);
+ public static final String DIRECTORY_NAME = "asset_model";
protected ManagerIdentityService identityService;
protected ClientEventService clientEventService;
protected GatewayService gatewayService;
+ protected PersistenceService persistenceService;
+ protected Map<String, AssetTypeInfo> dynamicAssetTypeInfos;
+ protected Path storageDir;
+
+ @Override
+ public int getPriority() {
+ // Need storageDir from PersistenceService
+ return PersistenceService.PRIORITY + 10;
+ }
@Override
public void configure() throws Exception {
@@ -59,17 +223,13 @@ public class AssetModelService extends RouteBuilder implements ContainerService
// .end();
}
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
identityService = container.getService(ManagerIdentityService.class);
clientEventService = container.getService(ClientEventService.class);
gatewayService = container.getService(GatewayService.class);
+ persistenceService = container.getService(PersistenceService.class);
container.getService(ManagerWebService.class).addApiSingleton(
new AssetModelResourceImpl(
@@ -82,6 +242,31 @@ public class AssetModelService extends RouteBuilder implements ContainerService
container.getService(MessageBrokerService.class).getContext().addRoutes(this);
}
+ protected void initDynamicModel() {
+ try {
+ Path rootStorageDir = persistenceService.getStorageDir();
+ storageDir = rootStorageDir.resolve(DIRECTORY_NAME);
+
+ if (!Files.exists(storageDir)) {
+ try {
+ Files.createDirectories(storageDir);
+ } catch (IOException e) {
+ LOG.log(Level.SEVERE, "Failed to create asset model storage directory", e);
+ throw new RuntimeException(e);
+ }
+ } else if (!Files.isDirectory(storageDir)) {
+ throw new IllegalStateException("Asset model storage directory is not a directory: " + storageDir);
+ }
+
+ dynamicAssetTypeInfos = loadDescriptors(AssetTypeInfo.class, storageDir)
+ .collect(Collectors.toMap(ati -> ati.getAssetDescriptor().getName(), ati -> ati));
+
+ LOG.fine("Loaded asset type infos from '" + storageDir + "': count = " + dynamicAssetTypeInfos.size());
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE, "Failed to load custom asset types from '" + storageDir + "':" + e.getMessage());
+ }
+ }
+
@Override
public void start(Container container) throws Exception {
@@ -92,6 +277,52 @@ public class AssetModelService extends RouteBuilder implements ContainerService
}
+
+ @Override
+ public boolean useAutoScan() {
+ return false;
+ }
+
+ @Override
+ public AssetDescriptor<?>[] getAssetDescriptors() {
+ if (dynamicAssetTypeInfos == null) {
+ return null;
+ }
+ return dynamicAssetTypeInfos.values().stream().map(AssetTypeInfo::getAssetDescriptor).toArray(AssetDescriptor[]::new);
+ }
+
+ @Override
+ public Map<String, Collection<AttributeDescriptor<?>>> getAttributeDescriptors() {
+ if (dynamicAssetTypeInfos == null) {
+ initDynamicModel();
+ }
+ return dynamicAssetTypeInfos.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, es -> es.getValue().getAttributeDescriptors().values()));
+ }
+
+ @Override
+ public Map<String, Collection<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
+ if (dynamicAssetTypeInfos == null) {
+ initDynamicModel();
+ }
+ return dynamicAssetTypeInfos.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, es -> Arrays.asList(es.getValue().getMetaItemDescriptors())));
+ }
+
+ @Override
+ public Map<String, Collection<ValueDescriptor<?>>> getValueDescriptors() {
+ if (dynamicAssetTypeInfos == null) {
+ initDynamicModel();
+ }
+ return dynamicAssetTypeInfos.entrySet().stream()
+ .collect(Collectors.toMap(Map.Entry::getKey, es -> Arrays.asList(es.getValue().getValueDescriptors())));
+ }
+
+ @Override
+ public boolean isDynamic() {
+ return true;
+ }
+
public AssetTypeInfo[] getAssetInfos(String parentId, String parentType) {
if (!TextUtil.isNullOrEmpty(parentId) && gatewayService.getLocallyRegisteredGatewayId(parentId, null) != null) {
@@ -122,23 +353,49 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return ValueUtil.getAssetDescriptors(parentType);
}
- public ValueDescriptor<?>[] getValueDescriptors(String parentId) {
+ public Map<String, ValueDescriptor<?>> getValueDescriptors(String parentId) {
if (!TextUtil.isNullOrEmpty(parentId) && gatewayService.getLocallyRegisteredGatewayId(parentId, null) != null) {
// TODO: Asset is on a gateway so need to get model info from the gateway instance
- return new ValueDescriptor<?>[0];
+ return null;
}
return ValueUtil.getValueDescriptors();
}
- public MetaItemDescriptor<?>[] getMetaItemDescriptors(String parentId) {
+ public Map<String, MetaItemDescriptor<?>> getMetaItemDescriptors(String parentId) {
if (!TextUtil.isNullOrEmpty(parentId) && gatewayService.getLocallyRegisteredGatewayId(parentId, null) != null) {
// TODO: Asset is on a gateway so need to get model info from the gateway instance
- return new MetaItemDescriptor<?>[0];
+ return null;
}
return ValueUtil.getMetaItemDescriptors();
}
+
+ protected <T> T parse(String jsonString, Class<T> type) throws JsonProcessingException {
+ return JSON.readValue(jsonString, JSON.constructType(type));
+ }
+
+ protected <T> Stream<T> loadDescriptors(Class<T> descriptorClazz, Path descriptorPath) {
+ try {
+ return Files.list(descriptorPath).map(descriptorFile -> {
+ LOG.log(Level.FINE, "Reading descriptor from: " + descriptorFile);
+ String descriptorStr;
+ try {
+ descriptorStr = Files.readString(descriptorFile);
+ if (descriptorStr != null) {
+ return parse(descriptorStr, descriptorClazz);
+ }
+ } catch (JsonProcessingException e) {
+ LOG.log(Level.SEVERE, "Failed to parse descriptor file '" + descriptorFile + "': " + e.getMessage());
+ } catch (IOException e) {
+ LOG.log(Level.SEVERE, "Failed to read descriptor file '" + descriptorFile + "': " + e.getMessage());
+ }
+ return null;
+ }).filter(Objects::nonNull);
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ }
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 91305924f..7d30ec0ff 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -154,8 +154,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
// TODO Better exception handling - dead letter queue?
- if (exception instanceof AssetProcessingException) {
- AssetProcessingException processingException = (AssetProcessingException) exception;
+ if (exception instanceof AssetProcessingException processingException) {
error.append(" - ").append(processingException.getMessage());
error.append(": ").append(event.toString());
logger.warning(error.toString());
@@ -347,41 +346,6 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
throw new AssetProcessingException(ATTRIBUTE_NOT_FOUND);
}
- // For executable attributes, non-sensor sources can set a writable attribute execute status
- if (oldAttribute.getType() == ValueType.EXECUTION_STATUS && source != SENSOR) {
- Optional<AttributeExecuteStatus> status = event.getValue()
- .flatMap(ValueUtil::getString)
- .flatMap(AttributeExecuteStatus::fromString);
-
- if (status.isPresent() && !status.get().isWrite()) {
- throw new AssetProcessingException(INVALID_ATTRIBUTE_EXECUTE_STATUS);
- }
- }
-
- // Type coercion
- Object value = event.getValue().map(eventValue -> {
- Class<?> attributeValueType = oldAttribute.getType().getType();
- return ValueUtil.getValueCoerced(eventValue, attributeValueType).orElseThrow(() -> {
- LOG.info("Failed to coerce attribute event value into the correct value type: realm=" + event.getRealm() + ", attribute=" + event.getAttributeRef() + ", event value type=" + eventValue.getClass() + ", attribute value type=" + attributeValueType);
- return new AssetProcessingException(INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE);
- });
-
- }).orElse(null);
-
- // TODO: Use schema validation
- // Check if attribute is well known and the value is valid
-// AssetModelUtil.getAssetDescriptor(asset.getType()).map(assetDescriptor -> assetDescriptor.get)
-// AssetModelUtil.getAttributeDescriptor(oldAttribute.name).ifPresent(wellKnownAttribute -> {
-// // Check if the value is valid
-// wellKnownAttribute.getValueDescriptor()
-// .getValidator().flatMap(v -> v.apply(event.getValue().orElse(null)))
-// .ifPresent(validationFailure -> {
-// throw new AssetProcessingException(
-// INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE
-// );
-// });
-// });
-
// Either use the timestamp of the event or set event time to processing time or (old event time + 1)
// We need a different timestamp for Attribute.equals() check
long oldEventTime = oldAttribute.getTimestamp().orElse(0L);
@@ -408,8 +372,30 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
}
);
+ // For executable attributes, non-sensor sources can set a writable attribute execute status
+ if (oldAttribute.getType() == ValueType.EXECUTION_STATUS && source != SENSOR) {
+ Optional<AttributeExecuteStatus> status = event.getValue()
+ .flatMap(ValueUtil::getString)
+ .flatMap(AttributeExecuteStatus::fromString);
+
+ // TODO: Make this mechanism more generic with an interface
+ if (status.isPresent() && !status.get().isWrite()) {
+ throw new AssetProcessingException(INVALID_ATTRIBUTE_EXECUTE_STATUS);
+ }
+ }
+
+ // Type coercion
+ Object value = event.getValue().map(eventValue -> {
+ Class<?> attributeValueType = oldAttribute.getTypeClass();
+ return ValueUtil.getValueCoerced(eventValue, attributeValueType).orElseThrow(() -> {
+ LOG.info("Failed to coerce attribute event value into the correct value type: realm=" + event.getRealm() + ", attribute=" + event.getAttributeRef() + ", event value type=" + eventValue.getClass() + ", attribute value type=" + attributeValueType);
+ return new AssetProcessingException(INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE);
+ });
+
+ }).orElse(null);
+
// Create a copy of the attribute and set the new value and timestamp
- Attribute updatedAttribute = ValueUtil.clone(oldAttribute);
+ Attribute updatedAttribute = oldAttribute.shallowClone();
updatedAttribute.setValue(value, eventTime);
// Need to record time here otherwise an infinite loop generated inside one of the processors means the timestamp
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index 375d7610d..1c4d95ab0 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -20,6 +20,16 @@
package org.openremote.manager.asset;
import com.fasterxml.jackson.databind.node.NullNode;
+import jakarta.persistence.OptimisticLockException;
+import jakarta.validation.ConstraintViolationException;
+import jakarta.ws.rs.BadRequestException;
+import jakarta.ws.rs.ForbiddenException;
+import jakarta.ws.rs.NotAuthorizedException;
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.HttpHeaders;
+import jakarta.ws.rs.core.MediaType;
+import jakarta.ws.rs.core.Response;
+import org.jboss.resteasy.plugins.validation.ResteasyViolationExceptionImpl;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.event.ClientEventService;
@@ -37,15 +47,6 @@ import org.openremote.model.security.ClientRole;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
-import jakarta.persistence.OptimisticLockException;
-import jakarta.validation.ConstraintViolationException;
-import jakarta.ws.rs.BadRequestException;
-import jakarta.ws.rs.ForbiddenException;
-import jakarta.ws.rs.NotAuthorizedException;
-import jakarta.ws.rs.WebApplicationException;
-import jakarta.ws.rs.core.HttpHeaders;
-import jakarta.ws.rs.core.MediaType;
-import jakarta.ws.rs.core.Response;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -53,7 +54,6 @@ import java.util.stream.IntStream;
import static jakarta.ws.rs.core.Response.Status.*;
import static org.openremote.manager.asset.AssetProcessingService.ATTRIBUTE_EVENT_QUEUE;
-import static org.openremote.manager.event.ClientEventService.CLIENT_INBOUND_QUEUE;
import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;
import static org.openremote.model.query.AssetQuery.Access;
import static org.openremote.model.value.MetaItemType.*;
@@ -282,7 +282,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
@Override
- public void update(RequestParams requestParams, String assetId, Asset<?> asset) {
+ public Asset<?> update(RequestParams requestParams, String assetId, Asset<?> asset) {
LOG.fine("Updating asset: assetID=" + assetId);
@@ -336,7 +336,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
String updatedAttributeName = updatedAttribute.getName();
// Check if attribute is present on the asset in storage
- Optional<Attribute<?>> serverAttribute = storageAsset.getAttribute(updatedAttributeName);
+ Optional<Attribute<Object>> serverAttribute = storageAsset.getAttribute(updatedAttributeName);
if (serverAttribute.isPresent()) {
Attribute<?> existingAttribute = serverAttribute.get();
@@ -403,12 +403,12 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
// });
// Store the result
- assetStorageService.merge(storageAsset, isRestrictedUser ? getUsername() : null);
+ return assetStorageService.merge(storageAsset, isRestrictedUser ? getUsername() : null);
} catch (IllegalStateException ex) {
throw new WebApplicationException(ex, FORBIDDEN);
} catch (ConstraintViolationException ex) {
- throw new WebApplicationException(ex, BAD_REQUEST);
+ throw new ResteasyViolationExceptionImpl(ex.getConstraintViolations(), requestParams.headers.getAcceptableMediaTypes());
} catch (OptimisticLockException opEx) {
throw new WebApplicationException("Refresh the asset from the server and try to update the changes again", opEx, CONFLICT);
}
@@ -434,25 +434,13 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
AttributeWriteResult result = doAttributeWrite(event);
if (result.getFailure() != null) {
- switch (result.getFailure()) {
- case ILLEGAL_SOURCE:
- case INSUFFICIENT_ACCESS:
- case INVALID_REALM:
- status = FORBIDDEN;
- break;
- case ASSET_NOT_FOUND:
- case ATTRIBUTE_NOT_FOUND:
- status = NOT_FOUND;
- break;
- case INVALID_AGENT_LINK:
- case ILLEGAL_AGENT_UPDATE:
- case INVALID_ATTRIBUTE_EXECUTE_STATUS:
- case INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE:
- status = NOT_ACCEPTABLE;
- break;
- default:
- status = BAD_REQUEST;
- }
+ status = switch (result.getFailure()) {
+ case ILLEGAL_SOURCE, INSUFFICIENT_ACCESS, INVALID_REALM -> FORBIDDEN;
+ case ASSET_NOT_FOUND, ATTRIBUTE_NOT_FOUND -> NOT_FOUND;
+ case INVALID_AGENT_LINK, ILLEGAL_AGENT_UPDATE, INVALID_ATTRIBUTE_EXECUTE_STATUS, INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE ->
+ NOT_ACCEPTABLE;
+ default -> BAD_REQUEST;
+ };
}
return Response.status(status).entity(result).type(MediaType.APPLICATION_JSON_TYPE).build();
@@ -484,7 +472,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// If there was no realm provided (create was called by regular user in manager UI), use the auth realm
- if (asset.getRealm() == null || asset.getRealm().length() == 0) {
+ if (asset.getRealm() == null || asset.getRealm().isEmpty()) {
asset.setRealm(getAuthenticatedRealm().getName());
} else if (!isRealmActiveAndAccessible(asset.getRealm())) {
LOG.fine("Forbidden access for user '" + getUsername() + "', can't create: " + asset);
@@ -498,39 +486,10 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
newAsset.setId(asset.getId());
}
- // TODO: Decide on the below - clients should ensure the asset conforms to the asset descriptor and we shouldn't do any 'magic' here
-// AssetModelUtil.getAssetDescriptor(asset.getType()).ifPresent(assetDescriptor -> {
-//
-// // Add meta items to well known attributes if not present
-// newAsset.getAttributes().stream().forEach(assetAttribute -> {
-// if (assetDescriptor.getAttributeDescriptors() != null) {
-// Arrays.stream(assetDescriptor.getAttributeDescriptors())
-// .filter(attrDescriptor -> attrDescriptor.getAttributeName().equals(assetAttribute.getName()))
-// .findFirst()
-// .ifPresent(defaultAttribute -> {
-// if (defaultAttribute.getMetaItemDescriptors() != null) {
-// assetAttribute.addMeta(
-// Arrays.stream(defaultAttribute.getMetaItemDescriptors())
-// .filter(metaItemDescriptor -> !assetAttribute.hasMetaItem(metaItemDescriptor))
-// .map(MetaItem::new)
-// .toArray(MetaItem[]::new)
-// );
-// }
-// });
-// }
-// });
-//
-// // Add attributes for this well known asset if not present
-// if (assetDescriptor.getAttributeDescriptors() != null) {
-// newAsset.addAttributes(
-// Arrays.stream(assetDescriptor.getAttributeDescriptors()).filter(attributeDescriptor ->
-// !newAsset.hasAttribute(attributeDescriptor.getAttributeName())).map(Attribute::new).toArray(Attribute[]::new)
-// );
-// }
-// });
-
return assetStorageService.merge(newAsset);
+ } catch (ConstraintViolationException ex) {
+ throw new ResteasyViolationExceptionImpl(ex.getConstraintViolations(), requestParams.headers.getAcceptableMediaTypes());
} catch (IllegalStateException ex) {
throw new WebApplicationException(ex, BAD_REQUEST);
}
@@ -625,7 +584,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
List<Asset<?>> assets = this.assetStorageService.findAll(query);
LOG.fine("Updating parent for assets: count=" + assets.size() + ", newParentID=" + parentId);
- for (Asset asset : assets) {
+ for (Asset<?> asset : assets) {
asset.setParentId(parentId);
LOG.fine("Updating asset parent: assetID=" + asset.getId() + ", newParentID=" + parentId);
assetStorageService.merge(asset);
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index ec2cecc8f..7eac0f420 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -19,10 +19,16 @@
*/
package org.openremote.manager.asset;
-import com.vladmihalcea.hibernate.type.array.StringArrayType;
+import jakarta.persistence.EntityManager;
+import jakarta.persistence.NoResultException;
+import jakarta.persistence.Query;
+import jakarta.persistence.TypedQuery;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.ConstraintViolationException;
import org.apache.camel.builder.RouteBuilder;
import org.hibernate.Session;
import org.hibernate.jdbc.AbstractReturningWork;
+import org.hibernate.jpa.AvailableHints;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.persistence.PersistenceService;
import org.openremote.container.security.AuthContext;
@@ -39,6 +45,7 @@ import org.openremote.model.ContainerService;
import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.*;
import org.openremote.model.asset.impl.GroupAsset;
+import org.openremote.model.asset.impl.ThingAsset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeMap;
@@ -54,15 +61,10 @@ import org.openremote.model.security.User;
import org.openremote.model.util.Pair;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
+import org.openremote.model.validation.AssetStateStore;
import org.openremote.model.value.MetaItemType;
import org.postgresql.util.PGobject;
-import jakarta.persistence.EntityManager;
-import jakarta.persistence.NoResultException;
-import jakarta.persistence.Query;
-import jakarta.persistence.TypedQuery;
-import jakarta.validation.ConstraintViolation;
-import jakarta.validation.ConstraintViolationException;
import java.sql.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -659,13 +661,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
throw new IllegalStateException(msg);
}
- // Do standard JSR-380 validation on the asset (includes custom validation)
- Set<ConstraintViolation<Asset<?>>> validationFailures = ValueUtil.validate(asset, Asset.AssetSave.class);
+ // Do standard JSR-380 validation on the asset (includes custom validation using descriptors and constraints)
+ Set<ConstraintViolation<Asset<?>>> validationFailures = ValueUtil.validate(asset);
- if (validationFailures.size() > 0) {
+ if (!validationFailures.isEmpty()) {
String msg = "Asset merge failed as asset has failed constraint validation: asset=" + asset;
ConstraintViolationException ex = new ConstraintViolationException(validationFailures);
- LOG.log(Level.WARNING, msg + ", exception=" + ex.getMessage(), ex);
+ LOG.log(Level.WARNING, msg + ", exception=" + ex.getMessage());
throw ex;
}
@@ -825,6 +827,16 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
createUserAssetLinks(em, Collections.singletonList(new UserAssetLink(user.getRealm(), user.getId(), updatedAsset.getId())));
}
+ if (existingAsset == null && updatedAsset instanceof ThingAsset && !ThingAsset.DESCRIPTOR.getName().equals(updatedAsset.getType())) {
+ // When an asset is first saved then any custom type is not persisted as JPA will set it to ThingAsset so we need to override
+ // We don't need to do this when updating an existing asset as JPA doesn't overwrite the type - if this changes in future it
+ // should be detected by tests
+ em.createNativeQuery("update ASSET set type = ? where id = ?;")
+ .setParameter(1, updatedAsset.getType())
+ .setParameter(2, updatedAsset.getId())
+ .executeUpdate();
+ }
+
return updatedAsset;
});
}
@@ -1248,6 +1260,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
@SuppressWarnings("unchecked")
protected List<Asset<?>> findAll(EntityManager em, AssetQuery query) {
+
long startMillis = System.currentTimeMillis();
if (query.access == null)
@@ -1309,8 +1322,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// return asset;
// });
- org.hibernate.query.Query<Object[]> jpql = em.createNativeQuery(querySql.querySql, Asset.class).unwrap(org.hibernate.query.Query.class);
-
+ org.hibernate.query.Query<Object[]> jpql = em.createNativeQuery(querySql.querySql, Asset.class).unwrap(org.hibernate.query.Query.class)
+ .setHint(AvailableHints.HINT_READ_ONLY, true); // Make query readonly so no dirty checks are performed
querySql.apply(em, jpql);
List<Asset<?>> assets = (List<Asset<?>>)(Object)jpql.getResultList();
@@ -1329,59 +1342,46 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
* This does a low level JDBC update so hibernate event interceptor doesn't get called and we 'manually'
* generate the {@link AttributeEvent}
*/
- protected boolean updateAttributeValue(EntityManager em, Asset<?> asset, Attribute<?> attribute) {
+ @SuppressWarnings("unchecked")
+ protected boolean updateAttributeValue(EntityManager em, Asset<?> asset, Attribute<?> attribute) throws ConstraintViolationException {
+
+ long timestamp = attribute.getTimestamp().orElseGet(timerService::getCurrentTimeMillis);
+
+ // TODO: Reuse AssetState and change validator over to that class
+ // Do standard JSR-380 validation on the new value (needs attribute descriptor to do this)
+ Set<ConstraintViolation<AssetStateStore>> validationFailures = ValueUtil.validate(new AssetStateStore(asset.getType(), attribute));
+
+ if (!validationFailures.isEmpty()) {
+ String msg = "Attribute update failed as value failed constraint validation: attribute=" + attribute;
+ ConstraintViolationException ex = new ConstraintViolationException(validationFailures);
+ LOG.log(Level.WARNING, msg + ", exception=" + ex.getMessage());
+ throw ex;
+ }
try {
+ PGobject valueTimestampJSON = new PGobject();
+ valueTimestampJSON.setType("jsonb");
+ valueTimestampJSON.setValue("{\"value\":" + ValueUtil.asJSON(attribute.getValue().orElse(null)).orElse(ValueUtil.NULL_LITERAL) + ",\"timestamp\":" + timestamp + "}");
- // Detach the asset from the em so we can manually update the attribute
- em.detach(asset);
- String attributeName = attribute.getName();
- Object value = attribute.getValue();
- long timestamp = attribute.getTimestamp().orElseGet(timerService::getCurrentTimeMillis);
-
- boolean success = em.unwrap(Session.class).doReturningWork(connection -> {
- String jpql = "update Asset" +
- " set attributes = jsonb_set(jsonb_set(attributes, ?, ?, true), ?, ?, true)" +
- " where id = ? and attributes -> ? is not null";
-
- try (PreparedStatement statement = connection.prepareStatement(jpql)) {
- Array attributeValuePath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "value"}
- );
- statement.setArray(1, attributeValuePath);
-
- PGobject pgJsonValue = new PGobject();
- pgJsonValue.setType("jsonb");
- // Careful, do not set Java null here! It will erase your whole SQL column!
- pgJsonValue.setValue(ValueUtil.asJSON(value).orElse(ValueUtil.NULL_LITERAL));
- statement.setObject(2, pgJsonValue);
-
- // Bind the value timestamp
- Array attributeValueTimestampPath = connection.createArrayOf(
- "text",
- new String[]{attributeName, "timestamp"}
- );
- statement.setArray(3, attributeValueTimestampPath);
- PGobject pgJsonValueTimestamp = new PGobject();
- pgJsonValueTimestamp.setType("jsonb");
- pgJsonValueTimestamp.setValue(Long.toString(timestamp));
- statement.setObject(4, pgJsonValueTimestamp);
-
- // Bind asset ID and attribute name
- statement.setString(5, asset.getId());
- statement.setString(6, attributeName);
-
- int updatedRows = statement.executeUpdate();
- if (LOG.isLoggable(Level.FINEST)) {
- LOG.finest("Stored asset '" + asset.getId()
- + "' attribute '" + attributeName
- + "' (affected rows: " + updatedRows + ") value: "
- + (value != null ? ValueUtil.asJSON(value).orElse("null") : "null"));
- }
- return updatedRows == 1;
+ // TODO: Use jsonb type directly to optimise over wire data (couldn't get this to work even after seeing https://stackoverflow.com/questions/53847917/postgresql-throws-column-is-of-type-jsonb-but-expression-is-of-type-bytea-with)
+ Query query = em.createNativeQuery("UPDATE asset SET attributes[?] = attributes[?] || ?\\:\\:jsonb where id = ?")
+ .setParameter(1, attribute.getName())
+ .setParameter(2, attribute.getName())
+ .setParameter(3, "{\"value\":" + ValueUtil.asJSON(attribute.getValue().orElse(null)).orElse(ValueUtil.NULL_LITERAL) + ",\"timestamp\":" + timestamp + "}")
+ .setParameter(4, asset.getId());
+
+ int affectedRows = query.executeUpdate();
+ boolean success = affectedRows == 1;
+
+ if (success) {
+ if (LOG.isLoggable(Level.FINEST)) {
+ LOG.finest("Updated attribute value assetID=" + asset.getId() + ", attributeName=" + attribute.getName() + ", timestamp=" + timestamp);
}
- });
+ } else {
+ if (LOG.isLoggable(Level.FINE)) {
+ LOG.fine("Failed to update attribute value assetID=" + asset.getId() + ", attributeName=" + attribute.getName() + ", timestamp=" + timestamp);
+ }
+ }
if (success) {
publishAttributeEvent(asset, attribute);
@@ -1588,7 +1588,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
.append("?")
.append(pos)
.append(")");
- binders.add((em, st) -> st.setParameter(pos, select.attributes, StringArrayType.INSTANCE));
+ binders.add((em, st) -> st.setParameter(pos, select.attributes));
}
if (query.access != PRIVATE) {
@@ -1670,7 +1670,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" and A.ID = ANY(?")
.append(pos)
.append(")");
- binders.add((em, st) -> st.setParameter(pos, query.ids, StringArrayType.INSTANCE));
+ binders.add((em, st) -> st.setParameter(pos, query.ids));
}
if (level == 1 && query.names != null) {
@@ -1745,7 +1745,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" and UA.USER_ID = ANY(?")
.append(pos)
.append(")");
- binders.add((em, st) -> st.setParameter(pos, query.userIds, StringArrayType.INSTANCE));
+ binders.add((em, st) -> st.setParameter(pos, query.userIds));
}
if (level == 1 && query.access == Access.PUBLIC) {
@@ -1758,7 +1758,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" and A.TYPE = ANY(?")
.append(pos)
.append(")");
- binders.add((em, st) -> st.setParameter(pos, resolvedTypes, StringArrayType.INSTANCE));
+ binders.add((em, st) -> st.setParameter(pos, resolvedTypes));
}
if (query.attributes != null) {
@@ -1920,7 +1920,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
valuePathInserter = (sb, b) -> {
final int pos = binders.size() + 1;
sb.append("(").append(jsonObjName).append(".VALUE ").append(operator).append(" ?").append(pos).append(")");
- binders.add((em, st) -> st.setParameter(pos, paths.toArray(new String[0]), StringArrayType.INSTANCE));
+ binders.add((em, st) -> st.setParameter(pos, paths.toArray(new String[0])));
};
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java
index c02151db4..4ab159b3a 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java
@@ -167,11 +167,11 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro
if (value[0] != null) {
// Do basic value conversion
- if (!attr.getType().getType().isAssignableFrom(value[0].getClass())) {
- Object val = ValueUtil.convert(value[0], attr.getType().getType());
+ if (!attr.getTypeClass().isAssignableFrom(value[0].getClass())) {
+ Object val = ValueUtil.convert(value[0], attr.getTypeClass());
if (val == null) {
- LOG.warning("Failed to convert value: " + value[0].getClass() + " -> " + attr.getType().getType());
+ LOG.warning("Failed to convert value: " + value[0].getClass() + " -> " + attr.getTypeClass());
LOG.warning("Cannot send linked attribute update");
return;
}
@@ -234,7 +234,7 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro
AttributeLink.ConverterType converter,
AttributeRef linkedAttributeRef) throws AssetProcessingException {
switch (converter) {
- case TOGGLE:
+ case TOGGLE -> {
// Look up current value of the linked attribute within the same database session
try {
Attribute<?> currentAttribute = getAttribute(em, assetStorageService, asset.getRealm(), linkedAttributeRef).orElseThrow(
@@ -243,19 +243,19 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro
"cannot toggle value as attribute cannot be found: " + linkedAttributeRef
)
);
- if (!ValueUtil.isBoolean(currentAttribute.getType().getType())) {
+ if (!ValueUtil.isBoolean(currentAttribute.getTypeClass())) {
throw new AssetProcessingException(
AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,
"cannot toggle value as attribute is not of type BOOLEAN: " + linkedAttributeRef
);
}
- return new Pair<>(false, !(Boolean)currentAttribute.getValueAs(Boolean.class).orElse(false));
+ return new Pair<>(false, !(Boolean) currentAttribute.getValue(Boolean.class).orElse(false));
} catch (NoSuchElementException e) {
LOG.fine("The attribute doesn't exist so ignoring toggle value request: " + linkedAttributeRef);
return new Pair<>(true, null);
}
- case INCREMENT:
- case DECREMENT:
+ }
+ case INCREMENT, DECREMENT -> {
// Look up current value of the linked attribute within the same database session
try {
Attribute<?> currentAttribute = getAttribute(em, assetStorageService, asset.getRealm(), linkedAttributeRef).orElseThrow(
@@ -264,7 +264,7 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro
"cannot toggle value as attribute cannot be found: " + linkedAttributeRef
)
);
- if (!ValueUtil.isNumber(currentAttribute.getType().getType())) {
+ if (!ValueUtil.isNumber(currentAttribute.getTypeClass())) {
throw new AssetProcessingException(
AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,
"cannot increment/decrement value as attribute is not of type NUMBER: " + linkedAttributeRef
@@ -276,11 +276,11 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro
LOG.fine("The attribute doesn't exist so ignoring increment/decrement value request: " + linkedAttributeRef);
return new Pair<>(true, null);
}
- default:
- throw new AssetProcessingException(
- AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,
- "converter is not supported: " + converter
- );
+ }
+ default -> throw new AssetProcessingException(
+ AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,
+ "converter is not supported: " + converter
+ );
}
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/ForecastService.java b/manager/src/main/java/org/openremote/manager/asset/ForecastService.java
index 386d75475..bcb2e704c 100644
--- a/manager/src/main/java/org/openremote/manager/asset/ForecastService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/ForecastService.java
@@ -36,6 +36,7 @@ import org.openremote.model.attribute.AttributeMap;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.datapoint.AssetDatapoint;
import org.openremote.model.datapoint.AssetPredictedDatapoint;
+import org.openremote.model.datapoint.Datapoint;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.NameValuePredicate;
@@ -210,7 +211,7 @@ public class ForecastService extends RouteBuilder implements ContainerService {
.count() == 0;
})
.map(attr -> new ForecastAttribute(asset, attr))
- .collect(Collectors.toList())
+ .toList()
);
forecastTaskManager.delete(attributesToDelete);
@@ -531,12 +532,12 @@ public class ForecastService extends RouteBuilder implements ContainerService {
// Attr(t) = Attr(t-p) * a + Attr(t-2p) * (1 - a)
List<Object> values = datapoints
.stream()
- .map(dp -> dp.getValue())
+ .map(Datapoint::getValue)
.collect(Collectors.toList());
double R = datapoints.size();
double a = 2 / (R + 1);
- Class<?> clazz = attribute.getType().getType();
+ Class<?> clazz = attribute.getTypeClass();
if (Long.class == clazz || Integer.class == clazz || Short.class == clazz || Byte.class == clazz ||
Double.class == clazz || Float.class == clazz) {
if (values.size() == 1) {
@@ -566,7 +567,7 @@ public class ForecastService extends RouteBuilder implements ContainerService {
}
}
return value;
- } else if (attribute.getType().getType() == BigDecimal.class) {
+ } else if (attribute.getTypeClass() == BigDecimal.class) {
if (values.size() == 1) {
values.add(0, BigDecimal.valueOf(0));
}
@@ -576,7 +577,7 @@ public class ForecastService extends RouteBuilder implements ContainerService {
.reduce((olderValue, oldValue) ->
((BigDecimal)oldValue).multiply(BigDecimal.valueOf(a)).add(((BigDecimal)olderValue).multiply(BigDecimal.valueOf(1 - a)))
);
- } else if (attribute.getType().getType() == BigInteger.class) {
+ } else if (attribute.getTypeClass() == BigInteger.class) {
if (values.size() == 1) {
values.add(0, BigInteger.valueOf(0));
}
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
index a97c1a1d6..834aaf69a 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AbstractDatapointService.java
@@ -193,7 +193,7 @@ public abstract class AbstractDatapointService<T extends Datapoint> implements C
@Override
public ValueDatapoint<?>[] execute(Connection connection) throws SQLException {
- Class<?> attributeType = attribute.getType().getType();
+ Class<?> attributeType = attribute.getTypeClass();
boolean isNumber = Number.class.isAssignableFrom(attributeType);
boolean isBoolean = Boolean.class.isAssignableFrom(attributeType);
@@ -206,7 +206,7 @@ public abstract class AbstractDatapointService<T extends Datapoint> implements C
}
try (PreparedStatement st = connection.prepareStatement(query)) {
- if(parameters.size() > 0) {
+ if(!parameters.isEmpty()) {
for(Map.Entry<Integer, Object> param : parameters.entrySet()) {
if(param.getValue() instanceof String) {
st.setString(param.getKey(), param.getValue().toString());
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointHealthStatusProvider.java
index 46ee2536b..f69bd5599 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointHealthStatusProvider.java
@@ -19,11 +19,11 @@
*/
package org.openremote.manager.datapoint;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
+
+import java.util.Map;
public class AssetDatapointHealthStatusProvider implements HealthStatusProvider {
@@ -57,8 +57,6 @@ public class AssetDatapointHealthStatusProvider implements HealthStatusProvider
@Override
public Object getHealthStatus() {
- ObjectNode value = ValueUtil.JSON.createObjectNode();
- value.put("totalDatapoints", assetDatapointService.getDatapointsCount());
- return value;
+ return Map.of("totalDatapoints", assetDatapointService.getDatapointsCount());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointHealthStatusProvider.java
index 9b244ca91..9f4a5a104 100644
--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointHealthStatusProvider.java
@@ -19,21 +19,15 @@
*/
package org.openremote.manager.datapoint;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
+
+import java.util.Map;
public class AssetPredictedDatapointHealthStatusProvider implements HealthStatusProvider {
public static final String NAME = "predicted";
protected AssetPredictedDatapointService assetPredictedDatapointService;
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class);
@@ -56,8 +50,6 @@ public class AssetPredictedDatapointHealthStatusProvider implements HealthStatus
@Override
public Object getHealthStatus() {
- ObjectNode value = ValueUtil.JSON.createObjectNode();
- value.put("totalDatapoints", assetPredictedDatapointService.getDatapointsCount());
- return value;
+ return Map.of("totalDatapoints", assetPredictedDatapointService.getDatapointsCount());
}
}
diff --git a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java
index 9add97824..cd6485b9f 100644
--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java
+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java
@@ -132,7 +132,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Container
.stream()
.map(asset -> (EnergyOptimisationAsset) asset)
.filter(optimisationAsset -> !optimisationAsset.isOptimisationDisabled().orElse(false))
- .collect(Collectors.toList());
+ .toList();
LOG.fine("Found enabled optimisation asset count = " + energyOptimisationAssets.size());
diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
index 29ae7893e..8cc768a53 100644
--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java
@@ -194,7 +194,7 @@ public class ClientEventService extends RouteBuilder implements ContainerService
messageBrokerService.getContext().addRoutes(this);
// Add pending internal subscriptions
- if (!pendingInternalSubscriptions.isEmpty()) {
+ if (pendingInternalSubscriptions != null && !pendingInternalSubscriptions.isEmpty()) {
pendingInternalSubscriptions.forEach(subscription ->
eventSubscriptions.createOrUpdate(INTERNAL_SESSION_KEY, subscription));
}
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
index e12e95980..a5fb513d9 100644
--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java
@@ -61,7 +61,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static org.apache.camel.builder.PredicateBuilder.and;
import static org.apache.camel.builder.PredicateBuilder.or;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
@@ -331,7 +330,7 @@ public class GatewayService extends RouteBuilder implements ContainerService, As
// This is a change to a locally registered gateway
if (GatewayAsset.DISABLED.getName().equals(attribute.getName())) {
- boolean disabled = attribute.getValueAs(Boolean.class).orElse(false);
+ boolean disabled = attribute.getValue(Boolean.class).orElse(false);
boolean isAlreadyDisabled = gatewayAsset.getDisabled().orElse(false);
gatewayAsset.setDisabled(disabled); // Ensure we update state
@@ -345,7 +344,7 @@ public class GatewayService extends RouteBuilder implements ContainerService, As
}
if (GatewayAsset.CLIENT_SECRET.getName().equals(attribute.getName())) {
- String newSecret = attribute.getValueAs(String.class).orElse(null);
+ String newSecret = attribute.getValue(String.class).orElse(null);
if (!TextUtil.isNullOrEmpty(newSecret)) {
LOG.fine("Gateway client secret attribute updated so updating gateway service user secret to match: (Gateway ID=" + asset.getId() + ")");
User gatewayServiceUser = identityProvider.getUserByUsername(asset.getRealm(), User.SERVICE_ACCOUNT_PREFIX + ((GatewayAsset) asset).getClientId().orElse(""));
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java b/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
index 7ce059a29..0b8024ef3 100644
--- a/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
+++ b/manager/src/main/java/org/openremote/manager/mqtt/ConnectionMonitorHandler.java
@@ -43,6 +43,7 @@ import org.openremote.model.query.filter.NameValuePredicate;
import org.openremote.model.security.User;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.Pair;
+import org.openremote.model.value.ValueHolder;
import org.openremote.model.value.ValueType;
import java.util.*;
@@ -53,8 +54,6 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import static java.util.stream.Collectors.mapping;
-import static java.util.stream.Collectors.toList;
import static org.openremote.container.persistence.PersistenceService.PERSISTENCE_TOPIC;
import static org.openremote.container.persistence.PersistenceService.isPersistenceEventForEntityType;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
@@ -106,12 +105,9 @@ public class ConnectionMonitorHandler extends MQTTHandler {
if (oldAttributes != null) {
oldAttributes.stream().filter(ConnectionMonitorHandler::attributeMatches)
- .forEach(attr -> {
- String userID = attr.getMetaValueOrDefault(USER_CONNECTED);
- if (userID != null) {
- removeSessionAttribute(userID, new AttributeRef(asset.getId(), attr.getName()));
- }
- });
+ .forEach(attr -> attr.getMetaItem(USER_CONNECTED)
+ .flatMap(ValueHolder::getValue)
+ .ifPresent(userID -> removeSessionAttribute(userID, new AttributeRef(asset.getId(), attr.getName()))));
}
if (newAttributes != null) {
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index 664ca455d..c421b5f83 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -49,6 +49,7 @@ import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
import java.io.InputStream;
+import java.lang.reflect.Array;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
@@ -56,7 +57,6 @@ import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-import java.util.stream.StreamSupport;
import static org.openremote.manager.gateway.GatewayService.isNotForGateway;
import static org.openremote.model.notification.PushNotificationMessage.TargetType.*;
@@ -384,8 +384,17 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
return consoleAsset.getConsoleProviders().flatMap(consoleProviders ->
Optional.ofNullable(consoleProviders.get(PushNotificationMessage.TYPE))
.map(ConsoleProvider::getData)
- .map(objectValue -> objectValue.withArray("topics"))
- .map(arrayValue -> StreamSupport.stream(arrayValue.spliterator(), false).anyMatch(node -> node.asText("").equals(topic))))
+ .map(data -> data.get("topics"))
+ .map(arrayValue -> {
+ int length = Array.getLength(arrayValue);
+ for (int i = 0; i < length; i ++) {
+ Object arrayElement = Array.get(arrayValue, i);
+ if (arrayElement instanceof String && arrayElement.equals(topic)) {
+ return true;
+ }
+ }
+ return false;
+ }))
.orElse(false);
}
@@ -483,7 +492,10 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
return asset.getConsoleProviders().flatMap(consoleProviders ->
Optional.ofNullable(consoleProviders.get(PushNotificationMessage.TYPE))
.map(ConsoleProvider::getData)
- .map(data -> data.get("token") != null && !data.get("token").isNull() && !data.get("token").asText().isEmpty() ? data.get("token").asText() : null));
+ .map(data -> {
+ Object token = data.get("token");
+ return token instanceof String ? (String)token : null;
+ }));
}
protected void processConsoleAssetChange(ConsoleAsset asset, PersistenceEvent<ConsoleAsset> persistenceEvent) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
index f822bd1fd..1443a1f8b 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -36,7 +36,6 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
-import java.util.stream.Collectors;
/**
* Test an {@link AssetState} with a {@link AssetQuery}.
diff --git a/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java
index 000bc4569..65597f7fa 100644
--- a/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/FlowRulesBuilder.java
@@ -18,9 +18,10 @@ import java.util.*;
import java.util.logging.Logger;
public class FlowRulesBuilder {
+
protected final Logger LOG;
protected final AssetStorageService assetStorageService;
- protected final Map<String, Long> triggerMap = new LinkedHashMap<>();
+ protected final Map<String, Long> triggerMap = new HashMap<>();
protected final List<NodeCollection> nodeCollections = new ArrayList<>();
protected final Assets assetsFacade;
protected final Users usersFacade;
@@ -28,7 +29,7 @@ public class FlowRulesBuilder {
protected final HistoricDatapoints historicDatapointsFacade;
protected final PredictedDatapoints predictedDatapointsFacade;
protected final TimerService timerService;
-
+
public FlowRulesBuilder(
Logger logger,
TimerService timerService,
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 4781c6a03..550c7dcf5 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -19,9 +19,6 @@
*/
package org.openremote.manager.rules;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.ws.rs.core.MediaType;
import org.openremote.container.timer.TimerService;
import org.openremote.manager.asset.AssetStorageService;
@@ -48,6 +45,7 @@ import org.quartz.CronExpression;
import org.shredzone.commons.suncalc.SunTimes;
import java.time.ZonedDateTime;
+import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
@@ -162,7 +160,9 @@ public class JsonRulesBuilder extends RulesBuilder {
// If occurrence is before requested time then advance the sun calculator to either reset occurrence or 5 mins before requested time (whichever is later)
if (nextMillis < time) {
- ZonedDateTime resetOccurrence = useRiseTime ? sunTimes.get().getSet() : sunTimes.get().getRise();
+ // Move to the next day
+ ZonedDateTime resetOccurrence = sunTimes.get().getSet().isBefore(sunTimes.get().getRise()) ? sunTimes.get().getSet() : sunTimes.get().getRise();
+ resetOccurrence = resetOccurrence.truncatedTo(ChronoUnit.DAYS).plusDays(1);
sunTimes.set(sunCalculator.on(new Date(Math.max(resetOccurrence.toInstant().toEpochMilli(), time - 300000))).execute());
}
@@ -213,15 +213,13 @@ public class JsonRulesBuilder extends RulesBuilder {
} else {
// Replace or remove asset state as required
switch (event.cause) {
- case UPDATE:
+ case UPDATE -> {
// Only insert if fact was already in there (i.e. it matches the asset type constraints)
if (unfilteredAssetStates.remove(event.assetState)) {
unfilteredAssetStates.add(event.assetState);
}
- break;
- case DELETE:
- unfilteredAssetStates.remove(event.assetState);
- break;
+ }
+ case DELETE -> unfilteredAssetStates.remove(event.assetState);
}
}
@@ -306,7 +304,7 @@ public class JsonRulesBuilder extends RulesBuilder {
.filter(matchedAssetState -> Objects.equals(previousAssetState, matchedAssetState))
.findFirst();
- boolean noLongerMatches = !matched.isPresent();
+ boolean noLongerMatches = matched.isEmpty();
if (!noLongerMatches) {
noLongerMatches = matched.map(matchedAssetState -> {
@@ -349,8 +347,8 @@ public class JsonRulesBuilder extends RulesBuilder {
// Filter out unmatched asset ids that are in the matched list
unmatchedAssetIds = unmatchedAssetStateStream
- .filter(assetState -> !matchedAssetIds.contains(assetState.getId()))
.map(AssetState::getId)
+ .filter(id -> !matchedAssetIds.contains(id))
.collect(Collectors.toList());
}
@@ -620,7 +618,7 @@ public class JsonRulesBuilder extends RulesBuilder {
add().name(rule.name)
.description(rule.description)
.priority(rule.priority)
- .when(condition::evaluate)
+ .when(condition)
.then(action);
return this;
@@ -628,7 +626,7 @@ public class JsonRulesBuilder extends RulesBuilder {
protected void addRuleConditionStates(LogicGroup<RuleCondition> ruleConditionGroup, boolean trackUnmatched, AtomicInteger index, Map<String, RuleConditionState> triggerStateMap) throws Exception {
if (ruleConditionGroup != null) {
- if (ruleConditionGroup.getItems().size() > 0) {
+ if (!ruleConditionGroup.getItems().isEmpty()) {
for (RuleCondition ruleCondition : ruleConditionGroup.getItems()) {
if (TextUtil.isNullOrEmpty(ruleCondition.tag)) {
ruleCondition.tag = index.toString();
@@ -638,7 +636,7 @@ public class JsonRulesBuilder extends RulesBuilder {
index.incrementAndGet();
}
}
- if (ruleConditionGroup.groups != null && ruleConditionGroup.groups.size() > 0) {
+ if (ruleConditionGroup.groups != null && !ruleConditionGroup.groups.isEmpty()) {
for (LogicGroup<RuleCondition> childRuleTriggerCondition : ruleConditionGroup.groups) {
addRuleConditionStates(childRuleTriggerCondition, trackUnmatched, index, triggerStateMap);
}
@@ -763,6 +761,7 @@ public class JsonRulesBuilder extends RulesBuilder {
.collect(Collectors.toList());
}
+ @SuppressWarnings({"rawtypes", "unchecked"})
protected RuleActionExecution buildRuleActionExecution(JsonRule rule, RuleAction ruleAction, String actionsName, int index, boolean useUnmatched, RulesFacts facts, RuleState ruleState, Assets assetsFacade, Users usersFacade, Notifications notificationsFacade, Webhooks webhooksFacade, PredictedDatapoints predictedDatapointsFacade) {
if (ruleAction instanceof RuleActionNotification notificationAction) {
@@ -957,62 +956,66 @@ public class JsonRulesBuilder extends RulesBuilder {
matchingAssetStates.forEach(assetState -> {
Object value = assetState.getValue().orElse(null);
- Class<?> valueType = assetState.getType().getType();
+ Class<?> valueType = assetState.getTypeClass();
boolean isArray = ValueUtil.isArray(valueType);
- if (!isArray && !ValueUtil.isObject(valueType)) {
+ if (!isArray && !ValueUtil.isMap(valueType)) {
log(Level.WARNING, "Rule action target asset cannot determine value type or incompatible value type for attribute: " + assetState);
} else {
+ if (isArray) {
+ List<Object> list = new ArrayList<>();
+ if (value != null) {
+ Collections.addAll(list, value);
+ }
- // Convert value to JSON Node to easily manipulate it
- value = isArray ? ValueUtil.convert(value, ArrayNode.class) : ValueUtil.convert(value, ObjectNode.class);
-
- switch (attributeUpdateAction.updateAction) {
- case ADD:
- if (isArray) {
- value = value == null ? ValueUtil.JSON.createArrayNode() : value;
- ((ArrayNode)value).add(ValueUtil.convert(attributeUpdateAction.value, JsonNode.class));
- } else {
- value = value == null ? ValueUtil.JSON.createObjectNode() : value;
- ((ObjectNode) value).set(attributeUpdateAction.key, ValueUtil.convert(attributeUpdateAction.value, JsonNode.class));
+ switch (attributeUpdateAction.updateAction) {
+ case ADD -> {
+ list.add(attributeUpdateAction.value);
}
- break;
- case ADD_OR_REPLACE:
- case REPLACE:
- if (isArray) {
- value = value == null ? ValueUtil.JSON.createArrayNode() : value;
- ArrayNode arrayValue = (ArrayNode) value;
-
- if (attributeUpdateAction.index != null && arrayValue.size() >= attributeUpdateAction.index) {
- arrayValue.set(attributeUpdateAction.index, ValueUtil.convert(attributeUpdateAction.value, JsonNode.class));
+ case ADD_OR_REPLACE, REPLACE -> {
+ if (attributeUpdateAction.index != null && list.size() >= attributeUpdateAction.index) {
+ list.set(attributeUpdateAction.index, attributeUpdateAction.value);
} else {
- arrayValue.add(ValueUtil.convert(attributeUpdateAction.value, JsonNode.class));
+ list.add(attributeUpdateAction.value);
}
- } else {
- value = value == null ? ValueUtil.JSON.createObjectNode() : value;
+ }
+ case DELETE -> {
+ if (attributeUpdateAction.index != null && list.size() >= attributeUpdateAction.index) {
+ list.remove(attributeUpdateAction.index);
+ }
+ }
+ case CLEAR -> {
+ value = Collections.emptyList();
+ }
+ }
+
+ value = list;
+ } else {
+ Map map = new HashMap();
+ if (value != null) {
+ map.putAll((Map)value);
+ }
+
+ switch (attributeUpdateAction.updateAction) {
+ case ADD -> {
+ map.put(attributeUpdateAction.key, attributeUpdateAction.value);
+ }
+ case ADD_OR_REPLACE, REPLACE -> {
if (!TextUtil.isNullOrEmpty(attributeUpdateAction.key)) {
- ((ObjectNode) value).set(attributeUpdateAction.key, ValueUtil.convert(attributeUpdateAction.value, JsonNode.class));
+ map.put(attributeUpdateAction.key, attributeUpdateAction.value);
} else {
log(Level.WARNING, "JSON Rule: Rule action missing required 'key': " + ValueUtil.asJSON(attributeUpdateAction));
}
}
- break;
- case DELETE:
- if(value != null) {
- if (isArray) {
- ((ArrayNode) value).remove(attributeUpdateAction.index);
- } else {
- ((ObjectNode) value).remove(attributeUpdateAction.key);
- }
+ case DELETE -> {
+ map.remove(attributeUpdateAction.key);
}
- break;
- case CLEAR:
- if (isArray) {
- value = ValueUtil.JSON.createArrayNode();
- } else {
- value = ValueUtil.JSON.createObjectNode();
+ case CLEAR -> {
+ map = Collections.emptyMap();
}
- break;
+ }
+
+ value = map;
}
log(Level.FINE, "Updating attribute for rule action: " + rule.name + " '" + actionsName + "' action index " + index + ": " + assetState);
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/rules/RulesHealthStatusProvider.java
index ccf7d57c6..3144c665e 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesHealthStatusProvider.java
@@ -19,13 +19,14 @@
*/
package org.openremote.manager.rules;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.rules.AssetRuleset;
import org.openremote.model.rules.RealmRuleset;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
+
+import java.util.HashMap;
+import java.util.Map;
public class RulesHealthStatusProvider implements HealthStatusProvider {
@@ -73,7 +74,7 @@ public class RulesHealthStatusProvider implements HealthStatusProvider {
}
}
- ObjectNode realmEngines = ValueUtil.createJsonObject();
+ Map<String, Object> realmEngines = new HashMap<>();
for (RulesEngine<RealmRuleset> realmEngine : rulesService.realmEngines.values()) {
if (!realmEngine.isRunning()) {
@@ -83,10 +84,10 @@ public class RulesHealthStatusProvider implements HealthStatusProvider {
errorEngines++;
}
- realmEngines.set(realmEngine.getId().getRealm().orElse(""), getEngineHealthStatus(realmEngine));
+ realmEngines.put(realmEngine.getId().getRealm().orElse(""), getEngineHealthStatus(realmEngine));
}
- ObjectNode assetEngines = ValueUtil.createJsonObject();
+ Map<String, Object> assetEngines = new HashMap<>();
for (RulesEngine<AssetRuleset> assetEngine : rulesService.assetEngines.values()) {
if (!assetEngine.isRunning()) {
@@ -97,45 +98,44 @@ public class RulesHealthStatusProvider implements HealthStatusProvider {
errorEngines++;
}
- assetEngines.set(assetEngine.getId().getAssetId().orElse(""), getEngineHealthStatus(assetEngine));
+ assetEngines.put(assetEngine.getId().getAssetId().orElse(""), getEngineHealthStatus(assetEngine));
}
- ObjectNode objectValue = ValueUtil.createJsonObject();
+ Map<String, Object> objectValue = new HashMap<>();
objectValue.put("totalEngines", totalEngines);
objectValue.put("stoppedEngines", stoppedEngines);
objectValue.put("errorEngines", errorEngines);
if (rulesService.globalEngine != null) {
- objectValue.set("global", getEngineHealthStatus(rulesService.globalEngine));
+ objectValue.put("global", getEngineHealthStatus(rulesService.globalEngine));
}
- objectValue.set("realm", realmEngines);
- objectValue.set("asset", assetEngines);
+ objectValue.put("realm", realmEngines);
+ objectValue.put("asset", assetEngines);
return objectValue;
}
- protected ObjectNode getEngineHealthStatus(RulesEngine<?> rulesEngine) {
+ protected Map<String, Object> getEngineHealthStatus(RulesEngine<?> rulesEngine) {
boolean isError = rulesEngine.isError();
int totalDeployments = rulesEngine.deployments.size();
int executionErrorDeployments = rulesEngine.getExecutionErrorDeploymentCount();
int compilationErrorDeployments = rulesEngine.getExecutionErrorDeploymentCount();
- ObjectNode val = ValueUtil.createJsonObject();
+ Map<String, Object> val = new HashMap<>();
val.put("isRunning", rulesEngine.isRunning());
val.put("isError", isError);
val.put("totalDeployments", totalDeployments);
val.put("executionErrorDeployments", executionErrorDeployments);
val.put("compilationErrorDeployments", compilationErrorDeployments);
- ObjectNode deployments = ValueUtil.createJsonObject();
+ Map<String, Object> deployments = new HashMap<>();
- for (Object obj : rulesEngine.deployments.values()) {
- RulesetDeployment deployment = (RulesetDeployment)obj;
- ObjectNode dVal = ValueUtil.createJsonObject();
+ for (RulesetDeployment deployment : rulesEngine.deployments.values()) {
+ Map<String, Object> dVal = new HashMap<>();
dVal.put("name", deployment.getName());
dVal.put("status", deployment.getStatus().name());
dVal.put("error", deployment.getError() != null ? deployment.getError().getMessage() : null);
- deployments.set(Long.toString(deployment.getId()), dVal);
+ deployments.put(Long.toString(deployment.getId()), dVal);
}
- val.set("deployments", deployments);
+ val.put("deployments", deployments);
return val;
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
index bfd1ec8f3..48d868394 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -127,7 +127,7 @@ public class RulesetDeployment {
}
protected void init() throws IllegalStateException {
- if (ruleset.getMeta().has(Ruleset.VALIDITY)) {
+ if (ruleset.getMeta().containsKey(Ruleset.VALIDITY)) {
validity = ruleset.getValidity();
if (validity == null) {
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
index be1c296cb..162edce9d 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
@@ -19,7 +19,6 @@
*/
package org.openremote.manager.rules;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.hibernate.Session;
import org.hibernate.jdbc.AbstractReturningWork;
import org.openremote.container.persistence.PersistenceService;
@@ -42,6 +41,7 @@ import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
+import java.util.Map;
import java.util.function.Consumer;
import java.util.logging.Logger;
@@ -290,7 +290,7 @@ public class RulesetStorageService implements ContainerService {
ruleset.setLastModified(rs.getTimestamp("LAST_MODIFIED"));
ruleset.setCreatedOn(rs.getTimestamp("CREATED_ON"));
if (rs.getString("META") != null) {
- ruleset.setMeta(ValueUtil.parse(rs.getString("META"), ObjectNode.class).orElse(null));
+ ruleset.setMeta(ValueUtil.parse(rs.getString("META"), Map.class).orElse(null));
}
if (query.fullyPopulate) {
ruleset.setRules(rs.getString("RULES"));
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index eaebbce91..74b2f60c7 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -19,16 +19,15 @@
*/
package org.openremote.manager.rules.geofence;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.builder.RouteBuilder;
import org.openremote.container.message.MessageBrokerService;
-import org.openremote.model.PersistenceEvent;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.gateway.GatewayService;
import org.openremote.manager.notification.NotificationService;
import org.openremote.manager.rules.RulesEngine;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.Container;
+import org.openremote.model.PersistenceEvent;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.impl.ConsoleAsset;
import org.openremote.model.attribute.AttributeRef;
@@ -39,7 +38,6 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.*;
import org.openremote.model.rules.geofence.GeofenceDefinition;
import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.ValueUtil;
import java.util.*;
import java.util.concurrent.*;
@@ -247,7 +245,7 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
}
List<String> ids = new ArrayList<>(assetIds);
- ObjectNode data = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> data = new HashMap<>();
data.put("action", "GEOFENCE_REFRESH");
// Break into batches of 10 sent every 10s to avoid consoles bombarding the backend
diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
index 831c778a9..e61827233 100644
--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java
@@ -154,9 +154,9 @@ public interface ManagerIdentityProvider extends IdentityProvider {
sb.append(" AND ua.asset_id IN (?").append(parameters.size() + 1).append(")");
parameters.add(Arrays.asList(userQuery.assets));
}
- if (userQuery.pathPredicate != null) {
- sb.append(" AND ?").append(parameters.size() + 1).append(" <@ get_asset_tree_path(ua.asset_id)");
- parameters.add(userQuery.pathPredicate.path);
+ if (userQuery.pathPredicate != null && userQuery.pathPredicate.path != null && userQuery.pathPredicate.path.length > 0) {
+ sb.append(" AND ?").append(parameters.size() + 1).append("\\:\\:text[] <@ get_asset_tree_path(ua.asset_id)");
+ parameters.add("{" + String.join(",", userQuery.pathPredicate.path) + "}");
}
if (userQuery.ids != null && userQuery.ids.length > 0) {
sb.append(" AND u.id IN (?").append(parameters.size() + 1).append(")");
@@ -268,8 +268,6 @@ public interface ManagerIdentityProvider extends IdentityProvider {
}
List<User> userList = sqlQuery.getResultList();
- // TODO: Remove this once migrated to hibernate 6.2.x+
- userList.forEach(u -> u.getAttributes().size());
return userList;
});
diff --git a/manager/src/main/java/org/openremote/manager/system/CamelHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/system/CamelHealthStatusProvider.java
index 4c7b9efee..965bcc371 100644
--- a/manager/src/main/java/org/openremote/manager/system/CamelHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/system/CamelHealthStatusProvider.java
@@ -19,8 +19,6 @@
*/
package org.openremote.manager.system;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.camel.Endpoint;
import org.apache.camel.component.seda.SedaEndpoint;
import org.apache.camel.health.HealthCheck;
@@ -28,11 +26,12 @@ import org.apache.camel.health.HealthCheckHelper;
import org.apache.camel.support.service.BaseService;
import org.openremote.container.message.MessageBrokerService;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
import org.openremote.model.util.ValueUtil;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
public class CamelHealthStatusProvider implements HealthStatusProvider {
@@ -43,13 +42,12 @@ public class CamelHealthStatusProvider implements HealthStatusProvider {
@Override
public void init(Container container) throws Exception {
brokerService = container.getService(MessageBrokerService.class);
- // Add mixin for health check results
- ValueUtil.JSON.addMixIn(HealthCheck.Result.class, HealthCheckResultMixin.class);
}
@Override
public void start(Container container) throws Exception {
-
+ // Add mixin for health check results
+ ValueUtil.JSON.addMixIn(HealthCheck.Result.class, HealthCheckResultMixin.class);
}
@Override
@@ -65,10 +63,10 @@ public class CamelHealthStatusProvider implements HealthStatusProvider {
@Override
public Object getHealthStatus() {
Map<String, Object> result = new HashMap<>();
- ArrayNode endpointInfos = ValueUtil.JSON.createArrayNode();
+ List<Map<String, Object>> endpointInfos = new ArrayList<>();
for (Endpoint endpoint : brokerService.getContext().getEndpoints()) {
- ObjectNode endpointInfo = ValueUtil.createJsonObject();
+ Map<String, Object> endpointInfo = new HashMap<>();
endpointInfo.put("uri", endpoint.getEndpointUri());
if (endpoint instanceof BaseService baseService) {
endpointInfo.put("status", baseService.getStatus().name());
diff --git a/manager/src/main/java/org/openremote/manager/system/JvmHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/system/JvmHealthStatusProvider.java
index b47f31d33..7e4a78248 100644
--- a/manager/src/main/java/org/openremote/manager/system/JvmHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/system/JvmHealthStatusProvider.java
@@ -19,26 +19,20 @@
*/
package org.openremote.manager.system;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ThreadMXBean;
+import java.util.HashMap;
+import java.util.Map;
public class JvmHealthStatusProvider implements HealthStatusProvider {
public static final String NAME = "jvm";
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
@@ -61,7 +55,7 @@ public class JvmHealthStatusProvider implements HealthStatusProvider {
@Override
public Object getHealthStatus() {
- ObjectNode objectValue = ValueUtil.createJsonObject();
+ Map<String, Object> objectValue = new HashMap<>();
com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
diff --git a/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
index e60fbd130..79e103671 100644
--- a/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/system/SslHealthStatusProvider.java
@@ -19,12 +19,9 @@
*/
package org.openremote.manager.system;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Constants;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
import javax.net.ssl.*;
import java.io.IOException;
@@ -32,6 +29,7 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.time.Instant;
import java.util.Date;
+import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -47,11 +45,6 @@ public class SslHealthStatusProvider implements X509TrustManager, HealthStatusPr
protected int SSLPort;
protected SSLContext SSLContext;
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
@@ -64,7 +57,7 @@ public class SslHealthStatusProvider implements X509TrustManager, HealthStatusPr
if (SSLPort > 0 && SSLPort <= 65536) {
this.SSLPort = SSLPort;
host = getString(container.getConfig(), Constants.OR_HOSTNAME, null);
- SSLContext = SSLContext.getInstance("TLS");
+ SSLContext = javax.net.ssl.SSLContext.getInstance("TLS");
SSLContext.init(null, new TrustManager[]{this}, null);
}
}
@@ -91,8 +84,7 @@ public class SslHealthStatusProvider implements X509TrustManager, HealthStatusPr
SSLSocketFactory ssf = SSLContext.getSocketFactory();
- try {
- SSLSocket socket = (SSLSocket) ssf.createSocket(host, SSLPort);
+ try (SSLSocket socket = (SSLSocket) ssf.createSocket(host, SSLPort)) {
socket.startHandshake();
X509Certificate[] peerCertificates = (X509Certificate[]) socket.getSession().getPeerCertificates();
@@ -100,9 +92,7 @@ public class SslHealthStatusProvider implements X509TrustManager, HealthStatusPr
Date date = serverCert.getNotAfter();
long validDays = DAYS.between(Instant.now(), date.toInstant());
- ObjectNode objectValue = ValueUtil.JSON.createObjectNode();
- objectValue.put("validDays", validDays);
- return objectValue;
+ return Map.<String, Object>of("validDays", validDays);
} catch (IOException e) {
LOG.log(Level.WARNING, "Failed to connect to SSL port " + SSLPort + " on host: " + host);
return null;
diff --git a/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java b/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java
index 2356029ca..b057a28cc 100644
--- a/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/system/StatusResourceImpl.java
@@ -19,16 +19,16 @@
*/
package org.openremote.manager.system;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.manager.security.ManagerIdentityService;
import org.openremote.model.Container;
import org.openremote.model.system.HealthStatusProvider;
import org.openremote.model.system.StatusResource;
-import org.openremote.model.util.ValueUtil;
import java.io.IOException;
import java.io.InputStream;
+import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -37,12 +37,12 @@ public class StatusResourceImpl implements StatusResource {
private static final Logger LOG = Logger.getLogger(StatusResourceImpl.class.getName());
protected List<HealthStatusProvider> healthStatusProviderList;
- protected ObjectNode serverInfo;
+ protected Map<String, Object> serverInfo;
public StatusResourceImpl(Container container, List<HealthStatusProvider> healthStatusProviderList) {
this.healthStatusProviderList = healthStatusProviderList;
Properties versionProps = new Properties();
- String authServerUrl = null;
+ String authServerUrl = "";
ManagerIdentityService identityService = container.getService(ManagerIdentityService.class);
if (identityService != null) {
@@ -57,19 +57,19 @@ public class StatusResourceImpl implements StatusResource {
}
String version = versionProps.getProperty("version");
- serverInfo = ValueUtil.JSON.createObjectNode();
- serverInfo.put("version", version);
- serverInfo.put("authServerUrl", authServerUrl);
+ serverInfo = Map.of(
+ "version", version,
+ "authServerUrl", authServerUrl
+ );
}
@Override
- public ObjectNode getHealthStatus() {
- ObjectNode objectValue = ValueUtil.JSON.createObjectNode();
+ public Map<String, Object> getHealthStatus() {
+ Map<String, Object> objectValue = new HashMap<>();
healthStatusProviderList.forEach(healthStatusProvider -> {
- ObjectNode providerValue = ValueUtil.JSON.createObjectNode();
- providerValue.putPOJO("data", healthStatusProvider.getHealthStatus());
- objectValue.set(healthStatusProvider.getHealthStatusName(), providerValue);
+ Map<String, Object> providerValue = Map.of("data", healthStatusProvider.getHealthStatus());
+ objectValue.put(healthStatusProvider.getHealthStatusName(), providerValue);
}
);
@@ -77,7 +77,7 @@ public class StatusResourceImpl implements StatusResource {
}
@Override
- public ObjectNode getInfo() {
+ public Map<String, Object> getInfo() {
return serverInfo;
}
}
diff --git a/manager/src/main/java/org/openremote/manager/system/SystemHealthStatusProvider.java b/manager/src/main/java/org/openremote/manager/system/SystemHealthStatusProvider.java
index 36c794a66..3edfff96b 100644
--- a/manager/src/main/java/org/openremote/manager/system/SystemHealthStatusProvider.java
+++ b/manager/src/main/java/org/openremote/manager/system/SystemHealthStatusProvider.java
@@ -19,24 +19,18 @@
*/
package org.openremote.manager.system;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Container;
-import org.openremote.model.ContainerService;
import org.openremote.model.system.HealthStatusProvider;
-import org.openremote.model.util.ValueUtil;
import java.io.File;
import java.lang.management.ManagementFactory;
+import java.util.HashMap;
+import java.util.Map;
public class SystemHealthStatusProvider implements HealthStatusProvider {
public static final String NAME = "system";
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void init(Container container) throws Exception {
@@ -59,7 +53,7 @@ public class SystemHealthStatusProvider implements HealthStatusProvider {
@Override
public Object getHealthStatus() {
- ObjectNode objectValue = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> objectValue = new HashMap<>();
com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
File[] roots = File.listRoots();
@@ -70,18 +64,18 @@ public class SystemHealthStatusProvider implements HealthStatusProvider {
objectValue.put("totalSwapSpaceMB", operatingSystemMXBean.getTotalSwapSpaceSize() / (1024F*1024F));
objectValue.put("freeSwapSpaceMB", operatingSystemMXBean.getFreeSwapSpaceSize() / (1024F*1024F));
- ObjectNode rootsObj = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> rootsObj = new HashMap<>();
for (File root : roots) {
- ObjectNode rootObj = ValueUtil.JSON.createObjectNode();
+ Map<String, Object> rootObj = new HashMap<>();
rootObj.put("totalSpaceMB", root.getTotalSpace() / (1024F*1024F));
rootObj.put("freeSpaceMB", root.getFreeSpace() / (1024F*1024F));
String name = root.getAbsolutePath();
name = name.replace("/","").replace("\\", "").replace(":", "");
- rootsObj.set(name, rootObj);
+ rootsObj.put(name, rootObj);
}
- objectValue.set("filesystem", rootsObj);
+ objectValue.put("filesystem", rootsObj);
return objectValue;
}
diff --git a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
index 5984b3010..47ee1dfab 100644
--- a/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
+++ b/manager/src/main/java/org/openremote/manager/webhook/WebhookService.java
@@ -63,11 +63,6 @@ public class WebhookService extends RouteBuilder implements ContainerService {
);
}
- @Override
- public int getPriority() {
- return ContainerService.DEFAULT_PRIORITY;
- }
-
@Override
public void configure() throws Exception {
// empty
@@ -83,7 +78,9 @@ public class WebhookService extends RouteBuilder implements ContainerService {
// empty
}
+
public boolean sendHttpRequest(Webhook webhook, MediaType mediaType, WebTarget target) {
+
try (Response response = this.buildRequest(target, webhook.getHttpMethod(), mediaType, webhook.getPayload())) {
if (response.getStatusInfo().getFamily() != Response.Status.Family.SUCCESSFUL) {
LOG.warning("Webhook request responded with error " + response.getStatus() + ": " + response.getStatusInfo().getReasonPhrase());
@@ -108,7 +105,7 @@ public class WebhookService extends RouteBuilder implements ContainerService {
} else if (webhook.getOAuthGrant() != null) {
builder.setOAuthAuthentication(webhook.getOAuthGrant());
}
- if (webhook.getHeaders() != null && webhook.getHeaders().size() > 0) {
+ if (webhook.getHeaders() != null && !webhook.getHeaders().isEmpty()) {
builder.setInjectHeaders(webhook.getHeaders());
}
return builder.build();
diff --git a/manager/src/main/resources/hibernate-types.properties b/manager/src/main/resources/hibernate-types.properties
deleted file mode 100644
index d0161c0f3..000000000
--- a/manager/src/main/resources/hibernate-types.properties
+++ /dev/null
@@ -1,2 +0,0 @@
-hibernate.types.jackson.object.mapper=org.openremote.container.persistence.CustomObjectMapperSupplier
-hibernate.types.json.serializer=org.openremote.container.persistence.CustomObjectMapperJsonSerializer
diff --git a/model/build.gradle b/model/build.gradle
index b76b155a3..cb37f8c31 100644
--- a/model/build.gradle
+++ b/model/build.gradle
@@ -10,7 +10,6 @@ dependencies {
api "org.hibernate.orm:hibernate-core:$hibernateVersion"
api "org.hibernate.validator:hibernate-validator:$hibernateValidatorVersion"
- api "com.vladmihalcea:hibernate-types-60:$hibernateTypesVersion"
api "jakarta.el:jakarta.el-api:$javaxELAPIVersion"
api "org.jboss.logging:jboss-logging-annotations:$jbossLoggingAnnotationsVersion"
diff --git a/model/src/main/java/org/openremote/model/AssetModelProvider.java b/model/src/main/java/org/openremote/model/AssetModelProvider.java
index e194fe136..910a6face 100644
--- a/model/src/main/java/org/openremote/model/AssetModelProvider.java
+++ b/model/src/main/java/org/openremote/model/AssetModelProvider.java
@@ -22,12 +22,12 @@ package org.openremote.model;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
import org.openremote.model.util.TsIgnore;
+import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
-import org.openremote.model.util.ValueUtil;
-import java.util.List;
+import java.util.Collection;
import java.util.Map;
import java.util.ServiceLoader;
@@ -57,14 +57,18 @@ public interface AssetModelProvider {
* If {@link #useAutoScan} is true and this is also defined then the results will be combined with those returned by
* scanning.
*/
- AssetDescriptor<?>[] getAssetDescriptors();
+ default AssetDescriptor<?>[] getAssetDescriptors() {
+ return null;
+ }
/**
* Get {@link AttributeDescriptor}s that should be associated with the specified {@link Asset} type; these are
* combined with any {@link AttributeDescriptor}s already associated with the given {@link Asset} type. Any
* duplicate conflicts will generate an {@link IllegalStateException} during {@link ValueUtil} initialisation.
*/
- Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors();
+ default Map<String, Collection<AttributeDescriptor<?>>> getAttributeDescriptors() {
+ return null;
+ }
/**
* Get {@link MetaItemDescriptor}s that should be associated with the specified {@link Asset} type; these are
@@ -74,23 +78,34 @@ public interface AssetModelProvider {
* If {@link #useAutoScan} is true and this is also defined then the results will be combined with those returned by
* scanning.
*/
- Map<Class<? extends Asset<?>>, List<MetaItemDescriptor<?>>> getMetaItemDescriptors();
+ default Map<String, Collection<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
+ return null;
+ }
/**
* Get {@link ValueDescriptor}s that should be associated with the specified {@link Asset} type; these are combined
* with any {@link ValueDescriptor}s already associated with the given {@link Asset} type. Any duplicate conflicts
- * will generate an {@link IllegalStateException} during {@link ValueUtil} initialisation. Shouldn't contain
- * any {@link ValueDescriptor}s of type array (i.e. ones obtained by calling {@link ValueDescriptor#asArray} or ones
+ * will generate an {@link IllegalStateException} during {@link ValueUtil} initialisation. Shouldn't contain any
+ * {@link ValueDescriptor}s of type array (i.e. ones obtained by calling {@link ValueDescriptor#asArray} or ones
* where {@link ValueDescriptor#getType} returns a class that {@link Class#isArray} returns true for.
* <p>
* If {@link #useAutoScan} is true and this is also defined then the results will be combined with those returned by
* scanning.
*/
- Map<Class<? extends Asset<?>>, List<ValueDescriptor<?>>> getValueDescriptors();
+ default Map<String, Collection<ValueDescriptor<?>>> getValueDescriptors() {
+ return null;
+ }
/**
* Called when the full Asset model has been initialised which gives {@link AssetModelProvider}s the chance to do
* additional work (e.g. add constraints such as allowed values based on available asset types).
*/
- void onAssetModelFinished();
+ default void onAssetModelFinished() {}
+
+ /**
+ * Indicates that this model provider is dynamic and can be refreshed when needed.
+ */
+ default boolean isDynamic() {
+ return false;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index a57571afd..21a17385a 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -53,8 +53,6 @@ public interface Constants {
int ACCESS_TOKEN_LIFESPAN_SECONDS = 60; // 1 minute
String PERSISTENCE_SEQUENCE_ID_GENERATOR = "OPENREMOTE_SEQUENCE";
String PERSISTENCE_UNIQUE_ID_GENERATOR = "UNIQUE_ID_GENERATOR";
- String PERSISTENCE_JSON_VALUE_TYPE = "jsonb";
- String PERSISTENCE_STRING_ARRAY_TYPE = "string-array";
String OR_HOSTNAME = "OR_HOSTNAME";
String OR_ADDITIONAL_HOSTNAMES = "OR_ADDITIONAL_HOSTNAMES";
@@ -77,7 +75,7 @@ public interface Constants {
String UUID_REGEXP = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}";
String EMAIL_REGEXP = "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])";
String ISO8601_DURATION_REGEXP = "^P(?!$)((\\d+Y)|(\\d+\\.\\d+Y$))?((\\d+M)|(\\d+\\.\\d+M$))?((\\d+W)|(\\d+\\.\\d+W$))?((\\d+D)|(\\d+\\.\\d+D$))?(T(?=\\d)((\\d+H)|(\\d+\\.\\d+H$))?((\\d+M)|(\\d+\\.\\d+M$))?(\\d+(\\.\\d+)?S)?)??$";
- String ISO8601_DATETIME_REGEXP = "^(?:[1-9]\\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:Z|[+-][01]\\d:[0-5]\\d)$";
+ String ISO8601_DATETIME_REGEXP = "^(?:[1-9]\\d{3}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)-02-29)T(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:[\\.,]\\d{1,9})?(?:Z|[+-][01]\\d:[0-5]\\d)$";
String HOSTNAME_OR_IP_REGEXP = "((^\\s*((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?)|^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9]))+(\\.([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9]))*)$";
String IP_REGEXP = "((^\\s*((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(^\\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?))$";
String HTTP_URL_REGEXP = "^(http:\\/\\/www\\.|https:\\/\\/www\\.|http:\\/\\/|https:\\/\\/)?((((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)))|(((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))(%.+)?)|(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9]))+(\\.([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9]))*)(:[0-9]{1,5})?(\\/.*)?$";
diff --git a/model/src/main/java/org/openremote/model/StandardModelProvider.java b/model/src/main/java/org/openremote/model/StandardModelProvider.java
index 7ddba19cc..a425b99ba 100644
--- a/model/src/main/java/org/openremote/model/StandardModelProvider.java
+++ b/model/src/main/java/org/openremote/model/StandardModelProvider.java
@@ -20,13 +20,16 @@
package org.openremote.model;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.util.ValueUtil;
-import org.openremote.model.value.*;
+import org.openremote.model.value.MetaItemType;
+import org.openremote.model.value.ValueConstraint;
+import org.openremote.model.value.ValueType;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
import java.util.logging.Logger;
import static org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES;
@@ -42,36 +45,17 @@ public class StandardModelProvider implements AssetModelProvider {
protected static Logger LOG = SyslogCategory.getLogger(MODEL_AND_VALUES, StandardModelProvider.class);
- @Override
- public AssetDescriptor<?>[] getAssetDescriptors() {
- return null;
- }
-
@Override
public boolean useAutoScan() {
return true;
}
- @Override
- public Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<ValueDescriptor<?>>> getValueDescriptors() {
- return null;
- }
-
@Override
public void onAssetModelFinished() {
// Inject allowed asset types into GroupAsset
List<ValueConstraint> constraints = ValueType.ASSET_TYPE.getConstraints() != null ? new ArrayList<>(Arrays.asList(ValueType.ASSET_TYPE.getConstraints())): new ArrayList<>();
- constraints.add(new ValueConstraint.AllowedValues(Arrays.stream(ValueUtil.getAssetClasses(null)).map(Class::getSimpleName).toArray()));
+ constraints.removeIf(vc -> vc instanceof ValueConstraint.AllowedValues);
+ constraints.add(new ValueConstraint.AllowedValues(Arrays.stream(ValueUtil.getAssetInfos(null)).map(ati -> ati.getAssetDescriptor().getName()).toArray()));
ValueType.ASSET_TYPE.updateConstraints(constraints.toArray(new ValueConstraint[0]));
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.java
index b330fbc59..3e760ae83 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -20,10 +20,24 @@
package org.openremote.model.asset;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
+import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import jakarta.persistence.Table;
+import jakarta.persistence.*;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Pattern;
+import jakarta.validation.constraints.Size;
import org.hibernate.annotations.*;
+import org.hibernate.generator.EventType;
+import org.hibernate.type.SqlTypes;
import org.openremote.model.Constants;
import org.openremote.model.IdentifiableEntity;
import org.openremote.model.asset.impl.ThingAsset;
@@ -33,7 +47,6 @@ import org.openremote.model.attribute.MetaMap;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.jackson.AssetTypeIdResolver;
import org.openremote.model.persistence.LTreeType;
-import org.openremote.model.util.TsIgnore;
import org.openremote.model.util.TsIgnoreTypeParams;
import org.openremote.model.util.ValueUtil;
import org.openremote.model.validation.AssetValid;
@@ -41,14 +54,12 @@ import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueFormat;
import org.openremote.model.value.ValueType;
-import jakarta.persistence.*;
-import jakarta.validation.Valid;
-import jakarta.validation.constraints.*;
+import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import static jakarta.persistence.DiscriminatorType.STRING;
-import static org.openremote.model.Constants.*;
+import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;
// @formatter:off
@@ -211,14 +222,45 @@ import static org.openremote.model.Constants.*;
@Check(constraints = "ID != PARENT_ID")
@JsonTypeInfo(include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true, use = JsonTypeInfo.Id.CUSTOM, defaultImpl = ThingAsset.class)
@JsonTypeIdResolver(AssetTypeIdResolver.class)
-@AssetValid(groups = Asset.AssetSave.class)
+@AssetValid
+@Valid
@DynamicUpdate
@TsIgnoreTypeParams
@SuppressWarnings("unchecked")
public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T> {
- @TsIgnore
- public interface AssetSave {}
+ /**
+ * The purpose of this is to provide {@link org.openremote.model.attribute.Attribute.AttributeDeserializer} access
+ * to the asset type so the {@link AttributeDescriptor} can be looked up to control value deserialization; this
+ * isn't used when hydrating from the DB as JPA uses its' own hydration mechanism so we also have a lazy loading
+ * of attribute value mechanism.
+ */
+ public static class AssetDeserializer extends StdDeserializer<Asset<?>> implements ResolvableDeserializer {
+ public static final String ASSET_TYPE_INFO_ATTRIBUTE = "assetTypeInfo";
+ protected final JsonDeserializer<Asset<?>> defaultDeserializer;
+ public AssetDeserializer(JsonDeserializer<Asset<?>> defaultDeserializer, Class<?> clazz) {
+ super(clazz);
+ this.defaultDeserializer = defaultDeserializer;
+ }
+
+ @Override
+ public Asset<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
+ JavaType jType = getValueType(ctxt);
+ if (jType != null) {
+ // Make the asset type info available to the attribute deserialiser
+ ctxt.setAttribute(ASSET_TYPE_INFO_ATTRIBUTE, ValueUtil.getAssetInfo(jType.getRawClass().getSimpleName()).orElse(null));
+ }
+ return defaultDeserializer.deserialize(p, ctxt);
+ }
+
+ // The wrapped deserializer might need some post-processing so check whether it implements it or not
+ @Override
+ public void resolve(DeserializationContext ctxt) throws JsonMappingException {
+ if (defaultDeserializer instanceof ResolvableDeserializer resolvableDeserializer) {
+ resolvableDeserializer.resolve(ctxt);
+ }
+ }
+ }
/*
* ATTRIBUTE DESCRIPTORS DESCRIBING FIXED NAME ATTRIBUTES AND THEIR VALUE TYPE - ALL SUB TYPES OF THIS ASSET TYPE
@@ -273,11 +315,11 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
@Column(name = "PATH", updatable = false, insertable = false, columnDefinition = LTreeType.TYPE)
@Type(LTreeType.class)
- @Generated(GenerationTime.ALWAYS)
+ @Generated(event = {EventType.INSERT, EventType.UPDATE})
protected String[] path;
- @Column(name = "ATTRIBUTES", columnDefinition = PERSISTENCE_JSON_VALUE_TYPE)
- @org.hibernate.annotations.Type(JsonBinaryType.class)
+ @Column(name = "ATTRIBUTES")
+ @JdbcTypeCode(SqlTypes.JSON)
@Valid
protected AttributeMap attributes;
@@ -326,7 +368,7 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
return name;
}
- public T setName(@NotNull String name) throws IllegalArgumentException {
+ public T setName(String name) throws IllegalArgumentException {
Objects.requireNonNull(name);
this.name = name;
return (T) this;
@@ -397,9 +439,6 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
}
public T setAttributes(AttributeMap attributes) {
- if (attributes == null) {
- attributes = new AttributeMap();
- }
this.attributes = attributes;
return (T) this;
}
@@ -417,18 +456,8 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
return getAttributes().get(descriptor);
}
- public Optional<Attribute<?>> getAttribute(String attributeName) {
- return getAttributes().get(attributeName);
- }
-
- public <U> Optional<Attribute<U>> getAttribute(String attributeName, Class<U> valueType) {
- return getAttributes().get(attributeName).map(attribute -> {
- if (attribute.getType().getType() == valueType) {
- return (Attribute<U>) attribute;
- } else {
- return null;
- }
- });
+ public <U> Optional<Attribute<U>> getAttribute(String attributeName) {
+ return getAttributes().get(attributeName).map(attribute -> (Attribute<U>) attribute);
}
public boolean hasAttribute(AttributeDescriptor<?> attributeDescriptor) {
@@ -439,7 +468,6 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
return getAttributes().has(attributeName);
}
-
public T addAttributes(Attribute<?>... attributes) {
getAttributes().addAll(attributes);
return (T) this;
@@ -557,4 +585,18 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
getAttributes().getOrCreate(MODEL).setValue(model);
return (T) this;
}
+
+ @PostLoad
+ protected void postLoadCallback() {
+ if (attributes != null) {
+ // Make sure the attribute types are correctly set based on current asset descriptor not what is in the DB
+ ValueUtil.getAssetInfo(getType()).ifPresent(assetTypeInfo ->
+ attributes.values().forEach(attribute -> {
+ AttributeDescriptor<?> attributeDescriptor = assetTypeInfo.getAttributeDescriptors().get(attribute.getName());
+ if (attributeDescriptor != null) {
+ ((Attribute)attribute).setTypeInternal(attributeDescriptor.getType());
+ }
+ }));
+ }
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java b/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java
index 098c08338..84c07502b 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java
@@ -19,21 +19,19 @@
*/
package org.openremote.model.asset;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonSubTypes;
-import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.fasterxml.jackson.annotation.JsonTypeName;
+import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import jakarta.validation.constraints.Pattern;
import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.util.TsIgnoreTypeParams;
-import org.openremote.model.value.NameHolder;
import org.openremote.model.util.ValueUtil;
+import org.openremote.model.value.NameHolder;
import java.io.IOException;
@@ -64,18 +62,23 @@ public class AssetDescriptor<T extends Asset<?>> implements NameHolder {
@Override
public AssetDescriptor<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
- String name = null;
JsonNode node = p.getCodec().readTree(p);
+ String name = node.get("name").asText();
+
+ // Try and lookup instance in type registry
+ AssetDescriptor<?> existing = ValueUtil.getAssetDescriptor(name).orElse(null);
- if (node.isTextual()) {
- name = node.asText();
- } else if (node.isObject()) {
- name = node.get("name").asText();
+ if (existing != null) {
+ return existing;
}
- return ValueUtil.getAssetDescriptor(name).orElse(null);
+
+ String icon = node.get("icon").asText();
+ String colour = node.get("colour").asText();
+ return new AssetDescriptor<>(name, icon, colour);
}
}
+ @Pattern(regexp = "^\\w+$")
protected String name;
@JsonIgnore
protected Class<T> type;
@@ -84,6 +87,13 @@ public class AssetDescriptor<T extends Asset<?>> implements NameHolder {
AssetDescriptor() {}
+ @JsonCreator
+ protected AssetDescriptor(String name, String icon, String colour) {
+ this.name = name;
+ this.icon = icon;
+ this.colour = colour;
+ }
+
/**
* Construct an instance using the {@link Class#getSimpleName} value of the specified type as the descriptor name,
* the {@link Class#getSimpleName} must therefore be unique enough to not clash with other {@link AssetDescriptor}s.
@@ -114,4 +124,13 @@ public class AssetDescriptor<T extends Asset<?>> implements NameHolder {
public String getColour() {
return colour;
}
+
+ @JsonProperty("dynamic")
+ protected Boolean isDynamicInternal() {
+ return type != null ? null : true;
+ }
+
+ public boolean isDynamic() {
+ return type == null;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetModelResource.java b/model/src/main/java/org/openremote/model/asset/AssetModelResource.java
index dbee6b5cb..6f55b7c69 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetModelResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetModelResource.java
@@ -26,6 +26,8 @@ import org.openremote.model.value.ValueDescriptor;
import jakarta.ws.rs.*;
+import java.util.Map;
+
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
/**
@@ -72,23 +74,23 @@ public interface AssetModelResource {
/**
* Retrieve value descriptors {@link ValueDescriptor} available in this system or from a {@link
- * org.openremote.model.asset.impl.GatewayAsset} depending on whether or not a * parentId is supplied, if it isn't
- * then this instance is used, if it is and the {@link Asset} or one of its' * ancestors resides on a {@link
+ * org.openremote.model.asset.impl.GatewayAsset} depending on whether or not a parentId is supplied, if it isn't
+ * then this instance is used, if it is and the {@link Asset} or one of its' ancestors resides on a {@link
* org.openremote.model.asset.impl.GatewayAsset} then that gateway instance is used.
*/
@GET
@Path("valueDescriptors")
@Produces(APPLICATION_JSON)
- ValueDescriptor<?>[] getValueDescriptors(@BeanParam RequestParams requestParams, @QueryParam("parentId") String parentId);
+ Map<String, ValueDescriptor<?>> getValueDescriptors(@BeanParam RequestParams requestParams, @QueryParam("parentId") String parentId);
/**
* Retrieve meta descriptors {@link MetaItemDescriptor} available in this system or from a {@link
- * org.openremote.model.asset.impl.GatewayAsset} depending on whether or not a * parentId is supplied, if it isn't
- * then this instance is used, if it is and the {@link Asset} or one of its' * ancestors resides on a {@link
+ * org.openremote.model.asset.impl.GatewayAsset} depending on whether or not a parentId is supplied, if it isn't
+ * then this instance is used, if it is and the {@link Asset} or one of its' ancestors resides on a {@link
* org.openremote.model.asset.impl.GatewayAsset} then that gateway instance is used.
*/
@GET
@Path("metaItemDescriptors")
@Produces(APPLICATION_JSON)
- MetaItemDescriptor<?>[] getMetaItemDescriptors(@BeanParam RequestParams requestParams, @QueryParam("parentId") String parentId);
+ Map<String, MetaItemDescriptor<?>> getMetaItemDescriptors(@BeanParam RequestParams requestParams, @QueryParam("parentId") String parentId);
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java
index 02de91151..e9de52713 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java
@@ -24,6 +24,11 @@ import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
+import jakarta.annotation.security.RolesAllowed;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+import jakarta.ws.rs.*;
+import jakarta.ws.rs.core.Response;
import org.openremote.model.Constants;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
@@ -33,12 +38,6 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.MetaItemType;
-import jakarta.annotation.security.RolesAllowed;
-import jakarta.validation.Valid;
-import jakarta.validation.constraints.NotNull;
-import jakarta.validation.constraints.Size;
-import jakarta.ws.rs.*;
-import jakarta.ws.rs.core.Response;
import java.util.List;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
@@ -206,8 +205,9 @@ public interface AssetResource {
@PUT
@Path("{assetId}")
@Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
@RolesAllowed({Constants.WRITE_ASSETS_ROLE})
- void update(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @Valid Asset<?> asset);
+ Asset<?> update(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, Asset<?> asset);
/**
* Updates an attribute of an asset. Regular users can only update assets in their authenticated realm, the
@@ -253,7 +253,7 @@ public interface AssetResource {
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed({Constants.WRITE_ASSETS_ROLE})
- Asset<?> create(@BeanParam RequestParams requestParams, @Valid Asset<?> asset);
+ Asset<?> create(@BeanParam RequestParams requestParams, Asset<?> asset);
/**
* Deletes an asset. Regular users can only delete assets in their authenticated realm, the superuser can delete
diff --git a/model/src/main/java/org/openremote/model/asset/AssetTypeInfo.java b/model/src/main/java/org/openremote/model/asset/AssetTypeInfo.java
index 330313c52..3f7cc82d2 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetTypeInfo.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetTypeInfo.java
@@ -19,29 +19,33 @@
*/
package org.openremote.model.asset;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.MetaItemDescriptor;
-import org.openremote.model.value.ValueDescriptor;
+import org.openremote.model.value.*;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
+import java.util.stream.Collectors;
public class AssetTypeInfo {
protected AssetDescriptor<?> assetDescriptor;
- protected AttributeDescriptor<?>[] attributeDescriptors;
- @JsonSerialize(contentConverter = MetaItemDescriptor.MetaItemDescriptorStringConverter.class)
+ @JsonIgnore
+ protected Map<String, AttributeDescriptor<?>> attributeDescriptors;
+ @JsonSerialize(contentConverter = NameHolder.NameHolderToStringConverter.class)
@JsonDeserialize(contentConverter = MetaItemDescriptor.StringMetaItemDescriptorConverter.class)
protected MetaItemDescriptor<?>[] metaItemDescriptors;
- @JsonSerialize(contentConverter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(contentConverter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonSerialize(contentConverter = ValueDescriptor.NameHolderToStringConverter.class)
protected ValueDescriptor<?>[] valueDescriptors;
- AssetTypeInfo() {
- }
-
- public AssetTypeInfo(AssetDescriptor<?> assetDescriptor, AttributeDescriptor<?>[] attributeDescriptors, MetaItemDescriptor<?>[] metaItemDescriptors, ValueDescriptor<?>[] valueDescriptors) {
+ @JsonCreator
+ public AssetTypeInfo(AssetDescriptor<?> assetDescriptor, @JsonProperty("attributeDescriptors") AttributeDescriptor<?>[] attributeDescriptors, MetaItemDescriptor<?>[] metaItemDescriptors, ValueDescriptor<?>[] valueDescriptors) {
this.assetDescriptor = assetDescriptor;
- this.attributeDescriptors = attributeDescriptors;
+ this.attributeDescriptors = Arrays.stream(attributeDescriptors).collect(Collectors.toMap(AbstractNameValueDescriptorHolder::getName, ad -> ad));
this.metaItemDescriptors = metaItemDescriptors;
this.valueDescriptors = valueDescriptors;
}
@@ -50,7 +54,12 @@ public class AssetTypeInfo {
return assetDescriptor;
}
- public AttributeDescriptor<?>[] getAttributeDescriptors() {
+ @JsonProperty("attributeDescriptors")
+ protected Collection<AttributeDescriptor<?>> getAttributeDescriptorsInternal() {
+ return attributeDescriptors.values();
+ }
+
+ public Map<String, AttributeDescriptor<?>> getAttributeDescriptors() {
return attributeDescriptors;
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/Agent.java b/model/src/main/java/org/openremote/model/asset/agent/Agent.java
index 977616c57..3aded4206 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/Agent.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/Agent.java
@@ -30,7 +30,6 @@ import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemType;
import org.openremote.model.value.ValueType;
-import java.util.Arrays;
import java.util.Optional;
import static org.openremote.model.value.MetaItemType.AGENT_LINK;
@@ -278,12 +277,11 @@ public abstract class Agent<T extends Agent<T, U, V>, U extends Protocol<T>, V e
// and it's not the status attribute (or we'll end up in a loop)
return !attributeName.equals(Agent.STATUS.getName())
&& ValueUtil.getAssetInfo(getType())
- .map(info ->
- Arrays.stream(info.getAttributeDescriptors())
- .anyMatch(ad -> ad.getName().equals(attributeName)))
+ .map(info -> info.getAttributeDescriptors().containsKey(attributeName))
.orElse(false)
+ // Exclude attributes that have a descriptor from the base Asset class
&& ValueUtil.getAssetInfo(Asset.class)
- .map(typeInfo -> Arrays.stream(typeInfo.getAttributeDescriptors()).noneMatch(ad -> ad.getName().equals(attributeName)))
+ .map(typeInfo -> !typeInfo.getAttributeDescriptors().containsKey(attributeName))
.orElse(false);
}
}
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.java
index 2bd0d23bf..38c70a343 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
@@ -22,7 +22,6 @@ package org.openremote.model.asset.agent;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaFormat;
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaInject;
import org.openremote.model.attribute.Attribute;
@@ -33,6 +32,7 @@ import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.ValueFilter;
import java.io.Serializable;
+import java.util.Map;
import java.util.Optional;
/**
@@ -55,10 +55,10 @@ public abstract class AgentLink<T extends AgentLink<?>> implements Serializable
" pushed through to the attribute. An example use case is an API that returns 'ACTIVE'/'DISABLED' strings but" +
" you want to connect this to a Boolean attribute")
@JsonSchemaInject(merge = false, jsonSupplierViaLookup = JSONSchemaUtil.SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_ANY_KEY_ANY_TYPE)
- protected ObjectNode valueConverter;
+ protected Map<String, Object> valueConverter;
@JsonSchemaInject(merge = false, jsonSupplierViaLookup = JSONSchemaUtil.SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_ANY_KEY_ANY_TYPE)
@JsonPropertyDescription("Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion")
- protected ObjectNode writeValueConverter;
+ protected Map<String, Object> writeValueConverter;
@JsonPropertyDescription("String to be used for attribute writes and can contain '" + Protocol.DYNAMIC_VALUE_PLACEHOLDER +
"' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the" +
" protocol (particularly useful for executable attributes)")
@@ -108,22 +108,22 @@ public abstract class AgentLink<T extends AgentLink<?>> implements Serializable
return (T) this;
}
- public Optional<ObjectNode> getValueConverter() {
+ public Optional<Map<String, Object>> getValueConverter() {
return Optional.ofNullable(valueConverter);
}
@SuppressWarnings("unchecked")
- public T setValueConverter(ObjectNode valueConverter) {
+ public T setValueConverter(Map<String, Object> valueConverter) {
this.valueConverter = valueConverter;
return (T) this;
}
- public Optional<ObjectNode> getWriteValueConverter() {
+ public Optional<Map<String, Object>> getWriteValueConverter() {
return Optional.ofNullable(writeValueConverter);
}
@SuppressWarnings("unchecked")
- public T setWriteValueConverter(ObjectNode writeValueConverter) {
+ public T setWriteValueConverter(Map<String, Object> writeValueConverter) {
this.writeValueConverter = writeValueConverter;
return (T) this;
}
diff --git a/model/src/main/java/org/openremote/model/asset/impl/BuildingAsset.java b/model/src/main/java/org/openremote/model/asset/impl/BuildingAsset.java
index be75d2a0d..1736b4463 100644
--- a/model/src/main/java/org/openremote/model/asset/impl/BuildingAsset.java
+++ b/model/src/main/java/org/openremote/model/asset/impl/BuildingAsset.java
@@ -29,7 +29,6 @@ import org.openremote.model.value.ValueType;
import jakarta.persistence.Entity;
import java.util.Collection;
-import java.util.Date;
import java.util.Optional;
import static org.openremote.model.Constants.*;
@@ -41,8 +40,8 @@ public class BuildingAsset extends CityAsset {
public static final AttributeDescriptor<String> POSTAL_CODE = new AttributeDescriptor<>("postalCode", ValueType.TEXT);
public static final AttributeDescriptor<Integer> AREA = new AttributeDescriptor<>("area", ValueType.POSITIVE_INTEGER)
.withUnits(UNITS_METRE, UNITS_SQUARED);
- public static final AttributeDescriptor<String> COUNTRY = CityAsset.COUNTRY.withOptional(true);
- public static final AttributeDescriptor<String> CITY = CityAsset.CITY.withOptional(false);
+ public static final AttributeDescriptor<String> COUNTRY = CityAsset.COUNTRY;
+ public static final AttributeDescriptor<String> CITY = new AttributeDescriptor<>("city", ValueType.TEXT).withOptional(false);
public static final AssetDescriptor<BuildingAsset> DESCRIPTOR = new AssetDescriptor<>("office-building", "4b5966", BuildingAsset.class);
diff --git a/model/src/main/java/org/openremote/model/asset/impl/CityAsset.java b/model/src/main/java/org/openremote/model/asset/impl/CityAsset.java
index c68cbdf7c..d8d644ac6 100644
--- a/model/src/main/java/org/openremote/model/asset/impl/CityAsset.java
+++ b/model/src/main/java/org/openremote/model/asset/impl/CityAsset.java
@@ -48,10 +48,6 @@ public class CityAsset extends Asset<CityAsset> {
super(name);
}
- public Optional<String> getCity() {
- return getAttributes().getValue(CITY);
- }
-
public Optional<String> getRegion() {
return getAttributes().getValue(REGION);
}
diff --git a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java
index 759c5187b..5080c6aec 100644
--- a/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java
+++ b/model/src/main/java/org/openremote/model/asset/impl/ElectricityProducerAsset.java
@@ -51,7 +51,7 @@ public class ElectricityProducerAsset extends ElectricityAsset<ElectricityProduc
/**
* For use by hydrators (i.e. JPA/Jackson)
*/
- ElectricityProducerAsset() {
+ protected ElectricityProducerAsset() {
}
public ElectricityProducerAsset(String name) {
diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.java
index 9d2132c08..9287d30b3 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -21,21 +21,29 @@ package org.openremote.model.attribute;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
+import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JavaType;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
-import com.fasterxml.jackson.databind.util.TokenBuffer;
+import com.fasterxml.jackson.databind.exc.InvalidFormatException;
+import com.fasterxml.jackson.databind.ser.std.StdSerializer;
+import com.fasterxml.jackson.databind.type.TypeFactory;
+import jakarta.annotation.Nonnull;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetTypeInfo;
+import org.openremote.model.syslog.SyslogCategory;
import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.*;
-import jakarta.validation.Valid;
-import jakarta.validation.constraints.NotNull;
import java.io.IOException;
import java.util.*;
import java.util.function.Predicate;
@@ -46,110 +54,162 @@ import java.util.stream.Stream;
* Stores a named value with associated {@link MetaItem}s.
*/
@JsonDeserialize(using = Attribute.AttributeDeserializer.class)
+@JsonSerialize(using = Attribute.AttributeSerializer.class)
public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHolder {
+ /**
+ * Custom deserializer that can use asset type info from deserialization context when it is passed in from the asset
+ * deserializer
+ */
public static class AttributeDeserializer extends StdDeserializer<Attribute<?>> {
+ protected static final JavaType META_MAP_TYPE = TypeFactory.defaultInstance().constructType(MetaMap.class);
+ protected static final JavaType OBJECT_TYPE = TypeFactory.defaultInstance().constructType(Object.class);
+
+ public static final System.Logger LOG = System.getLogger(AttributeDeserializer.class.getName() + "." + SyslogCategory.MODEL_AND_VALUES);
+
protected AttributeDeserializer() {
super(Attribute.class);
}
+ public static Object deserialiseValue(ValueDescriptor<?> valueDescriptor, JsonParser jp, DeserializationContext ctxt) throws IOException {
+ JsonDeserializer<Object> valueTypeDeserializer;
+ if (valueDescriptor != null) {
+ valueTypeDeserializer = ctxt.findRootValueDeserializer(TypeFactory.defaultInstance().constructType(valueDescriptor.getType()));
+ } else {
+ valueTypeDeserializer = ctxt.findRootValueDeserializer(OBJECT_TYPE);
+ }
+ return valueTypeDeserializer.deserialize(jp, ctxt);
+ }
+
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public Attribute<?> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
- // Need to find the type field to know how to deserialise the value
- TokenBuffer tokenBuffer = new TokenBuffer(jp);
- tokenBuffer.copyCurrentStructure(jp);
- JsonParser jp2 = tokenBuffer.asParser();
- JsonParser jp3 = tokenBuffer.asParser();
- String attributeValueType = null;
- int level = 1;
- jp2.nextToken();
-
- while (level > 0) {
- JsonToken nextToken = jp2.nextToken();
-
- if (nextToken == JsonToken.START_OBJECT) {
- level++;
- continue;
- }
-
- if (nextToken == JsonToken.END_OBJECT) {
- level--;
- continue;
- }
-
- if (level == 1 && jp2.currentName().equals("type")) {
- jp2.nextToken();
- attributeValueType = jp2.getValueAsString();
- break;
- }
+ if (!jp.isExpectedStartObjectToken()) {
+ throw new InvalidFormatException(jp, "Attribute must be an object", jp.nextValue(), Attribute.class);
}
- if (attributeValueType == null) {
- throw new JsonParseException(jp, "Failed to extract attribute type information");
- }
+ AssetTypeInfo assetTypeInfo = (AssetTypeInfo) ctxt.getAttribute(Asset.AssetDeserializer.ASSET_TYPE_INFO_ATTRIBUTE);
+ String attributeName = jp.getCurrentName();
+ AttributeDescriptor<?> attributeDescriptor = assetTypeInfo != null ? assetTypeInfo.getAttributeDescriptors().get(attributeName) : null;
+ Attribute<?> attribute;
- // Get inner attribute type or fallback to primitive/JSON type
- Optional<ValueDescriptor<?>> valueDescriptor = ValueUtil.getValueDescriptor(attributeValueType);
- Attribute attribute = new Attribute<>();
+ if (attributeDescriptor != null) {
+ attribute = new Attribute<>(attributeName, attributeDescriptor.getType());
+ } else {
+ attribute = new Attribute<>(attributeName);
+ }
- while (jp3.nextToken() != JsonToken.END_OBJECT) {
- if (jp3.currentToken() == JsonToken.FIELD_NAME) {
- String propName = jp3.currentName();
- JsonToken token = jp3.nextToken();
- if (token == JsonToken.VALUE_NULL) {
- continue;
+ while (jp.nextToken() != JsonToken.END_OBJECT) {
+ String propName = jp.currentName();
+ if (jp.currentToken() == JsonToken.FIELD_NAME) {
+ jp.nextToken();
+ }
+ if (jp.currentToken() == JsonToken.VALUE_NULL) {
+ continue;
+ }
+ switch (propName) {
+ case "type" -> {
+ // Attribute descriptor value type takes priority
+ if (attributeDescriptor == null) {
+ String valueType = jp.getValueAsString();
+ // Try and find matching value descriptor
+ ValueUtil.getValueDescriptor(valueType).ifPresent(vd -> ((Attribute) attribute).setTypeInternal(vd));
+ }
}
- switch (propName) {
- case "meta":
- attribute.meta = jp3.readValueAs(MetaMap.class);
- break;
- case "name":
- attribute.name = jp3.readValueAs(String.class);
- break;
- case "timestamp":
- attribute.timestamp = jp3.readValueAs(Long.class);
- break;
- case "value":
- @SuppressWarnings("unchecked")
- Class valueType = valueDescriptor.map(ValueDescriptor::getType)
- .orElseGet(() -> (Class) Object.class);
- attribute.value = jp3.readValueAs(valueType);
- break;
+ case "meta" -> {
+ JsonDeserializer<Object> metaDeserializer = ctxt.findNonContextualValueDeserializer(META_MAP_TYPE);
+ attribute.meta = (MetaMap) metaDeserializer.deserialize(jp, ctxt);
+ }
+ case "name" -> {
+ String name = jp.getValueAsString();
+ if (!name.equals(attribute.name)) {
+ throw new JsonParseException("Attribute name doesn't match attribute map key");
+ }
+ }
+ case "timestamp" -> attribute.timestamp = jp.getValueAsLong();
+ case "value" -> {
+// // Can only deserialise value once we know its' type
+// if (!typeFound) {
+// valueBuffer = new TokenBuffer(jp, ctxt);
+// valueBuffer.copyCurrentStructure(jp);
+// continue;
+// }
+ ValueDescriptor<?> valueDescriptor = attribute.getType();
+ if (valueDescriptor == null) {
+ // We don't know the type so store the value as a string and hydrate on demand when value
+ // type may be known (this occurs when hydrating assets from the DB)
+ attribute.valueStr = jp.getCodec().readTree(jp).toString();
+ } else {
+ try {
+ ((Attribute) attribute).value = deserialiseValue(valueDescriptor, jp, ctxt);
+ } catch (Exception ignored) {}
+ }
}
}
}
- // Get the value descriptor from the value if it isn't known
- attribute.type = valueDescriptor.orElseGet(() -> {
- if (attribute.value == null) {
- return ValueDescriptor.UNKNOWN;
- }
- Object value = attribute.value;
- return ValueUtil.getValueDescriptorForValue(value);
- });
+// if (valueBuffer != null) {
+// if (!typeFound) {
+// throw new JsonParseException("Asset type is missing");
+// }
+//
+// attribute.value = deserialiseValue(attribute.getType(), valueBuffer.asParser(), ctxt);
+// }
+ return attribute;
+ }
+ }
+
+ /**
+ * Custom serializer that can serialize valueStr (for attributes that haven't been fully hydrated)
+ */
+ @SuppressWarnings("rawtypes")
+ public static class AttributeSerializer extends StdSerializer<Attribute> {
- return (Attribute<?>) attribute;
+ public AttributeSerializer() {
+ super(Attribute.class);
+ }
+
+ @Override
+ public void serialize(Attribute value, JsonGenerator gen, SerializerProvider provider) throws IOException {
+ gen.writeStartObject();
+ gen.writeFieldName("name");
+ gen.writeString(value.getName());
+ if (value.getType() != null) {
+ gen.writeFieldName("type");
+ gen.writeString(value.getType().getName());
+ }
+ provider.defaultSerializeField("meta", value.meta, gen);
+ if (value.valueStr != null) {
+ gen.writeFieldName("value");
+ gen.writeRawValue(value.valueStr);
+ } else {
+ provider.defaultSerializeField("value", value.value, gen);
+ }
+ if (value.timestamp > 0) {
+ gen.writeFieldName("timestamp");
+ gen.writeNumber(value.timestamp);
+ }
+ gen.writeEndObject();
}
}
+ @JsonIgnore
@Valid
protected MetaMap meta;
- @JsonProperty
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
protected long timestamp;
Attribute() {
}
-
public Attribute(AttributeDescriptor<T> attributeDescriptor) {
this(attributeDescriptor, null);
}
public Attribute(AttributeDescriptor<T> attributeDescriptor, T value) {
- this(attributeDescriptor.getName(), attributeDescriptor.getType(), value);
+ super(attributeDescriptor.getName(), attributeDescriptor.getType(), value);
+ // TODO: We should not do this attribute descriptor meta should be read from the descriptor even for DB queries
// Auto merge meta from attribute descriptor
if (attributeDescriptor.getMeta() != null) {
getMeta().addOrReplace(attributeDescriptor.getMeta());
@@ -171,10 +231,14 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
}
public Attribute(String name, ValueDescriptor<T> valueDescriptor, T value, long timestamp) {
- this(name, valueDescriptor, value);
+ super(name, valueDescriptor, value);
setTimestamp(timestamp);
}
+ public Attribute(String name) {
+ this(name, null);
+ }
+
/**
* @return All attributes that exist only in the new list or are different than any attribute in the old list.
*/
@@ -276,10 +340,6 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
return getMeta().getValue(metaItemDescriptor);
}
- public <U> U getMetaValueOrDefault(MetaItemDescriptor<U> metaItemDescriptor) {
- return getMeta().getValueOrDefault(metaItemDescriptor);
- }
-
public boolean hasMeta(MetaItemDescriptor<?> metaItemDescriptor) {
return getMeta().has(metaItemDescriptor);
}
@@ -292,6 +352,25 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
return getMeta().get(metaItemDescriptor);
}
+ @SuppressWarnings("unchecked")
+ @Override
+ public Optional<T> getValue() {
+ if (valueStr != null) {
+ value = (T)ValueUtil.parse(valueStr, getTypeClass()).orElse(null);
+ valueStr = null;
+ }
+ return Optional.ofNullable(value);
+ }
+
+ @SuppressWarnings("unchecked")
+ @Override
+ public <U> Optional<U> getValue(@Nonnull Class<U> valueType) {
+ if (valueType.isAssignableFrom(getTypeClass())) {
+ return (Optional<U>) getValue();
+ }
+ return getValue().flatMap(v -> ValueUtil.getValueCoerced(v, valueType));
+ }
+
@Override
public void setValue(T value) {
super.setValue(value);
@@ -303,7 +382,6 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
this.timestamp = timestamp;
}
- @JsonIgnore
public Optional<Long> getTimestamp() {
return hasExplicitTimestamp() ? Optional.of(Math.abs(timestamp)) : Optional.empty();
}
@@ -317,12 +395,20 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
return timestamp > 0;
}
+ // type is effectively transient so don't use in equality checks as JPA will think the entity is dirty just because
+ // the type has been injected PostLoad
+ // TODO: Restructure packages so this can be package visible
+ public void setTypeInternal(ValueDescriptor<T> type) {
+ this.type = type;
+ }
+
@Override
public String toString() {
String valStr = value != null ? value.toString() : null;
valStr = valStr != null && valStr.length() > 100 ? valStr.substring(0, 100) : valStr;
return getClass().getSimpleName() + "{" +
"name='" + name + '\'' +
+ ", type='" + (type != null ? type.getName() : "null") + '\'' +
", value='" + valStr + '\'' +
", timestamp='" + getTimestamp().orElse(0L) + '\'' +
"} ";
@@ -331,6 +417,7 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
public String toStringAll() {
return getClass().getSimpleName() + "{" +
"name='" + name + '\'' +
+ ", type='" + (type != null ? type.getName() : "null") + '\'' +
", value='" + value + '\'' +
", timestamp='" + getTimestamp().orElse(0L) + '\'' +
", meta='" + (meta == null ? "" : getMeta().values().stream().map(MetaItem::toString).collect(Collectors.joining(","))) + '\'' +
@@ -339,7 +426,7 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
@Override
public int hashCode() {
- return super.hashCode() + Objects.hash(timestamp) + Objects.hash(meta);
+ return Objects.hash(value, name, timestamp, meta);
}
/**
@@ -361,26 +448,18 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
&& Objects.equals(type, that.type);
}
- /**
- * Deep equality check looking at value and meta; this is needed when merging an {@link Asset} as the {@link
- * Attribute} meta and value can be modified without the timestamp being updated; the backend should take care to
- * update timestamps when meta or value is updated during a merge so that the standard {@link #equals} logic can be
- * used in all other cases. Meta value and value equality checking is done by converting value to {@link JsonNode}
- * as all {@link Attribute} and {@link MetaItem} values must be serializable but this doesn't mean that the value
- * type has an equality override so this is the safest mechanism.
- */
- public boolean deepEquals(Object obj) {
- if (obj == null)
- return false;
- if (!(obj instanceof Attribute))
- return false;
- Attribute<?> that = (Attribute<?>) obj;
+ public boolean deepEquals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+ Attribute<?> that = (Attribute<?>) o;
- boolean timestampMatches = Objects.equals(timestamp, that.timestamp);
- boolean metaMatches = (meta == null && that.meta != null && that.meta.isEmpty()) || (that.meta == null && meta != null && meta.isEmpty()) || Objects.equals(meta, that.meta);
- boolean superMatches = super.equals(obj);
- boolean result = timestampMatches && metaMatches && superMatches;
- return result;
+ return Objects.equals(timestamp, that.timestamp)
+ && Objects.equals(name, that.name)
+ && Objects.equals(type, that.type)
+ // Use uninitialized json value if available
+ && (valueStr != null && that.valueStr != null ? Objects.equals(valueStr, that.valueStr) : ValueUtil.objectsEqualsWithJSONFallback(value, that.value))
+ // null or empty meta are considered equal
+ && ((meta == null && that.meta != null && that.meta.isEmpty()) || (that.meta == null && meta != null && meta.isEmpty()) || Objects.equals(meta, that.meta));
}
public boolean equals(Object obj, Comparator<Attribute<?>> comparator) {
@@ -394,4 +473,14 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
Attribute<?> that = (Attribute<?>) obj;
return comparator.compare(this, that) == 0;
}
+
+ public Attribute<T> shallowClone() {
+ Attribute<T> cloned = new Attribute<>();
+ cloned.name = name;
+ cloned.meta = meta;
+ cloned.type = type;
+ cloned.timestamp = timestamp;
+ cloned.value = value;
+ return cloned;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeLink.java b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
index 417ad7d99..e2d3c364a 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
@@ -21,11 +21,11 @@ package org.openremote.model.attribute;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.openremote.model.value.*;
+import org.openremote.model.value.ValueFilter;
import java.io.Serializable;
import java.util.Arrays;
+import java.util.Map;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
@@ -85,12 +85,12 @@ public class AttributeLink implements Serializable {
}
protected AttributeRef ref;
- protected ObjectNode converter;
+ protected Map<String, Object> converter;
protected ValueFilter[] filters;
@JsonCreator
public AttributeLink(@JsonProperty("ref") AttributeRef ref,
- @JsonProperty("converter") ObjectNode converter,
+ @JsonProperty("converter") Map<String, Object> converter,
@JsonProperty("filters") ValueFilter[] filters) {
this.ref = requireNonNull(ref);
this.converter = converter;
@@ -101,11 +101,11 @@ public class AttributeLink implements Serializable {
return ref;
}
- public Optional<ObjectNode> getConverter() {
+ public Optional<Map<String, Object>> getConverter() {
return Optional.ofNullable(converter);
}
- public void setConverter(ObjectNode converter) {
+ public void setConverter(Map<String, Object> converter) {
this.converter = converter;
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeMap.java b/model/src/main/java/org/openremote/model/attribute/AttributeMap.java
index 03d49d321..5d2dcee49 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeMap.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeMap.java
@@ -19,7 +19,6 @@
*/
package org.openremote.model.attribute;
-import org.checkerframework.checker.nullness.qual.Nullable;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
@@ -42,6 +41,7 @@ public class AttributeMap extends NamedMap<Attribute<?>> {
// This works around the crappy type system and avoids the need for a type witness
public <S> Optional<Attribute<S>> get(AttributeDescriptor<S> attributeDescriptor) {
+
return super.get(attributeDescriptor);
}
@@ -52,7 +52,7 @@ public class AttributeMap extends NamedMap<Attribute<?>> {
public <S> Attribute<S> getOrCreate(AttributeDescriptor<S> attributeDescriptor) {
return get(attributeDescriptor).orElseGet(() -> {
Attribute<S> attr = new Attribute<>(attributeDescriptor);
- putSilent(attr);
+ put(attr);
return attr;
});
}
@@ -61,7 +61,7 @@ public class AttributeMap extends NamedMap<Attribute<?>> {
public <S> Attribute<S> getOrCreate(String attributeName, ValueDescriptor<S> valueDescriptor) {
return (Attribute<S>) get(attributeName).orElseGet(() -> {
Attribute<S> attr = new Attribute<>(attributeName, valueDescriptor);
- putSilent(attr);
+ put(attr);
return attr;
});
}
@@ -69,13 +69,4 @@ public class AttributeMap extends NamedMap<Attribute<?>> {
public <T> void setValue(AttributeDescriptor<T> descriptor, T value) {
getOrCreate(descriptor).setValue(value);
}
-
- /**
- * Need to declare equals here as {@link com.vladmihalcea.hibernate.type.json.internal.JsonTypeDescriptor} uses
- * {@link Class#getDeclaredMethod} to find it...
- */
- @Override
- public boolean equals(@Nullable Object object) {
- return super.equals(object);
- }
}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeRef.java b/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
index ffadc30b8..3dc589452 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeRef.java
@@ -21,6 +21,9 @@ package org.openremote.model.attribute;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
+import jakarta.validation.constraints.NotBlank;
+import jakarta.validation.constraints.Pattern;
+import org.openremote.model.Constants;
import java.io.Serializable;
@@ -36,7 +39,10 @@ import static org.openremote.model.util.TextUtil.requireNonNullAndNonEmpty;
*/
public class AttributeRef implements Serializable {
+ @Pattern(regexp = Constants.ASSET_ID_REGEXP, message = "{Asset.id.Pattern}")
protected String id;
+ @NotBlank(message = "{Asset.valueHolder.name.NotBlank}")
+ @Pattern(regexp = "^\\w+$")
protected String name;
@JsonCreator
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaItem.java b/model/src/main/java/org/openremote/model/attribute/MetaItem.java
index 3184cc43d..beb00152d 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaItem.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaItem.java
@@ -28,7 +28,6 @@ import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
import java.io.IOException;
-import java.util.Objects;
/**
* A named value whose name must match the name of a {@link MetaItemDescriptor} and whose value must match the value
@@ -56,28 +55,27 @@ public class MetaItem<T> extends AbstractNameValueHolder<T> {
MetaItem() {
}
- @SuppressWarnings("unchecked")
- public MetaItem(MetaItemDescriptor<T> metaDescriptor) {
- // If it's a boolean meta descriptor assume the caller wants it to be true as a default
- this(metaDescriptor, (T) (metaDescriptor.getType().getType() != Boolean.class ? null : true));
+ public MetaItem(String name) {
+ this(name, null);
}
- public MetaItem(MetaItemDescriptor<T> metaDescriptor, T value) {
- super(metaDescriptor.getName(), metaDescriptor.getType(), value);
+ @SuppressWarnings("unchecked")
+ public MetaItem(String name, ValueDescriptor<?> valueDescriptor) {
+ this(name, (ValueDescriptor<T>) valueDescriptor, null);
}
- // For JPA/Hydrators
- protected void setNameInternal(String name) {
- this.name = name;
+ public MetaItem(String name, ValueDescriptor<T> valueDescriptor, T value) {
+ super(name, valueDescriptor, value);
}
- protected void setTypeInternal(ValueDescriptor<T> type) {
- this.type = type;
+ @SuppressWarnings("unchecked")
+ public MetaItem(MetaItemDescriptor<T> metaDescriptor) {
+ // If it's a boolean meta descriptor assume the caller wants it to be true as a default
+ this(metaDescriptor, (T) (metaDescriptor.getType().getType() != Boolean.class ? null : true));
}
- @Override
- public int hashCode() {
- return Objects.hash(getName(), getValue());
+ public MetaItem(MetaItemDescriptor<T> metaDescriptor, T value) {
+ super(metaDescriptor.getName(), metaDescriptor.getType(), value);
}
@Override
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaMap.java b/model/src/main/java/org/openremote/model/attribute/MetaMap.java
index f84b2b8c7..4eefe503c 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaMap.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaMap.java
@@ -22,16 +22,15 @@ package org.openremote.model.attribute;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
-import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
-import com.fasterxml.jackson.databind.exc.InvalidFormatException;
-import org.checkerframework.checker.nullness.qual.Nullable;
import org.openremote.model.util.ValueUtil;
-import org.openremote.model.value.*;
+import org.openremote.model.value.MetaItemDescriptor;
import java.io.IOException;
import java.util.*;
+import java.util.function.Function;
@JsonDeserialize(using = MetaMap.MetaObjectDeserializer.class)
public class MetaMap extends NamedMap<MetaItem<?>> {
@@ -41,52 +40,62 @@ public class MetaMap extends NamedMap<MetaItem<?>> {
*/
public static class MetaObjectDeserializer extends StdDeserializer<MetaMap> {
+ public static final String META_DESCRIPTOR_PROVIDER = "meta-descriptor-provider";
+ protected static Function<String, MetaItemDescriptor<?>> DEFAULT_META_DESCRIPTOR_PROVIDER = (name) -> ValueUtil.getMetaItemDescriptor(name).orElse(null);
+
public MetaObjectDeserializer() {
super(MetaMap.class);
}
- @SuppressWarnings({"unchecked", "rawtypes"})
+ @SuppressWarnings("unchecked")
@Override
public MetaMap deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
- if (!jp.isExpectedStartObjectToken()) {
- throw new InvalidFormatException(jp, "Expected an object but got something else", jp.nextValue(), MetaMap.class);
+
+ Function<String, MetaItemDescriptor<?>> metaDescriptorProvider = (Function<String, MetaItemDescriptor<?>>)ctxt.getAttribute(META_DESCRIPTOR_PROVIDER);
+ if (metaDescriptorProvider == null) {
+ metaDescriptorProvider = DEFAULT_META_DESCRIPTOR_PROVIDER;
}
- List<MetaItem<?>> list = new ArrayList<>();
+ List<MetaItem<?>> list = deserialiseMetaMap(jp, ctxt, metaDescriptorProvider);
- while(jp.nextToken() != JsonToken.END_OBJECT) {
- if(jp.currentToken() == JsonToken.FIELD_NAME) {
- String metaItemName = jp.getCurrentName();
- jp.nextToken();
+ MetaMap metaMap = new MetaMap();
+ metaMap.putAll(list);
+ return metaMap;
+ }
+ }
- MetaItem metaItem = new MetaItem<>();
- metaItem.setNameInternal(metaItemName);
+ @SuppressWarnings({"unchecked", "rawtypes"})
+ public static List<MetaItem<?>> deserialiseMetaMap(JsonParser jp, DeserializationContext ctxt, Function<String, MetaItemDescriptor<?>> metaDescriptorProvider) throws IOException {
+ if (!jp.isExpectedStartObjectToken()) {
+ throw JsonMappingException.from(jp, "MetaMap must be an object");
+ }
- // Find the meta descriptor for this meta item as this will give us value type also; fallback to
- // OBJECT type meta item to allow deserialization of meta that doesn't exist in the current asset model
- Optional<ValueDescriptor<?>> valueDescriptor = ValueUtil.getMetaItemDescriptor(metaItemName)
- .map(MetaItemDescriptor::getType);
+ List<MetaItem<?>> list = new ArrayList<>();
- Class valueType = valueDescriptor.map(ValueDescriptor::getType).orElseGet(() -> (Class) JsonNode.class);
- metaItem.setValue(jp.readValueAs(valueType));
+ while(jp.nextToken() != JsonToken.END_OBJECT) {
+ if(jp.currentToken() == JsonToken.FIELD_NAME) {
+ jp.nextToken();
+ }
+ if (jp.currentToken() == JsonToken.VALUE_NULL) {
+ continue;
+ }
- // Get the value descriptor from the value if it isn't known
- metaItem.setTypeInternal(valueDescriptor.orElseGet(() -> {
- if (!metaItem.getValue().isPresent()) {
- return ValueDescriptor.UNKNOWN;
- }
- Object value = metaItem.getValue().orElse(null);
- return ValueUtil.getValueDescriptorForValue(value);
- }));
+ String metaItemName = jp.getCurrentName();
+ MetaItemDescriptor<?> metaItemDescriptor = metaDescriptorProvider.apply(metaItemName);
- list.add(metaItem);
- }
+ MetaItem metaItem;
+ if (metaItemDescriptor != null) {
+ metaItem = new MetaItem(metaItemDescriptor.getName(), metaItemDescriptor.getType());
+ } else {
+ metaItem = new MetaItem(metaItemName);
}
- MetaMap metaMap = new MetaMap();
- metaMap.putAllSilent(list);
- return metaMap;
+ metaItem.setValue(Attribute.AttributeDeserializer.deserialiseValue(metaItem.getType(), jp, ctxt));
+
+ list.add(metaItem);
}
+
+ return list;
}
public MetaMap() {
@@ -114,13 +123,4 @@ public class MetaMap extends NamedMap<MetaItem<?>> {
addOrReplace(metaItem);
return metaItem;
}
-
- /**
- * Need to declare equals here as {@link com.vladmihalcea.hibernate.type.json.internal.JsonTypeDescriptor} uses
- * {@link Class#getDeclaredMethod} to find it...
- */
- @Override
- public boolean equals(@Nullable Object object) {
- return super.equals(object);
- }
}
diff --git a/model/src/main/java/org/openremote/model/attribute/NamedMap.java b/model/src/main/java/org/openremote/model/attribute/NamedMap.java
index b06ba2fc3..3b15b5b93 100644
--- a/model/src/main/java/org/openremote/model/attribute/NamedMap.java
+++ b/model/src/main/java/org/openremote/model/attribute/NamedMap.java
@@ -20,12 +20,12 @@
package org.openremote.model.attribute;
import com.google.common.collect.ForwardingMap;
+import jakarta.validation.constraints.NotNull;
import org.openremote.model.value.AbstractNameValueDescriptorHolder;
import org.openremote.model.value.AbstractNameValueHolder;
import org.openremote.model.value.NameHolder;
import org.openremote.model.value.ValueHolder;
-import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer;
@@ -69,17 +69,13 @@ public class NamedMap<T extends AbstractNameValueHolder<?>> extends ForwardingMa
return super.put(key, value);
}
- protected T putSilent(T value) {
- return super.put(value.getName(), value);
- }
-
@Override
public void putAll(Map<? extends String, ? extends T> map) {
addAll(map.values());
}
- protected void putAllSilent(Collection<? extends T> c) {
- c.forEach(this::putSilent);
+ public void putAll(Collection<? extends T> c) {
+ c.forEach(this::put);
}
public void add(@NotNull T t) {
@@ -104,7 +100,7 @@ public class NamedMap<T extends AbstractNameValueHolder<?>> extends ForwardingMa
}
public void addOrReplace(T item) {
- putSilent(item);
+ put(item);
}
@SafeVarargs
@@ -127,34 +123,18 @@ public class NamedMap<T extends AbstractNameValueHolder<?>> extends ForwardingMa
@SuppressWarnings("unchecked")
public <V, W extends AbstractNameValueHolder<V>> Optional<W> get(AbstractNameValueDescriptorHolder<V> nameValueDescriptorHolder) {
Optional<T> valueProvider = get(nameValueDescriptorHolder.getName());
- return valueProvider.map(item -> {
- Class<?> itemType = item.getType().getType();
- Class<V> expectedType = nameValueDescriptorHolder.getType().getType();
- if (itemType == expectedType) {
- return (W)item;
- }
- return null;
- });
+ return valueProvider.map(item -> (W)item);
}
@SuppressWarnings("unchecked")
- public <S> Optional<S> getValue(String name) {
- return get(name).flatMap(ValueHolder::getValue).map(v -> (S)v);
- }
-
- @SuppressWarnings("unchecked")
- public <S> S getValueOrDefault(String name) {
- return (S) get(name).flatMap(ValueHolder::getValue).orElse(null);
+ public <S> Optional<S> getValue(String name, Class<S> clazz) {
+ return get(name).flatMap(valueHolder -> valueHolder.getValue(clazz));
}
public <S> Optional<S> getValue(AbstractNameValueDescriptorHolder<S> nameValueDescriptorProvider) {
return get(nameValueDescriptorProvider).flatMap(ValueHolder::getValue);
}
- public <S> S getValueOrDefault(AbstractNameValueDescriptorHolder<S> nameValueDescriptorProvider) {
- return get(nameValueDescriptorProvider).flatMap(ValueHolder::getValue).orElse(null);
- }
-
public boolean has(NameHolder nameHolder) {
return has(nameHolder.getName());
}
diff --git a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
index 4112f0f3d..86ec7690e 100644
--- a/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
+++ b/model/src/main/java/org/openremote/model/console/ConsoleProvider.java
@@ -21,9 +21,9 @@ package org.openremote.model.console;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.Serializable;
+import java.util.Map;
import java.util.Objects;
public class ConsoleProvider implements Serializable {
@@ -33,7 +33,7 @@ public class ConsoleProvider implements Serializable {
protected boolean success;
protected boolean enabled;
protected boolean disabled;
- protected ObjectNode data;
+ protected Map<String, Object> data;
@JsonCreator
public ConsoleProvider(@JsonProperty("version") String version,
@@ -42,7 +42,7 @@ public class ConsoleProvider implements Serializable {
@JsonProperty("success") boolean success,
@JsonProperty("enabled") boolean enabled,
@JsonProperty("disabled") boolean disabled,
- @JsonProperty("data") ObjectNode data) {
+ @JsonProperty("data") Map<String, Object> data) {
this.version = version;
this.requiresPermission = requiresPermission;
this.hasPermission = hasPermission;
@@ -76,7 +76,7 @@ public class ConsoleProvider implements Serializable {
return disabled;
}
- public ObjectNode getData() {
+ public Map<String, Object> getData() {
return data;
}
diff --git a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
index b16e1f426..f2be0074a 100644
--- a/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
+++ b/model/src/main/java/org/openremote/model/dashboard/Dashboard.java
@@ -1,14 +1,15 @@
package org.openremote.model.dashboard;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import jakarta.persistence.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
+import org.hibernate.annotations.JdbcTypeCode;
+import org.hibernate.type.SqlTypes;
+
import java.util.Date;
-import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_UNIQUE_ID_GENERATOR;
@Entity
@@ -48,8 +49,8 @@ public class Dashboard {
protected String displayName;
@NotNull(message = "{Dashboard.template.NotNull}")
- @Column(name = "TEMPLATE", columnDefinition = PERSISTENCE_JSON_VALUE_TYPE, nullable = false)
- @org.hibernate.annotations.Type(JsonBinaryType.class)
+ @Column(name = "TEMPLATE", nullable = false)
+ @JdbcTypeCode(SqlTypes.JSON)
@Valid
protected DashboardTemplate template;
diff --git a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
index 6ff6164e7..1bb83edec 100644
--- a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
+++ b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java
@@ -19,7 +19,8 @@
*/
package org.openremote.model.datapoint;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
+import org.hibernate.annotations.JdbcTypeCode;
+import org.hibernate.type.SqlTypes;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
@@ -50,8 +51,8 @@ public abstract class Datapoint implements Serializable {
@Column(name = "TIMESTAMP", updatable = false, nullable = false, columnDefinition = "TIMESTAMP")
protected Date timestamp;
- @Column(name = "VALUE", columnDefinition = "jsonb", nullable = false)
- @org.hibernate.annotations.Type(JsonBinaryType.class)
+ @Column(name = "VALUE", nullable = false)
+ @JdbcTypeCode(SqlTypes.JSON)
protected Object value;
public Datapoint() {
diff --git a/model/src/main/java/org/openremote/model/flow/EditorSettings.java b/model/src/main/java/org/openremote/model/flow/EditorSettings.java
index edcf97b7e..9a6ed4dc3 100644
--- a/model/src/main/java/org/openremote/model/flow/EditorSettings.java
+++ b/model/src/main/java/org/openremote/model/flow/EditorSettings.java
@@ -20,15 +20,11 @@
package org.openremote.model.flow;
-import com.vladmihalcea.hibernate.type.array.StringArrayType;
import jakarta.persistence.Column;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.validation.constraints.NotNull;
-import static org.openremote.model.Constants.PERSISTENCE_STRING_ARRAY_TYPE;
-
-
public class EditorSettings {
@NotNull
@@ -48,8 +44,7 @@ public class EditorSettings {
@Column(name = "EDITOR_POSITION_Y", nullable = false)
public double positionY;
- @Column(name = "EDITOR_COMPONENTS", columnDefinition = "text[]")
- @org.hibernate.annotations.Type(StringArrayType.class)
+ @Column(name = "EDITOR_COMPONENTS")
public String[] components;
diff --git a/model/src/main/java/org/openremote/model/flow/Node.java b/model/src/main/java/org/openremote/model/flow/Node.java
index eaf99dcf8..264ad5ed0 100644
--- a/model/src/main/java/org/openremote/model/flow/Node.java
+++ b/model/src/main/java/org/openremote/model/flow/Node.java
@@ -21,16 +21,12 @@
package org.openremote.model.flow;
import com.fasterxml.jackson.annotation.JsonIgnore;
-
-import com.vladmihalcea.hibernate.type.array.StringArrayType;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import jakarta.persistence.*;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.openremote.model.Constants.PERSISTENCE_STRING_ARRAY_TYPE;
-
@Entity
@Table(name = "NODE")
@@ -79,8 +75,7 @@ public class Node extends FlowObject {
@Column(name = "NODE_PROPERTIES", nullable = true, length = 1048576) // TODO 1MB?
public String properties;
- @Column(name = "PERSISTENT_PROPERTY_PATHS", nullable = true, columnDefinition = "text[]")
- @org.hibernate.annotations.Type(StringArrayType.class)
+ @Column(name = "PERSISTENT_PROPERTY_PATHS", nullable = true)
public String[] persistentPropertyPaths;
diff --git a/model/src/main/java/org/openremote/model/http/RequestParams.java b/model/src/main/java/org/openremote/model/http/RequestParams.java
index 6b69e04e4..3a677277a 100644
--- a/model/src/main/java/org/openremote/model/http/RequestParams.java
+++ b/model/src/main/java/org/openremote/model/http/RequestParams.java
@@ -27,6 +27,9 @@ import java.net.URI;
public class RequestParams {
+ @Context
+ public HttpHeaders headers;
+
@HeaderParam(HttpHeaders.AUTHORIZATION)
public String authorization;
diff --git a/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java
index 211baa1c1..43328f0c6 100644
--- a/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java
+++ b/model/src/main/java/org/openremote/model/notification/PushNotificationMessage.java
@@ -21,9 +21,9 @@ package org.openremote.model.notification;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import java.util.List;
+import java.util.Map;
public class PushNotificationMessage extends AbstractNotificationMessage {
@@ -44,7 +44,7 @@ public class PushNotificationMessage extends AbstractNotificationMessage {
protected String body;
protected PushNotificationAction action;
protected List<PushNotificationButton> buttons;
- protected ObjectNode data;
+ protected Map<String, Object> data;
protected MessagePriority priority;
protected TargetType targetType;
protected String target;
@@ -55,7 +55,7 @@ public class PushNotificationMessage extends AbstractNotificationMessage {
@JsonProperty("body") String body,
@JsonProperty("action") PushNotificationAction action,
@JsonProperty("buttons") List<PushNotificationButton> buttons,
- @JsonProperty("data") ObjectNode data,
+ @JsonProperty("data") Map<String, Object> data,
@JsonProperty("priority") MessagePriority priority,
@JsonProperty("targetType") TargetType targetType,
@JsonProperty("target") String target,
@@ -76,7 +76,7 @@ public class PushNotificationMessage extends AbstractNotificationMessage {
String body,
PushNotificationAction action,
List<PushNotificationButton> buttons,
- ObjectNode data) {
+ Map<String, Object> data) {
super(TYPE);
this.title = title;
this.body = body;
@@ -125,11 +125,11 @@ public class PushNotificationMessage extends AbstractNotificationMessage {
return this;
}
- public ObjectNode getData() {
+ public Map<String, Object> getData() {
return data;
}
- public PushNotificationMessage setData(ObjectNode data) {
+ public PushNotificationMessage setData(Map<String, Object> data) {
this.data = data;
return this;
}
diff --git a/model/src/main/java/org/openremote/model/notification/SentNotification.java b/model/src/main/java/org/openremote/model/notification/SentNotification.java
index 869a7de85..3eef3fcd2 100644
--- a/model/src/main/java/org/openremote/model/notification/SentNotification.java
+++ b/model/src/main/java/org/openremote/model/notification/SentNotification.java
@@ -19,12 +19,13 @@
*/
package org.openremote.model.notification;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
+import org.hibernate.annotations.JdbcTypeCode;
+import org.hibernate.type.SqlTypes;
+
import java.util.Date;
-import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
@Entity
@@ -61,8 +62,8 @@ public class SentNotification {
@Column(name = "SOURCE_ID", length = 43)
protected String sourceId;
- @Column(name = "MESSAGE", columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(JsonBinaryType.class)
+ @Column(name = "MESSAGE")
+ @JdbcTypeCode(SqlTypes.JSON)
protected AbstractNotificationMessage message;
@Column(name = "ERROR", length = 4096)
diff --git a/model/src/main/java/org/openremote/model/persistence/EpochMillisInstantType.java b/model/src/main/java/org/openremote/model/persistence/EpochMillisInstantType.java
deleted file mode 100644
index d02ea7510..000000000
--- a/model/src/main/java/org/openremote/model/persistence/EpochMillisInstantType.java
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright 2021, 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.persistence;
-
-import com.vladmihalcea.hibernate.type.MutableType;
-import com.vladmihalcea.hibernate.type.util.Configuration;
-import org.hibernate.type.descriptor.java.InstantJavaType;
-import org.hibernate.type.descriptor.jdbc.BigIntJdbcType;
-
-import java.time.Instant;
-
-public class EpochMillisInstantType extends MutableType<Instant, BigIntJdbcType, InstantJavaType> {
-
- public static final String TYPE_NAME = "epoch-millis-instant";
-
- public EpochMillisInstantType() {
- super(
- Instant.class,
- BigIntJdbcType.INSTANCE,
- InstantJavaType.INSTANCE
- );
- }
-
- public EpochMillisInstantType(Configuration configuration) {
- super(
- Instant.class,
- BigIntJdbcType.INSTANCE,
- InstantJavaType.INSTANCE,
- configuration
- );
- }
-
- public EpochMillisInstantType(org.hibernate.type.spi.TypeBootstrapContext typeBootstrapContext) {
- this(new Configuration(typeBootstrapContext.getConfigurationSettings()));
- }
-
- public String getName() {
- return TYPE_NAME;
- }
-}
diff --git a/model/src/main/java/org/openremote/model/persistence/InstantEpochConverter.java b/model/src/main/java/org/openremote/model/persistence/InstantEpochConverter.java
new file mode 100644
index 000000000..24d1b38f5
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/persistence/InstantEpochConverter.java
@@ -0,0 +1,17 @@
+package org.openremote.model.persistence;
+
+import jakarta.persistence.AttributeConverter;
+
+import java.time.Instant;
+
+public class InstantEpochConverter implements AttributeConverter<Instant, Long> {
+ @Override
+ public Long convertToDatabaseColumn(Instant attribute) {
+ return attribute != null ? attribute.toEpochMilli() : 0;
+ }
+
+ @Override
+ public Instant convertToEntityAttribute(Long dbData) {
+ return dbData != null ? Instant.ofEpochMilli(dbData) : null;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/protocol/ProtocolUtil.java b/model/src/main/java/org/openremote/model/protocol/ProtocolUtil.java
index d712ff43a..9e2683ed8 100644
--- a/model/src/main/java/org/openremote/model/protocol/ProtocolUtil.java
+++ b/model/src/main/java/org/openremote/model/protocol/ProtocolUtil.java
@@ -19,8 +19,6 @@
*/
package org.openremote.model.protocol;
-import com.fasterxml.jackson.databind.node.JsonNodeType;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.codec.binary.BinaryCodec;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.ArrayUtils;
@@ -39,6 +37,7 @@ import org.openremote.model.value.ValueFilter;
import org.openremote.model.value.ValueType;
import java.util.Locale;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
@@ -96,7 +95,7 @@ public final class ProtocolUtil {
Pair<Boolean, Object> ignoreAndConvertedValue;
// Check if attribute type is executable
- if (attribute.getType().equals(ValueType.EXECUTION_STATUS)) {
+ if (ValueType.EXECUTION_STATUS.equals(attribute.getType())) {
AttributeExecuteStatus status = ValueUtil.getValueCoerced(value, AttributeExecuteStatus.class).orElse(null);
if (status == AttributeExecuteStatus.REQUEST_START && writeValue != null) {
@@ -174,7 +173,7 @@ public final class ProtocolUtil {
}
// built in value conversion
- Class<?> toType = attribute.getType().getType();
+ Class<?> toType = attribute.getTypeClass();
Class<?> fromType = valRef.get().getClass();
if (toType != fromType) {
@@ -192,7 +191,7 @@ public final class ProtocolUtil {
}
@SuppressWarnings("unchecked")
- public static Pair<Boolean, Object> applyValueConverter(Object value, ObjectNode converter) {
+ public static Pair<Boolean, Object> applyValueConverter(Object value, Map<String, Object> converter) {
if (converter == null) {
return new Pair<>(false, value);
@@ -201,23 +200,23 @@ public final class ProtocolUtil {
String converterKey = ValueUtil.getValueCoerced(value, String.class).map(str -> str.toUpperCase(Locale.ROOT)).orElse(NULL_LITERAL.toUpperCase());
return Optional.ofNullable(converter.get(converterKey))
- .map(node -> {
- if (node.getNodeType() == JsonNodeType.STRING) {
- if ("@IGNORE".equalsIgnoreCase(node.textValue())) {
+ .map(converterValue -> {
+ if (converterValue instanceof String convertValueStr) {
+ if ("@IGNORE".equalsIgnoreCase(convertValueStr)) {
return new Pair<>(true, null);
}
- if ("@NULL".equalsIgnoreCase(node.textValue())) {
+ if ("@NULL".equalsIgnoreCase(convertValueStr)) {
return new Pair<>(false, null);
}
}
- return new Pair<Boolean, Object>(false, node);
+ return new Pair<>(false, converterValue);
})
.orElse((Pair<Boolean, Object>) Optional.ofNullable(converter.get("*"))
- .map(node -> {
- if (node.getNodeType() == JsonNodeType.STRING) {
- if (AttributeLink.ConverterType.NEGATE.getValue().equals(node.textValue())) {
+ .map(converterValue -> {
+ if (converterValue instanceof String converterValueStr) {
+ if (AttributeLink.ConverterType.NEGATE.getValue().equals(converterValueStr)) {
if (ValueUtil.isNumber(value.getClass())) {
return new Pair<>(false, (ValueUtil.getValueCoerced(value, Double.class).orElse(0D) * -1));
}
@@ -226,7 +225,7 @@ public final class ProtocolUtil {
}
}
}
- return new Pair<Boolean, Object>(false, node);
+ return new Pair<>(false, converterValue);
})
.orElse(new Pair<>(true, value)));
}
diff --git a/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java b/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
index d5e0b2490..6d74886c7 100644
--- a/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
+++ b/model/src/main/java/org/openremote/model/provisioning/ProvisioningConfig.java
@@ -23,7 +23,6 @@ import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
-import com.vladmihalcea.hibernate.type.array.StringArrayType;
import jakarta.persistence.*;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
@@ -84,8 +83,7 @@ public abstract class ProvisioningConfig<T, U extends ProvisioningConfig<T, U>>
@Column(name = "RESTRICTED_USER", nullable = false)
protected boolean restrictedUser;
- @Column(name = "ROLES", columnDefinition = "client_role[]")
- @org.hibernate.annotations.Type(StringArrayType.class)
+ @Column(name = "ROLES")
@Enumerated(EnumType.STRING)
protected ClientRole[] userRoles;
diff --git a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
index 9e733c368..0e6425d48 100644
--- a/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
+++ b/model/src/main/java/org/openremote/model/provisioning/X509ProvisioningConfig.java
@@ -20,18 +20,17 @@
package org.openremote.model.provisioning;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
-import org.openremote.model.util.TextUtil;
-
import jakarta.persistence.Column;
import jakarta.persistence.DiscriminatorValue;
import jakarta.persistence.Entity;
import jakarta.persistence.Transient;
+import org.hibernate.annotations.JdbcTypeCode;
+import org.hibernate.type.SqlTypes;
+import org.openremote.model.util.TextUtil;
+
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
-import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;
-
@Entity
@DiscriminatorValue("x509")
public class X509ProvisioningConfig extends ProvisioningConfig<X509ProvisioningData, X509ProvisioningConfig> {
@@ -44,8 +43,8 @@ public class X509ProvisioningConfig extends ProvisioningConfig<X509ProvisioningD
@Transient
boolean valid = true;
- @Column(name = DATA_PROPERTY_NAME, columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(JsonBinaryType.class)
+ @Column(name = DATA_PROPERTY_NAME)
+ @JdbcTypeCode(SqlTypes.JSON)
protected X509ProvisioningData data;
protected X509ProvisioningConfig() {}
diff --git a/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
index 4affddf7e..b8914f983 100644
--- a/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
+++ b/model/src/main/java/org/openremote/model/query/filter/DateTimePredicate.java
@@ -101,14 +101,14 @@ public class DateTimePredicate extends ValuePredicate {
if (TimeUtil.isTimeDuration(value)) {
from = currentMillis + TimeUtil.parseTimeDuration(value);
} else {
- from = TimeUtil.parseTimeIso8601(value);
+ from = TimeUtil.parseTimeIso8601(value).toEpochMilli();
}
if (operator == AssetQuery.Operator.BETWEEN) {
if (TimeUtil.isTimeDuration(rangeValue)) {
to = currentMillis + TimeUtil.parseTimeDuration(rangeValue);
} else {
- to = TimeUtil.parseTimeIso8601(rangeValue);
+ to = TimeUtil.parseTimeIso8601(rangeValue).toEpochMilli();
}
}
} catch (IllegalArgumentException e) {
diff --git a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
index fed4ae759..7071a86a0 100644
--- a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
@@ -19,15 +19,14 @@
*/
package org.openremote.model.rules;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.hibernate.annotations.Formula;
-import org.openremote.model.attribute.MetaMap;
-import org.openremote.model.calendar.CalendarEvent;
-
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
+import org.hibernate.annotations.Formula;
+import org.openremote.model.calendar.CalendarEvent;
+
import java.util.Date;
+import java.util.Map;
/**
* Rules that can only be triggered by asset modifications in a particular
@@ -131,7 +130,7 @@ public class AssetRuleset extends Ruleset {
}
@Override
- public AssetRuleset setMeta(ObjectNode meta) {
+ public AssetRuleset setMeta(Map<String, Object> meta) {
super.setMeta(meta);
return this;
}
diff --git a/model/src/main/java/org/openremote/model/rules/AssetState.java b/model/src/main/java/org/openremote/model/rules/AssetState.java
index ca207842d..b7f7dad41 100644
--- a/model/src/main/java/org/openremote/model/rules/AssetState.java
+++ b/model/src/main/java/org/openremote/model/rules/AssetState.java
@@ -20,12 +20,12 @@
package org.openremote.model.rules;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.MetaMap;
+import org.openremote.model.util.TsIgnore;
import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.*;
@@ -40,13 +40,14 @@ import java.util.Optional;
* are equal if they have the same asset ID and attribute name (the same attribute
* reference).
*/
+@TsIgnore
public class AssetState<T> implements Comparable<AssetState<?>>, NameValueHolder<T>, MetaHolder {
- @JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
+ @JsonProperty(value = "name")
final protected String attributeName;
- @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonProperty(value = "type")
+ @JsonSerialize(converter = ValueDescriptor.NameHolderToStringConverter.class)
final protected ValueDescriptor<T> attributeValueType;
final protected T value;
@@ -81,7 +82,7 @@ public class AssetState<T> implements Comparable<AssetState<?>>, NameValueHolder
this.value = attribute.getValue().orElse(null);
this.timestamp = attribute.getTimestamp().orElse(-1L);
this.source = source;
- this.oldValue = asset.getAttribute(attributeName, attribute.getType().getType()).flatMap(Attribute::getValue).orElse(null);
+ this.oldValue = asset.<T>getAttribute(attributeName).flatMap(Attribute::getValue).orElse(null);
this.oldValueTimestamp = asset.getAttributes().get(attributeName).flatMap(Attribute::getTimestamp).orElse(-1L);
this.id = asset.getId();
this.assetName = asset.getName();
@@ -98,20 +99,22 @@ public class AssetState<T> implements Comparable<AssetState<?>>, NameValueHolder
return attributeName;
}
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
@Override
public ValueDescriptor<T> getType() {
return attributeValueType;
}
- @JsonProperty
+ @Override
+ public Class<?> getTypeClass() {
+ return getType() != null ? getType().getType() : Object.class;
+ }
+
public Optional<T> getValue() {
return Optional.ofNullable(value);
}
@Override
- public <U> Optional<U> getValueAs(Class<U> valueType) {
+ public <U> Optional<U> getValue(Class<U> valueType) {
return ValueUtil.getValueCoerced(value, valueType);
}
diff --git a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
index a883bf44a..3f0d52bd4 100644
--- a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
@@ -19,13 +19,12 @@
*/
package org.openremote.model.rules;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.openremote.model.attribute.MetaMap;
-import org.openremote.model.calendar.CalendarEvent;
-
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
+import org.openremote.model.calendar.CalendarEvent;
+
import java.util.Date;
+import java.util.Map;
/**
* Rules that apply to all realms and assets, for the whole system.
@@ -92,7 +91,7 @@ public class GlobalRuleset extends Ruleset {
}
@Override
- public GlobalRuleset setMeta(ObjectNode meta) {
+ public GlobalRuleset setMeta(Map<String, Object> meta) {
super.setMeta(meta);
return this;
}
diff --git a/model/src/main/java/org/openremote/model/rules/RealmRuleset.java b/model/src/main/java/org/openremote/model/rules/RealmRuleset.java
index bab9e2b2f..ee95579a5 100644
--- a/model/src/main/java/org/openremote/model/rules/RealmRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/RealmRuleset.java
@@ -19,14 +19,13 @@
*/
package org.openremote.model.rules;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.openremote.model.attribute.MetaMap;
-import org.openremote.model.calendar.CalendarEvent;
-
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Table;
+import org.openremote.model.calendar.CalendarEvent;
+
import java.util.Date;
+import java.util.Map;
/**
* Rules that can only be triggered by asset modifications in a particular
@@ -118,7 +117,7 @@ public class RealmRuleset extends Ruleset {
}
@Override
- public RealmRuleset setMeta(ObjectNode meta) {
+ public RealmRuleset setMeta(Map<String, Object> meta) {
super.setMeta(meta);
return this;
}
diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.java
index e496a272b..f9a99d68c 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -22,19 +22,19 @@ package org.openremote.model.rules;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.fasterxml.jackson.databind.node.BooleanNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
-import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
-import org.openremote.model.calendar.CalendarEvent;
-import org.openremote.model.util.ValueUtil;
-
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
+import org.hibernate.annotations.JdbcTypeCode;
+import org.hibernate.type.SqlTypes;
+import org.openremote.model.calendar.CalendarEvent;
+import org.openremote.model.util.ValueUtil;
+
import java.util.Date;
+import java.util.HashMap;
+import java.util.Map;
import java.util.Optional;
-import static org.openremote.model.Constants.PERSISTENCE_JSON_VALUE_TYPE;
import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
/**
@@ -99,9 +99,9 @@ public abstract class Ruleset {
@Column(name = "RULES_LANG", nullable = false)
protected Lang lang = Lang.GROOVY;
- @Column(name = "META", columnDefinition = "jsonb")
- @org.hibernate.annotations.Type(JsonBinaryType.class)
- protected ObjectNode meta;
+ @Column(name = "META")
+ @JdbcTypeCode(SqlTypes.JSON)
+ protected Map<String, Object> meta;
@Transient
protected RulesetStatus status;
@@ -202,14 +202,14 @@ public abstract class Ruleset {
return this;
}
- public ObjectNode getMeta() {
+ public Map<String, Object> getMeta() {
if (meta == null) {
- meta = ValueUtil.createJsonObject();
+ meta = new HashMap<>();
}
return meta;
}
- public Ruleset setMeta(ObjectNode meta) {
+ public Ruleset setMeta(Map<String, Object> meta) {
this.meta = meta;
return this;
}
@@ -233,41 +233,41 @@ public abstract class Ruleset {
}
public boolean isContinueOnError() {
- return Optional.ofNullable(getMeta().get(CONTINUE_ON_ERROR)).map(node -> node.asBoolean(true)).orElse(true);
+ return Optional.ofNullable(getMeta().get(CONTINUE_ON_ERROR)).flatMap(ValueUtil::getBoolean).orElse(true);
}
public Ruleset setContinueOnError(boolean continueOnError) {
- getMeta().set(CONTINUE_ON_ERROR, BooleanNode.valueOf(continueOnError));
+ getMeta().put(CONTINUE_ON_ERROR, continueOnError);
return this;
}
@JsonIgnore
public CalendarEvent getValidity() {
- return Optional.ofNullable(getMeta().get(VALIDITY)).map(node -> ValueUtil.convert(node, CalendarEvent.class)).orElse(null);
+ return Optional.ofNullable(getMeta().get(VALIDITY)).map(calEvent -> ValueUtil.convert(calEvent, CalendarEvent.class)).orElse(null);
}
@JsonIgnore
public Ruleset setValidity(CalendarEvent calendarEvent) {
- getMeta().set(VALIDITY, ValueUtil.getValue(calendarEvent, ObjectNode.class, true).orElse(null));
+ getMeta().put(VALIDITY, calendarEvent);
return this;
}
// TODO: Unify triggers for rulesets
public boolean isTriggerOnPredictedData() {
- return Optional.ofNullable(getMeta().get(TRIGGER_ON_PREDICTED_DATA)).map(node -> node.asBoolean(false)).orElse(false);
+ return Optional.ofNullable(getMeta().get(TRIGGER_ON_PREDICTED_DATA)).flatMap(ValueUtil::getBoolean).orElse(false);
}
public Ruleset setTriggerOnPredictedData(boolean triggerOnPredictedData) {
- getMeta().set(TRIGGER_ON_PREDICTED_DATA, BooleanNode.valueOf(triggerOnPredictedData));
+ getMeta().put(TRIGGER_ON_PREDICTED_DATA, triggerOnPredictedData);
return this;
}
public boolean isShowOnList() {
- return Optional.ofNullable(getMeta().get(SHOW_ON_LIST)).map(node -> node.asBoolean(false)).orElse(false);
+ return Optional.ofNullable(getMeta().get(SHOW_ON_LIST)).flatMap(ValueUtil::getBoolean).orElse(false);
}
public Ruleset setShowOnList(boolean showOn) {
- getMeta().set(SHOW_ON_LIST, BooleanNode.valueOf(showOn));
+ getMeta().put(SHOW_ON_LIST, showOn);
return this;
}
}
diff --git a/model/src/main/java/org/openremote/model/security/ClientRole.java b/model/src/main/java/org/openremote/model/security/ClientRole.java
index 395b7734f..44d1f7d4a 100644
--- a/model/src/main/java/org/openremote/model/security/ClientRole.java
+++ b/model/src/main/java/org/openremote/model/security/ClientRole.java
@@ -23,10 +23,8 @@ import com.fasterxml.jackson.annotation.JsonValue;
import org.keycloak.representations.idm.RoleRepresentation;
import org.openremote.model.Constants;
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
+import java.util.stream.Collectors;
/**
* Roles available for our client application on Keycloak.
@@ -77,13 +75,10 @@ public enum ClientRole {
});
// Only individual roles, not composites
- public static final Set<String> ALL_ROLES = new HashSet<String>() {{
- for (ClientRole clientRole : values()) {
- if (clientRole.composites == null) {
- add(clientRole.value);
- }
- }
- }};
+ public static final Set<String> ALL_ROLES = Arrays.stream(values())
+ .filter(r -> r.composites == null)
+ .map(ClientRole::getValue)
+ .collect(Collectors.toSet());
final protected String value;
final protected String description;
diff --git a/model/src/main/java/org/openremote/model/security/Realm.java b/model/src/main/java/org/openremote/model/security/Realm.java
index 421160ea0..a9400fd32 100644
--- a/model/src/main/java/org/openremote/model/security/Realm.java
+++ b/model/src/main/java/org/openremote/model/security/Realm.java
@@ -276,7 +276,7 @@ public class Realm {
@JsonIgnore
public Set<RealmRole> getNormalisedRealmRoles() {
- Set<RealmRole> tempSet = new LinkedHashSet<>(getDefaultRealmRoles(getName()));
+ Set<RealmRole> tempSet = new HashSet<>(getDefaultRealmRoles(getName()));
if (realmRoles != null) {
tempSet.addAll(realmRoles);
}
diff --git a/model/src/main/java/org/openremote/model/security/User.java b/model/src/main/java/org/openremote/model/security/User.java
index 0c496b4cf..e7b0d8eca 100644
--- a/model/src/main/java/org/openremote/model/security/User.java
+++ b/model/src/main/java/org/openremote/model/security/User.java
@@ -29,7 +29,7 @@ import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import org.hibernate.annotations.Formula;
import org.hibernate.annotations.Subselect;
-import org.openremote.model.persistence.EpochMillisInstantType;
+import org.openremote.model.persistence.InstantEpochConverter;
import java.lang.reflect.Field;
import java.time.Instant;
@@ -78,7 +78,7 @@ public class User {
protected Boolean enabled;
@Column(name = "CREATED_TIMESTAMP")
- @org.hibernate.annotations.Type(EpochMillisInstantType.class)
+ @Convert(converter = InstantEpochConverter.class)
protected Instant createdOn;
@Formula("(SELECT C.SECRET FROM PUBLIC.CLIENT C WHERE C.ID = SERVICE_ACCOUNT_CLIENT_LINK)")
diff --git a/model/src/main/java/org/openremote/model/system/StatusResource.java b/model/src/main/java/org/openremote/model/system/StatusResource.java
index 5971bf8c5..2e19af0f9 100644
--- a/model/src/main/java/org/openremote/model/system/StatusResource.java
+++ b/model/src/main/java/org/openremote/model/system/StatusResource.java
@@ -19,14 +19,14 @@
*/
package org.openremote.model.system;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import io.swagger.v3.oas.annotations.tags.Tag;
-import org.openremote.model.Constants;
-
import jakarta.annotation.security.RolesAllowed;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
+import org.openremote.model.Constants;
+
+import java.util.Map;
import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
@@ -39,10 +39,10 @@ public interface StatusResource {
@GET
@Produces(APPLICATION_JSON)
@RolesAllowed({Constants.READ_ADMIN_ROLE})
- ObjectNode getHealthStatus();
+ Map<String, Object> getHealthStatus();
@Path("info")
@GET
@Produces(APPLICATION_JSON)
- ObjectNode getInfo();
+ Map<String, Object> getInfo();
}
diff --git a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
index 73b0eee2a..900696420 100644
--- a/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
+++ b/model/src/main/java/org/openremote/model/util/JSONSchemaUtil.java
@@ -30,9 +30,8 @@ import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaInject;
import java.util.Arrays;
import java.util.Collections;
-import java.util.HashMap;
+import java.util.Map;
import java.util.Optional;
-import java.util.function.Supplier;
public class JSONSchemaUtil {
@@ -115,15 +114,15 @@ public class JSONSchemaUtil {
Collections.emptyMap(),
false,
Collections.emptySet(),
- new HashMap<Class<?>, Class<?>>(){{
- put(Object.class, AnyType.class);
- put(ObjectNode.class, PatternPropertiesSimpleKeyAnyType.class);
- }},
- new HashMap<String, Supplier<JsonNode>>() {{
- put(SCHEMA_SUPPLIER_NAME_ANY_TYPE, () -> getSchemaType(true, TYPES_ALL));
- put(SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_ANY_KEY_ANY_TYPE, JSONSchemaUtil::getSchemaPatternPropertiesAnyKeyAnyType);
- put(SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_SIMPLE_KEY_ANY_TYPE, JSONSchemaUtil::getSchemaPatternPropertiesSimpleKeyAnyType);
- }},
+ Map.of(
+ Object.class, AnyType.class,
+ ObjectNode.class, PatternPropertiesSimpleKeyAnyType.class
+ ),
+ Map.of(
+ SCHEMA_SUPPLIER_NAME_ANY_TYPE, () -> getSchemaType(true, TYPES_ALL),
+ SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_ANY_KEY_ANY_TYPE, JSONSchemaUtil::getSchemaPatternPropertiesAnyKeyAnyType,
+ SCHEMA_SUPPLIER_NAME_PATTERN_PROPERTIES_SIMPLE_KEY_ANY_TYPE, JSONSchemaUtil::getSchemaPatternPropertiesSimpleKeyAnyType
+ ),
null,
false,
null,
diff --git a/model/src/main/java/org/openremote/model/util/TimeUtil.java b/model/src/main/java/org/openremote/model/util/TimeUtil.java
index b61ad9886..b67e0707a 100644
--- a/model/src/main/java/org/openremote/model/util/TimeUtil.java
+++ b/model/src/main/java/org/openremote/model/util/TimeUtil.java
@@ -24,7 +24,6 @@ import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
-import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.time.format.DateTimeFormatter.ISO_LOCAL_DATE;
@@ -38,6 +37,23 @@ public class TimeUtil {
// Simple syntax
protected static final Pattern SIMPLE = Pattern.compile(Constants.ISO8601_DURATION_REGEXP);
+ protected static final DateTimeFormatter formatter = new DateTimeFormatterBuilder()
+ .parseCaseInsensitive()
+ .append(ISO_LOCAL_DATE)
+ .optionalStart() // time made optional
+ .appendLiteral('T')
+ .append(ISO_LOCAL_TIME)
+ .optionalStart() // zone and offset made optional
+ .appendOffsetId()
+ .optionalStart()
+ .appendLiteral('[')
+ .parseCaseSensitive()
+ .appendZoneRegionId()
+ .appendLiteral(']')
+ .optionalEnd()
+ .optionalEnd()
+ .optionalEnd()
+ .toFormatter();
/**
* Parses the given time duration String and returns the corresponding number of milliseconds.
@@ -78,25 +94,7 @@ public class TimeUtil {
* Parses ISO8601 strings with optional time and/or offset; if no zone is provided then UTC is assumed if no
* time is provided then 00:00:00 is assumed.
*/
- public static long parseTimeIso8601(String datetime) {
- DateTimeFormatter formatter = new DateTimeFormatterBuilder()
- .parseCaseInsensitive()
- .append(ISO_LOCAL_DATE)
- .optionalStart() // time made optional
- .appendLiteral('T')
- .append(ISO_LOCAL_TIME)
- .optionalStart() // zone and offset made optional
- .appendOffsetId()
- .optionalStart()
- .appendLiteral('[')
- .parseCaseSensitive()
- .appendZoneRegionId()
- .appendLiteral(']')
- .optionalEnd()
- .optionalEnd()
- .optionalEnd()
- .toFormatter();
-
+ public static Instant parseTimeIso8601(CharSequence datetime) {
TemporalAccessor temporalAccessor = formatter.parseBest(datetime, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
ZonedDateTime zonedDateTime;
@@ -107,6 +105,6 @@ public class TimeUtil {
} else {
zonedDateTime = ((LocalDate) temporalAccessor).atStartOfDay(ZoneOffset.UTC);
}
- return zonedDateTime.toInstant().toEpochMilli();
+ return zonedDateTime.toInstant();
}
}
diff --git a/model/src/main/java/org/openremote/model/util/ValueUtil.java b/model/src/main/java/org/openremote/model/util/ValueUtil.java
index 3912d426e..e6b831826 100644
--- a/model/src/main/java/org/openremote/model/util/ValueUtil.java
+++ b/model/src/main/java/org/openremote/model/util/ValueUtil.java
@@ -23,18 +23,24 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.cfg.ConstructorDetector;
+import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.jsontype.NamedType;
-import com.fasterxml.jackson.databind.node.*;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.node.TextNode;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import com.kjetland.jackson.jsonSchema.JsonSchemaGenerator;
+import jakarta.persistence.Entity;
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.ConstraintViolation;
+import jakarta.validation.Validation;
+import jakarta.validation.Validator;
+import jakarta.validation.constraints.NotNull;
import org.hibernate.internal.util.SerializationHelper;
-import org.openremote.model.AssetModelProvider;
-import org.openremote.model.ModelDescriptor;
-import org.openremote.model.ModelDescriptors;
-import org.openremote.model.StandardModelProvider;
+import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;
+import org.openremote.model.*;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
import org.openremote.model.asset.AssetTypeInfo;
@@ -50,17 +56,14 @@ import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
-import jakarta.persistence.Entity;
-import jakarta.validation.ConstraintViolation;
-import jakarta.validation.Validation;
-import jakarta.validation.Validator;
-import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.lang.reflect.*;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.time.Instant;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
@@ -86,7 +89,18 @@ import static org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES;
public class ValueUtil {
/**
- * Copied from: https://puredanger.github.io/tech.puredanger.com/2006/11/29/writing-a-class-hierarchy-comparator/
+ * A {@link FunctionalInterface} for populating the {@link ConstraintViolation#getPropertyPath()} for the value being
+ * validated (e.g. for the value of an {@link Attribute} called 'customAttribute' the path provided should be
+ * attributes["customAttribute"].value
+ */
+ @TsIgnore
+ @FunctionalInterface
+ public interface ConstraintViolationPathProvider {
+ void accept(ConstraintValidatorContext.ConstraintViolationBuilder constraintViolationBuilder);
+ }
+
+ /**
+ * Copied from: <a href="https://puredanger.github.io/tech.puredanger.com/2006/11/29/writing-a-class-hierarchy-comparator/">https://puredanger.github.io/tech.puredanger.com/2006/11/29/writing-a-class-hierarchy-comparator</a>
*/
protected static class ClassHierarchyComparator implements Comparator<Class<?>> {
@@ -126,37 +140,46 @@ public class ValueUtil {
// Preload the Standard model provider so it takes priority over others
public static Logger LOG = SyslogCategory.getLogger(MODEL_AND_VALUES, ValueUtil.class);
- public static ObjectMapper JSON;
- protected static List<AssetModelProvider> assetModelProviders = new ArrayList<>(Collections.singletonList(new StandardModelProvider()));
- protected static Map<Class<? extends Asset<?>>, AssetTypeInfo> assetInfoMap;
- protected static Map<String, Class<? extends Asset<?>>> assetTypeMap;
- protected static Map<String, Class<? extends AgentLink<?>>> agentLinkMap;
- protected static List<MetaItemDescriptor<?>> metaItemDescriptors;
- protected static List<ValueDescriptor<?>> valueDescriptors;
+ public static ObjectMapper JSON = configureObjectMapper(new ObjectMapper());
+ protected static List<AssetModelProvider> assetModelProviders = new ArrayList<>();
+ protected static Map<String, AssetTypeInfo> assetInfoMap = new HashMap<>();
+ protected static Map<String, Class<? extends Asset<?>>> assetTypeMap = new HashMap<>();
+ protected static Map<String, Class<? extends AgentLink<?>>> agentTypeMap = new HashMap<>();
+ protected static Map<String, MetaItemDescriptor<?>> metaItemDescriptors = new HashMap<>();
+ protected static Map<String, ValueDescriptor<?>> valueDescriptors = new HashMap<>();
protected static Validator validator;
protected static JsonSchemaGenerator generator;
- static {
- // Find all service loader registered asset model providers
- ServiceLoader.load(AssetModelProvider.class).forEach(ValueUtil.assetModelProviders::add);
- initialise();
- }
-
public static ObjectMapper configureObjectMapper(ObjectMapper objectMapper) {
objectMapper
.setConstructorDetector(ConstructorDetector.DEFAULT)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false) // see https://github.com/FasterXML/jackson-databind/issues/1547
.configure(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
+ .configure(SerializationFeature.INDENT_OUTPUT, false)
.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)
.configure(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
+ .configure(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY, true)
+ .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, false)
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
- .registerModule(new ParameterNamesModule(JsonCreator.Mode.DEFAULT));
+ .registerModule(new ParameterNamesModule(JsonCreator.Mode.DEFAULT))
+ .registerModule(new SimpleModule()
+ .setDeserializerModifier(new BeanDeserializerModifier() {
+ @Override
+ public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
+ if (Asset.class.isAssignableFrom(beanDesc.getBeanClass())) {
+ return new Asset.AssetDeserializer((JsonDeserializer<Asset<?>>) deserializer, beanDesc.getBeanClass());
+ }
+ if (ValueDescriptor.class.isAssignableFrom(beanDesc.getBeanClass())) {
+ return new ValueDescriptor.ValueDescriptorDeserializer((JsonDeserializer<ValueDescriptor<?>>) deserializer);
+ }
+ return deserializer;
+ }}));
objectMapper.configOverride(Map.class)
.setInclude(JsonInclude.Value.construct(JsonInclude.Include.NON_NULL, JsonInclude.Include.NON_NULL));
@@ -170,12 +193,12 @@ public class ValueUtil {
public static final String NULL_LITERAL = "null";
- public static Optional<JsonNode> parse(String jsonString) {
+ public static Optional<Object> parse(String jsonString) {
if (TextUtil.isNullOrEmpty(jsonString) || NULL_LITERAL.equals(jsonString)) {
return Optional.empty();
}
try {
- return Optional.of(JSON.readTree(jsonString));
+ return Optional.of(JSON.readValue(jsonString, Object.class));
} catch (Exception e) {
LOG.log(Level.INFO, "Failed to parse JSON string: " + jsonString, e);
}
@@ -224,10 +247,9 @@ public class ValueUtil {
return Optional.empty();
}
- if (value instanceof Optional) {
- Optional opt = (Optional)value;
- if (!opt.isPresent()) {
- return opt;
+ if (value instanceof Optional opt) {
+ if (opt.isEmpty()) {
+ return Optional.empty();
}
value = opt.get();
}
@@ -236,7 +258,30 @@ public class ValueUtil {
return Optional.of((T) value);
}
- if (value instanceof String && !coerce) {
+ if (value instanceof CharSequence && String.class.isAssignableFrom(type)) {
+ return Optional.of((T) String.valueOf(value));
+ }
+
+ if (Instant.class.isAssignableFrom(type)) {
+ if (value instanceof Date dateValue) {
+ return Optional.of((T) dateValue.toInstant());
+ }
+ if (value instanceof Long longValue) {
+ return Optional.of((T) Instant.ofEpochMilli(longValue));
+ }
+ if (value instanceof Calendar calendarValue) {
+ return Optional.of((T) calendarValue.toInstant());
+ }
+ if (value instanceof CharSequence charSequence) {
+ try {
+ return Optional.of((T) TimeUtil.parseTimeIso8601(charSequence));
+ } catch (Exception e) {
+ LOG.info("Failed to parse char sequence as Instant: " + e.getMessage());
+ }
+ }
+ }
+
+ if (value instanceof CharSequence && !coerce) {
return Optional.empty();
}
@@ -259,7 +304,8 @@ public class ValueUtil {
return Optional.of((T) Short.valueOf(node.shortValue()));
}
}
- if (String.class == type) {
+ if (CharSequence.class.isAssignableFrom(type)) {
+
if (node.isTextual()) {
return Optional.of((T) node.asText());
}
@@ -375,18 +421,6 @@ public class ValueUtil {
return getValueCoerced(value, Long.class);
}
- public static Optional<ObjectNode> asJSONObject(Object value) {
- return getValue(value, ObjectNode.class);
- }
-
- public static Optional<ArrayNode> asJSONArray(Object value) {
- return getValue(value, ArrayNode.class);
- }
-
- public static ObjectNode createJsonObject() {
- return ValueUtil.JSON.createObjectNode();
- }
-
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
@@ -409,27 +443,34 @@ public class ValueUtil {
}
public static boolean isArray(Class<?> clazz) {
- return clazz.isArray() || clazz == ArrayNode.class;
+ return clazz.isArray();
}
public static boolean isBoolean(Class<?> clazz) {
- return clazz == Boolean.class || clazz == BooleanNode.class;
+ return clazz == Boolean.class;
}
public static boolean isNumber(Class<?> clazz) {
- return Number.class.isAssignableFrom(clazz) || NumericNode.class.isAssignableFrom(clazz);
+ return Number.class.isAssignableFrom(clazz);
}
public static boolean isString(Class<?> clazz) {
- return String.class.isAssignableFrom(clazz) || TextNode.class.isAssignableFrom(clazz) || BinaryNode.class.isAssignableFrom(clazz);
+ return CharSequence.class.isAssignableFrom(clazz);
+ }
+
+ public static boolean isMap(Class<?> clazz) {
+ return Map.class.isAssignableFrom(clazz);
+ }
+
+ public static boolean isCollection(Class<?> clazz) {
+ return Collection.class.isAssignableFrom(clazz);
}
public static boolean isObject(Class<?> clazz) {
- return !isArray(clazz) && !isBoolean(clazz) && !isNumber(clazz) && !isString(clazz);
+ return isMap(clazz) || (!isArray(clazz) && !isBoolean(clazz) && !isNumber(clazz) && !isString(clazz));
}
public static Class<?> getArrayClass(Class<?> componentType) throws ClassNotFoundException {
- ClassLoader classLoader = componentType.getClassLoader();
String name;
if (componentType.isArray()) {
// just add a leading "["
@@ -541,11 +582,11 @@ public class ValueUtil {
}
public static <T extends Asset<?>> Optional<AssetTypeInfo> getAssetInfo(Class<T> assetType) {
- return Optional.ofNullable(assetInfoMap.get(assetType));
+ return Optional.ofNullable(assetInfoMap.get(assetType.getSimpleName()));
}
public static Optional<AssetTypeInfo> getAssetInfo(String assetType) {
- return getAssetClass(assetType).map(assetClass -> assetInfoMap.get(assetClass));
+ return Optional.ofNullable(assetInfoMap.get(assetType));
}
// TODO: Implement ability to restrict which asset types are allowed to be added to a given parent type
@@ -571,8 +612,8 @@ public class ValueUtil {
.map(assetDescriptor -> assetDescriptor instanceof AgentDescriptor ? (AgentDescriptor<?, ?, ?>)assetDescriptor : null);
}
- public static MetaItemDescriptor<?>[] getMetaItemDescriptors() {
- return metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]);
+ public static Map<String, MetaItemDescriptor<?>> getMetaItemDescriptors() {
+ return metaItemDescriptors;
}
public static <T extends Asset<?>> Optional<MetaItemDescriptor<?>[]> getMetaItemDescriptors(Class<T> assetType) {
@@ -585,12 +626,11 @@ public class ValueUtil {
public static Optional<MetaItemDescriptor<?>> getMetaItemDescriptor(String name) {
if (TextUtil.isNullOrEmpty(name)) return Optional.empty();
-
- return metaItemDescriptors.stream().filter(mid -> mid.getName().equals(name)).findFirst();
+ return Optional.ofNullable(metaItemDescriptors.get(name));
}
- public static ValueDescriptor<?>[] getValueDescriptors() {
- return valueDescriptors.toArray(new ValueDescriptor<?>[0]);
+ public static Map<String, ValueDescriptor<?>> getValueDescriptors() {
+ return valueDescriptors;
}
public static <T extends Asset<?>> Optional<ValueDescriptor<?>[]> getValueDescriptors(Class<T> assetType) {
@@ -611,12 +651,11 @@ public class ValueUtil {
arrayDimensions++;
}
- String finalName = name;
int finalArrayDimensions = arrayDimensions;
- return valueDescriptors.stream().filter(vd -> vd.getName().equals(finalName)).findFirst().map(vd -> {
+ return Optional.ofNullable(valueDescriptors.get(name)).map(vd -> {
int dims = finalArrayDimensions;
while(dims > 0) {
- vd = vd.asArray();
+ vd = (ValueDescriptor) vd.asArray();
dims--;
}
return vd;
@@ -625,13 +664,13 @@ public class ValueUtil {
public static ValueDescriptor<?> getValueDescriptorForValue(Object value) {
if (value == null) {
- return ValueDescriptor.UNKNOWN;
+ return null;
}
Class<?> valueClass = value.getClass();
boolean isArray = valueClass.isArray();
valueClass = isArray ? valueClass.getComponentType() : valueClass;
- ValueDescriptor<?> valueDescriptor = ValueDescriptor.UNKNOWN;
+ ValueDescriptor<?> valueDescriptor = null;
if (valueClass == Boolean.class) valueDescriptor = ValueType.BOOLEAN;
else if (valueClass == String.class) valueDescriptor = ValueType.TEXT;
@@ -641,16 +680,31 @@ public class ValueUtil {
else if (valueClass == BigInteger.class) valueDescriptor = ValueType.BIG_INTEGER;
else if (valueClass == BigDecimal.class) valueDescriptor = ValueType.BIG_NUMBER;
else if (valueClass == Byte.class) valueDescriptor = ValueType.BYTE;
- else if (Map.class.isAssignableFrom(valueClass)) valueDescriptor = ValueType.JSON_OBJECT;
- return isArray ? valueDescriptor.asArray() : valueDescriptor;
+ return isArray && valueDescriptor != null ? valueDescriptor.asArray() : valueDescriptor;
}
public static List<AssetModelProvider> getModelProviders() {
return assetModelProviders;
}
- public static void initialise() throws IllegalStateException {
+ public static void initialise(Container container) throws IllegalStateException {
+ assetModelProviders.clear();
+
+ // Load in default model provider
+ assetModelProviders.add(new StandardModelProvider());
+
+ // Find all service loader registered asset model providers
+ ServiceLoader.load(AssetModelProvider.class).forEach(assetModelProviders::add);
+
+ if (container != null) {
+ // Look for any container services that implement model provider
+ assetModelProviders.addAll(Arrays.stream(container.getServices())
+ .filter(service -> service instanceof AssetModelProvider)
+ .map(service -> (AssetModelProvider) service)
+ .collect(Collectors.toSet()));
+ }
+
try {
doInitialise();
} catch (IllegalStateException e) {
@@ -663,21 +717,21 @@ public class ValueUtil {
* Initialise the asset model and throw an {@link IllegalStateException} exception if a problem is detected; this
* can be called by applications at startup to fail hard and fast if the asset model is un-usable
*/
- protected static void doInitialise() throws IllegalStateException {
- assetInfoMap = new HashMap<>();
- assetTypeMap = new HashMap<>();
- agentLinkMap = new HashMap<>();
- metaItemDescriptors = new ArrayList<>();
- valueDescriptors = new ArrayList<>();
+ static void doInitialise() throws IllegalStateException {
generator = null;
-
- // Provide basic Object Mapper and enhance once asset model is initialised
- JSON = configureObjectMapper(new ObjectMapper());
+ assetInfoMap.clear();
+ assetTypeMap.clear();
+ agentTypeMap.clear();
+ metaItemDescriptors.clear();
+ valueDescriptors.clear();
LOG.info("Initialising asset model...");
- Map<Class<? extends Asset<?>>, List<NameHolder>> assetDescriptorProviders = new TreeMap<>(new ClassHierarchyComparator());
+ Set<Class<? extends Asset<?>>> assetClasses = new TreeSet<>(new ClassHierarchyComparator());
+ Map<String, List<NameHolder>> assetDescriptorsMap = new HashMap<>();
+
//noinspection RedundantCast
- assetDescriptorProviders.put((Class<? extends Asset<?>>)(Class<?>)Asset.class, new ArrayList<>(getDescriptorFields(Asset.class)));
+ assetClasses.add((Class<? extends Asset<?>>)(Class<?>)Asset.class);
+ assetDescriptorsMap.put(Asset.class.getSimpleName(), new ArrayList<>(getDescriptorFields(Asset.class)));
getModelProviders().forEach(assetModelProvider -> {
LOG.fine("Processing asset model provider: " + assetModelProvider.getClass().getSimpleName());
@@ -685,118 +739,162 @@ public class ValueUtil {
if (assetModelProvider.useAutoScan()) {
- Set<Class<? extends Asset<?>>> assetClasses = getAssetClasses(assetModelProvider);
- LOG.fine("Found " + assetClasses.size() + " asset class(es)");
+ Set<Class<? extends Asset<?>>> providerAssetClasses = getAssetClasses(assetModelProvider);
+ LOG.fine("Found " + providerAssetClasses.size() + " asset class(es)");
- assetClasses.forEach(assetClass ->
- assetDescriptorProviders.computeIfAbsent(assetClass, aClass ->
- new ArrayList<>(getDescriptorFields(aClass))));
+ providerAssetClasses.forEach(assetClass -> {
+ assetClasses.add(assetClass);
+ assetDescriptorsMap.computeIfAbsent(assetClass.getSimpleName(), name ->
+ new ArrayList<>(getDescriptorFields(assetClass)));
+ });
ModelDescriptors modelDescriptors = assetModelProvider.getClass().getAnnotation(ModelDescriptors.class);
if (modelDescriptors != null) {
for (ModelDescriptor modelDescriptor : modelDescriptors.value()) {
Class<? extends Asset<?>> assetClass = (Class<? extends Asset<?>>)modelDescriptor.assetType();
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ assetClasses.add(assetClass);
+ assetDescriptorsMap.compute(assetClass.getSimpleName(), (name, list) -> {
if (list == null) {
list = new ArrayList<>();
}
- list.addAll(getDescriptorFields(modelDescriptor.provider()));
+ List<NameHolder> descriptors = getDescriptorFields(modelDescriptor.provider());
+ list.addAll(descriptors);
+ // Push value descriptors straight in so they are accessible to asset model providers
+ descriptors.forEach(d -> {
+ if (d instanceof ValueDescriptor vd) {
+ ValueUtil.valueDescriptors.put(vd.getName(), vd);
+ }
+ });
return list;
});
}
}
}
- if (assetModelProvider.getAssetDescriptors() != null) {
- for (AssetDescriptor<?> assetDescriptor : assetModelProvider.getAssetDescriptors()) {
- Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
-
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ Map<String, Collection<ValueDescriptor<?>>> valueDescriptors1 = assetModelProvider.getValueDescriptors();
+ if (valueDescriptors1 != null) {
+ AtomicInteger count = new AtomicInteger(0);
+ valueDescriptors1.forEach((name, valueDescriptors) -> {
+ assetClasses.stream().filter(c -> c.getSimpleName().equals(name)).findFirst().ifPresent(assetClasses::add);
+ assetDescriptorsMap.compute(name, (n, list) -> {
if (list == null) {
list = new ArrayList<>();
}
- list.add(assetDescriptor);
+ list.addAll(valueDescriptors);
+ count.addAndGet(valueDescriptors.size());
+ // Push value descriptors straight in so they are accessible to asset model providers
+ valueDescriptors.forEach(vd -> ValueUtil.valueDescriptors.put(vd.getName(), vd));
return list;
});
- }
+ });
+ LOG.fine("Found " + count.get() + " value descriptors");
}
- if (assetModelProvider.getAttributeDescriptors() != null) {
- assetModelProvider.getAttributeDescriptors().forEach((assetClass, attributeDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ Map<String, Collection<MetaItemDescriptor<?>>> metaItemDescriptors = assetModelProvider.getMetaItemDescriptors();
+ if (metaItemDescriptors != null) {
+ AtomicInteger count = new AtomicInteger(0);
+ metaItemDescriptors.forEach((name, metaDescriptors) -> {
+ assetClasses.stream().filter(c -> c.getSimpleName().equals(name)).findFirst().ifPresent(assetClasses::add);
+ assetDescriptorsMap.compute(name, (n, list) -> {
if (list == null) {
list = new ArrayList<>();
}
- list.addAll(attributeDescriptors);
+ list.addAll(metaDescriptors);
+ count.addAndGet(metaDescriptors.size());
return list;
- }));
+ });
+ });
+ LOG.fine("Found " + count.get() + " meta item descriptors");
}
- if (assetModelProvider.getMetaItemDescriptors() != null) {
- assetModelProvider.getMetaItemDescriptors().forEach((assetClass, metaDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ Map<String, Collection<AttributeDescriptor<?>>> attributeDescriptors1 = assetModelProvider.getAttributeDescriptors();
+ if (attributeDescriptors1 != null) {
+ AtomicInteger count = new AtomicInteger(0);
+ attributeDescriptors1.forEach((name, attributeDescriptors) -> {
+ assetClasses.stream().filter(c -> c.getSimpleName().equals(name)).findFirst().ifPresent(assetClasses::add);
+ assetDescriptorsMap.compute(name, (n, list) -> {
if (list == null) {
list = new ArrayList<>();
}
- list.addAll(metaDescriptors);
+ list.addAll(attributeDescriptors);
+ count.addAndGet(attributeDescriptors.size());
return list;
- }));
+ });
+ });
+ LOG.fine("Found " + count.get() + " attribute descriptors");
}
- if (assetModelProvider.getValueDescriptors() != null) {
- assetModelProvider.getValueDescriptors().forEach((assetClass, valueDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ AssetDescriptor<?>[] assetDescriptors = assetModelProvider.getAssetDescriptors();
+ if (assetDescriptors != null) {
+ LOG.fine("Found " + assetDescriptors.length + " asset descriptors");
+ for (AssetDescriptor<?> assetDescriptor : assetDescriptors) {
+ Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
+ if (assetClass != null) {
+ assetClasses.add(assetClass);
+ }
+ assetDescriptorsMap.compute(assetDescriptor.getName(), (name, list) -> {
if (list == null) {
list = new ArrayList<>();
}
- list.addAll(valueDescriptors);
+ list.add(assetDescriptor);
return list;
- }));
+ });
+ }
}
});
// Build each asset info checking that no conflicts occur
- Map<Class<? extends Asset<?>>, List<NameHolder>> copy = new HashMap<>(assetDescriptorProviders);
- assetDescriptorProviders.forEach((assetClass, descriptors) -> {
+ Map<String, List<NameHolder>> copy = new HashMap<>(assetDescriptorsMap);
+ assetDescriptorsMap.forEach((name, descriptors) -> {
+ Class<? extends Asset<?>> assetClass = assetClasses.stream().filter(c -> c.getSimpleName().equals(name)).findFirst().orElse(null);
- // Skip abstract classes as a start point - they should be in the class hierarchy of concrete class
- if (!Modifier.isAbstract(assetClass.getModifiers())) {
-
- AssetTypeInfo assetInfo = buildAssetInfo(assetClass, copy);
+ if (assetClass == null) {
+ AssetTypeInfo assetInfo = buildAssetInfoFromName(name, copy);
if (assetInfo != null) {
- assetInfoMap.put(assetClass, assetInfo);
- assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
+ assetInfoMap.put(name, assetInfo);
+ }
+ } else {
+ // Skip abstract classes as a start point - they should be in the class hierarchy of concrete class
+ if (!Modifier.isAbstract(assetClass.getModifiers())) {
+
+ AssetTypeInfo assetInfo = buildAssetInfoFromClass(assetClass, copy);
- if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor<?, ?, ?> agentDescriptor) {
- String agentLinkName = agentDescriptor.getAgentLinkClass().getSimpleName();
- if (agentLinkMap.containsKey(agentLinkName) && agentLinkMap.get(agentLinkName) != agentDescriptor.getAgentLinkClass()) {
- throw new IllegalStateException("AgentLink simple class name must be unique, duplicate found for: " + agentDescriptor.getAgentLinkClass());
+ if (assetInfo != null) {
+ assetInfoMap.put(assetClass.getSimpleName(), assetInfo);
+ assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
+
+ if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor<?, ?, ?> agentDescriptor) {
+ String agentLinkName = agentDescriptor.getAgentLinkClass().getSimpleName();
+ if (agentTypeMap.containsKey(agentLinkName) && agentTypeMap.get(agentLinkName) != agentDescriptor.getAgentLinkClass()) {
+ throw new IllegalStateException("AgentLink simple class name must be unique, duplicate found for: " + agentDescriptor.getAgentLinkClass());
+ }
+ agentTypeMap.put(agentLinkName, agentDescriptor.getAgentLinkClass());
}
- agentLinkMap.put(agentLinkName, agentDescriptor.getAgentLinkClass());
}
}
}
});
- // Check each value type implements serializable interface
- List<ValueDescriptor<?>> nonSerializableValueDescriptors = new ArrayList<>();
- valueDescriptors.forEach(vd -> {
- if (!Serializable.class.isAssignableFrom(vd.getType())) {
- nonSerializableValueDescriptors.add(vd);
- }
- });
-
- if (!nonSerializableValueDescriptors.isEmpty()) {
- String vds = nonSerializableValueDescriptors.stream().map(ValueDescriptor::toString).collect(Collectors.joining(",\n"));
- throw new IllegalStateException("One or more value types do not implement java.io.Serializable: " + vds);
- }
+ // RT: Think this as needed for hibernate-types lib that is no longer used
+// // Check each value type implements serializable interface
+// List<ValueDescriptor<?>> nonSerializableValueDescriptors = new ArrayList<>();
+// valueDescriptors.values().forEach(vd -> {
+// if (!Serializable.class.isAssignableFrom(vd.getType())) {
+// nonSerializableValueDescriptors.add(vd);
+// }
+// });
+//
+// if (!nonSerializableValueDescriptors.isEmpty()) {
+// String vds = nonSerializableValueDescriptors.stream().map(ValueDescriptor::toString).collect(Collectors.joining(",\n"));
+// throw new IllegalStateException("One or more value types do not implement java.io.Serializable: " + vds);
+// }
// Call on finished on each provider
assetModelProviders.forEach(AssetModelProvider::onAssetModelFinished);
@@ -848,6 +946,62 @@ public class ValueUtil {
return validator;
}
+ /**
+ * Evaluate the validity of a value dynamically by extracting {@link ValueConstraint}s from the supplied parameters;
+ * each found constraint is then evaluated against the value supplied to the function.
+ * <p>
+ * Unfortunately JSR-380 can't be used (even Hibernate validator's programmatic API) because validators are type
+ * centric but here the type (e.g. {@link Attribute} or {@link org.openremote.model.rules.AssetState}) is fixed
+ * but the constraints to be applied are dynamic, would be nice if there was a solution to this problem but this
+ * works for now.
+ */
+ // TODO: Implement some sort of caching if performance warrants it
+ public static boolean validateValue(AttributeDescriptor<?> attributeDescriptor, ValueDescriptor<?> valueDescriptor, MetaHolder metaHolder, Instant now, ConstraintValidatorContext context, ConstraintViolationPathProvider constraintBuilderProvider, Object value) {
+ boolean valid = true;
+
+ if (valueDescriptor != null && valueDescriptor.getConstraints() != null) {
+ if (Arrays.stream(valueDescriptor.getConstraints()).map(constraint -> validateValueConstraint(context, constraintBuilderProvider, now, constraint, value)).anyMatch(constraintValid -> !constraintValid)) {
+ valid = false;
+ }
+ }
+ if (attributeDescriptor != null && attributeDescriptor.getConstraints() != null) {
+ if (Arrays.stream(attributeDescriptor.getConstraints()).map(constraint -> validateValueConstraint(context, constraintBuilderProvider, now, constraint, value)).anyMatch(constraintValid -> !constraintValid)) {
+ valid = false;
+ }
+ }
+ if (attributeDescriptor != null && attributeDescriptor.getMeta() != null) {
+ if (attributeDescriptor.getMeta().get(MetaItemType.CONSTRAINTS).flatMap(ValueHolder::getValue).map(constraints ->
+ Arrays.stream(constraints).map(constraint -> validateValueConstraint(context, constraintBuilderProvider, now, constraint, value)).anyMatch(constraintValid -> !constraintValid)
+ ).orElse(false)) {
+ valid = false;
+ }
+ }
+ if (metaHolder != null && metaHolder.getMeta() != null) {
+ if (metaHolder.getMeta().get(MetaItemType.CONSTRAINTS).flatMap(ValueHolder::getValue).map(constraints ->
+ Arrays.stream(constraints).map(constraint -> validateValueConstraint(context, constraintBuilderProvider, now, constraint, value)).anyMatch(constraintValid -> !constraintValid)
+ ).orElse(false)) {
+ valid = false;
+ }
+ }
+ return valid;
+ }
+
+ public static boolean validateValueConstraint(ConstraintValidatorContext context, ConstraintViolationPathProvider constraintViolationPathProvider, Instant now, ValueConstraint valueConstraint, Object value) {
+ if (!valueConstraint.evaluate(value, now)) {
+ if (context instanceof HibernateConstraintValidatorContext hibernateContext) {
+ Map<String, Object> messageParams = valueConstraint.getParameters();
+ if (messageParams != null) {
+ messageParams.forEach(hibernateContext::addMessageParameter);
+ }
+ }
+ ConstraintValidatorContext.ConstraintViolationBuilder constraintBuilder = context.buildConstraintViolationWithTemplate(valueConstraint.getMessage().orElse(ValueConstraint.VALUE_CONSTRAINT_INVALID));
+ constraintViolationPathProvider.accept(constraintBuilder);
+ constraintBuilder.addConstraintViolation();
+ return false;
+ }
+ return true;
+ }
+
/**
* Returns the schema for the specified type
*/
@@ -861,7 +1015,7 @@ public class ValueUtil {
public static void initialiseAssetAttributes(Asset<?> asset) throws IllegalStateException {
AssetTypeInfo assetInfo = getAssetInfo(asset.getType()).orElseThrow(() -> new IllegalStateException("Cannot get asset model info for requested asset type: " + asset.getType()));
asset.getAttributes().addOrReplace(
- Arrays.stream(assetInfo.getAttributeDescriptors())
+ assetInfo.getAttributeDescriptors().values().stream()
.filter(attributeDescriptor -> !attributeDescriptor.isOptional())
.map(Attribute::new)
.collect(Collectors.toList())
@@ -894,43 +1048,55 @@ public class ValueUtil {
}
public static boolean objectsEquals(Object a, Object b) {
- if (!Objects.equals(a, b)) {
- Object subject = a != null ? a : b;
- Object subordinate = a != null ? b : a;
- if (subject.getClass().isArray()) {
- Class<?> arrayType = subject.getClass().getComponentType();
- if (arrayType.isPrimitive()) {
- if (arrayType == boolean.class) {
- return Arrays.equals((boolean[]) subject, (boolean[]) subordinate);
- }
- if (arrayType == int.class) {
- return Arrays.equals((int[]) subject, (int[]) subordinate);
- }
- if (arrayType == double.class) {
- return Arrays.equals((double[]) subject, (double[]) subordinate);
- }
- if (arrayType == float.class) {
- return Arrays.equals((float[]) subject, (float[]) subordinate);
- }
- if (arrayType == long.class) {
- return Arrays.equals((long[]) subject, (long[]) subordinate);
- }
- if (arrayType == short.class) {
- return Arrays.equals((short[]) subject, (short[]) subordinate);
- }
- if (arrayType == byte.class) {
- return Arrays.equals((byte[]) subject, (byte[]) subordinate);
- }
- if (arrayType == char.class) {
- return Arrays.equals((char[]) subject, (char[]) subordinate);
- }
- return false;
+ if (a == b) return true;
+ if (a == null || b == null || a.getClass() != b.getClass()) return false;
+
+ if (Objects.equals(a, b)) {
+ return true;
+ }
+
+ if (a.getClass().isArray()) {
+ Class<?> arrayType = a.getClass().getComponentType();
+ if (arrayType.isPrimitive()) {
+ if (arrayType == boolean.class) {
+ return Arrays.equals((boolean[]) a, (boolean[]) b);
+ }
+ if (arrayType == int.class) {
+ return Arrays.equals((int[]) a, (int[]) b);
+ }
+ if (arrayType == double.class) {
+ return Arrays.equals((double[]) a, (double[]) b);
+ }
+ if (arrayType == float.class) {
+ return Arrays.equals((float[]) a, (float[]) b);
+ }
+ if (arrayType == long.class) {
+ return Arrays.equals((long[]) a, (long[]) b);
+ }
+ if (arrayType == short.class) {
+ return Arrays.equals((short[]) a, (short[]) b);
}
- return Arrays.deepEquals((Object[])subject,(Object[])subordinate);
+ if (arrayType == byte.class) {
+ return Arrays.equals((byte[]) a, (byte[]) b);
+ }
+ if (arrayType == char.class) {
+ return Arrays.equals((char[]) a, (char[]) b);
+ }
+ return false;
}
- return false;
+ return Arrays.deepEquals((Object[]) a,(Object[]) b);
}
- return true;
+ return false;
+ }
+
+ public static boolean objectsEqualsWithJSONFallback(Object a, Object b) {
+ return objectsEquals(a, b) || objectsEqualsUsingJSON(a, b);
+ }
+
+ public static boolean objectsEqualsUsingJSON(Object a, Object b) {
+ if (a == b) return true;
+ if (a == null || b == null || a.getClass() != b.getClass()) return false;
+ return Objects.equals(ValueUtil.convert(a, JsonNode.class), ValueUtil.convert(b, JsonNode.class));
}
protected static boolean isGetter(Method method) {
@@ -993,7 +1159,68 @@ public class ValueUtil {
.collect(Collectors.toList());
}
- protected static AssetTypeInfo buildAssetInfo(Class<? extends Asset<?>> assetClass, Map<Class<? extends Asset<?>>, List<NameHolder>> classDescriptorMap) throws IllegalStateException {
+ protected static AssetTypeInfo buildAssetInfoFromName(String name, Map<String, List<NameHolder>> classDescriptorMap) throws IllegalStateException {
+ List<NameHolder> descriptors = classDescriptorMap.get(name);
+ if (descriptors == null) {
+ return null;
+ }
+
+ AtomicReference<AssetDescriptor<?>> assetDescriptor = new AtomicReference<>();
+ Set<AttributeDescriptor<?>> attributeDescriptors = new HashSet<>(10);
+ List<MetaItemDescriptor<?>> metaItemDescriptors = new ArrayList<>(50);
+ List<ValueDescriptor<?>> valueDescriptors = new ArrayList<>(50);
+
+ descriptors.forEach(descriptor -> {
+ if (descriptor instanceof AssetDescriptor<?> ad) {
+ if (assetDescriptor.get() != null) {
+ throw new IllegalStateException("Duplicate asset descriptor found: asset type=" + name +", descriptor=" + assetDescriptor.get() + ", duplicate descriptor=" + descriptor);
+ }
+ assetDescriptor.set(ad);
+ } else if (descriptor instanceof AttributeDescriptor) {
+ attributeDescriptors.stream().filter(d -> d.equals(descriptor)).findFirst()
+ .ifPresent(existingDescriptor -> {
+ if (!existingDescriptor.getType().equals(((AttributeDescriptor<?>) descriptor).getType())) {
+ throw new IllegalStateException("Attribute descriptor override cannot change the value type found: asset type=" + name + ", descriptor=" + existingDescriptor + ", duplicate descriptor=" + descriptor);
+ }
+ attributeDescriptors.remove(existingDescriptor);
+ });
+ attributeDescriptors.add((AttributeDescriptor<?>) descriptor);
+ } else if (descriptor instanceof MetaItemDescriptor metaItemDescriptor) {
+ MetaItemDescriptor<?> existing = ValueUtil.metaItemDescriptors.get(descriptor.getName());
+ if (existing != null && !existing.equals(descriptor)) {
+ throw new IllegalStateException("Duplicate meta item descriptor found: asset type=" + name + ", descriptor=" + existing + ", duplicate descriptor=" + descriptor);
+ }
+ metaItemDescriptors.add(metaItemDescriptor);
+ if (existing == null) {
+ ValueUtil.metaItemDescriptors.put(metaItemDescriptor.getName(), metaItemDescriptor);
+ }
+ } else if (descriptor instanceof ValueDescriptor valueDescriptor) {
+ // Only store basic value type ignore array type for value descriptor as any value descriptor can be an array value descriptor
+ valueDescriptor = valueDescriptor.asNonArray();
+ ValueDescriptor<?> existing = ValueUtil.valueDescriptors.get(descriptor.getName());
+ if (existing != null && !existing.equals(descriptor)) {
+ throw new IllegalStateException("Duplicate value descriptor found: asset type=" + name +", descriptor=" + existing + ", duplicate descriptor=" + descriptor);
+ }
+ valueDescriptors.add(valueDescriptor);
+ if (existing == null) {
+ ValueUtil.valueDescriptors.put(valueDescriptor.getName(), valueDescriptor);
+ }
+ }
+ });
+
+ if (assetDescriptor.get() == null) {
+ LOG.log(Level.WARNING, "Asset descriptor not found for this asset type: asset type=" + name);
+ return null;
+ }
+
+ return new AssetTypeInfo(
+ assetDescriptor.get(),
+ attributeDescriptors.toArray(new AttributeDescriptor<?>[0]),
+ metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]),
+ valueDescriptors.toArray(new ValueDescriptor<?>[0]));
+ }
+
+ protected static AssetTypeInfo buildAssetInfoFromClass(Class<? extends Asset<?>> assetClass, Map<String, List<NameHolder>> classDescriptorMap) throws IllegalStateException {
if (assetClass == UnknownAsset.class) {
return null;
@@ -1025,7 +1252,7 @@ public class ValueUtil {
List<ValueDescriptor<?>> valueDescriptors = new ArrayList<>(50);
classTree.forEach(aClass -> {
- List<NameHolder> descriptors = classDescriptorMap.get(aClass);
+ List<NameHolder> descriptors = classDescriptorMap.get(aClass.getSimpleName());
if (descriptors != null) {
descriptors.forEach(descriptor -> {
if (aClass == assetClass && descriptor instanceof AssetDescriptor) {
@@ -1042,28 +1269,25 @@ public class ValueUtil {
attributeDescriptors.remove(existingDescriptor);
});
attributeDescriptors.add((AttributeDescriptor<?>) descriptor);
- } else if (descriptor instanceof MetaItemDescriptor) {
- int index = ValueUtil.metaItemDescriptors.indexOf(descriptor);
- if (index >= 0 && ValueUtil.metaItemDescriptors.get(index) != descriptor) {
- throw new IllegalStateException("Duplicate meta item descriptor found: asset type=" + assetClass +", descriptor=" + metaItemDescriptors.get(index) + ", duplicate descriptor=" + descriptor);
+ } else if (descriptor instanceof MetaItemDescriptor metaItemDescriptor) {
+ MetaItemDescriptor<?> existing = ValueUtil.metaItemDescriptors.get(descriptor.getName());
+ if (existing != null && !existing.equals(descriptor)) {
+ throw new IllegalStateException("Duplicate meta item descriptor found: asset type=" + assetClass +", descriptor=" + existing + ", duplicate descriptor=" + descriptor);
}
- metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
- if (!ValueUtil.metaItemDescriptors.contains(descriptor)) {
- ValueUtil.metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
+ metaItemDescriptors.add(metaItemDescriptor);
+ if (existing == null) {
+ ValueUtil.metaItemDescriptors.put(metaItemDescriptor.getName(), metaItemDescriptor);
}
- } else if (descriptor instanceof ValueDescriptor) {
- ValueDescriptor<?> valueDescriptor = (ValueDescriptor<?>)descriptor;
+ } else if (descriptor instanceof ValueDescriptor valueDescriptor) {
// Only store basic value type ignore array type for value descriptor as any value descriptor can be an array value descriptor
-
valueDescriptor = valueDescriptor.asNonArray();
-
- int index = valueDescriptors.indexOf(descriptor);
- if (index >= 0 && valueDescriptors.get(index).getType() != valueDescriptor.getType()) {
- throw new IllegalStateException("Duplicate value descriptor found: asset type=" + assetClass +", descriptor=" + valueDescriptors.get(index) + ", duplicate descriptor=" + descriptor);
+ ValueDescriptor<?> existing = ValueUtil.valueDescriptors.get(descriptor.getName());
+ if (existing != null && !existing.equals(descriptor)) {
+ throw new IllegalStateException("Duplicate value descriptor found: asset type=" + assetClass +", descriptor=" + existing + ", duplicate descriptor=" + descriptor);
}
valueDescriptors.add(valueDescriptor);
- if (!ValueUtil.valueDescriptors.contains(descriptor)) {
- ValueUtil.valueDescriptors.add((ValueDescriptor<?>) descriptor);
+ if (existing == null) {
+ ValueUtil.valueDescriptors.put(valueDescriptor.getName(), valueDescriptor);
}
}
});
diff --git a/model/src/main/java/org/openremote/model/validation/AssetStateStore.java b/model/src/main/java/org/openremote/model/validation/AssetStateStore.java
new file mode 100644
index 000000000..020973127
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/AssetStateStore.java
@@ -0,0 +1,27 @@
+package org.openremote.model.validation;
+
+import org.openremote.model.attribute.Attribute;
+
+/**
+ * This is just used as a wrapper for validation purposes
+ */
+// TODO: Replace this with AssetState
+@AssetStateValid
+public class AssetStateStore {
+
+ protected String assetType;
+ protected Attribute<?> attribute;
+
+ public AssetStateStore(String assetType, Attribute<?> attribute) {
+ this.assetType = assetType;
+ this.attribute = attribute;
+ }
+
+ public String getAssetType() {
+ return assetType;
+ }
+
+ public Attribute<?> getAttribute() {
+ return attribute;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/validation/AssetStateValid.java b/model/src/main/java/org/openremote/model/validation/AssetStateValid.java
new file mode 100644
index 000000000..042f963be
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/AssetStateValid.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2020, 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.validation;
+
+import jakarta.validation.Constraint;
+import jakarta.validation.Payload;
+import org.openremote.model.util.TsIgnore;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.Repeatable;
+import java.lang.annotation.Retention;
+import java.lang.annotation.Target;
+
+import static java.lang.annotation.ElementType.*;
+import static java.lang.annotation.RetentionPolicy.RUNTIME;
+
+@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
+@Retention(RUNTIME)
+@Repeatable(AssetStateValid.List.class)
+@Constraint(validatedBy = AssetStateValidator.class)
+@Documented
+@TsIgnore
+public @interface AssetStateValid {
+
+ String MESSAGE_TEMPLATE = "{Asset.invalid.message}";
+
+ String message() default MESSAGE_TEMPLATE;
+
+ Class<?>[] groups() default { };
+
+ Class<? extends Payload>[] payload() default { };
+
+ @Target({ METHOD, FIELD, ANNOTATION_TYPE, PARAMETER, TYPE_USE })
+ @Retention(RUNTIME)
+ @Documented
+ @interface List {
+
+ AssetStateValid[] value();
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/validation/AssetStateValidator.java b/model/src/main/java/org/openremote/model/validation/AssetStateValidator.java
new file mode 100644
index 000000000..4cd7ef90c
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/AssetStateValidator.java
@@ -0,0 +1,50 @@
+package org.openremote.model.validation;
+
+import jakarta.validation.ClockProvider;
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.metadata.ConstraintDescriptor;
+import org.hibernate.validator.constraintvalidation.HibernateConstraintValidator;
+import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetTypeInfo;
+import org.openremote.model.attribute.Attribute;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TsIgnore;
+import org.openremote.model.util.ValueUtil;
+import org.openremote.model.value.AttributeDescriptor;
+
+import java.time.Instant;
+import java.util.Arrays;
+import java.util.Map;
+import java.util.Objects;
+
+/**
+ * A JSR-380 validator that uses {@link ValueUtil} to ensure that the
+ * {@link Asset#getAttributes} conforms to the {@link AttributeDescriptor}s for the
+ * given {@link Asset} type. Checks the following:
+ * <ul>
+ * <li>Required attributes are present and the type matches the {@link AttributeDescriptor};
+ * if no {@link AssetTypeInfo} can be found for the given {@link Asset} then this step is skipped</li>
+ * <li></li>
+ * </ul>
+ */
+@TsIgnore
+public class AssetStateValidator implements HibernateConstraintValidator<AssetStateValid, AssetStateStore> {
+
+ public static final System.Logger LOG = System.getLogger(AssetStateValidator.class.getName() + "." + SyslogCategory.MODEL_AND_VALUES.name());
+ protected ClockProvider clockProvider;
+ @Override
+ public void initialize(ConstraintDescriptor<AssetStateValid> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
+ clockProvider = initializationContext.getClockProvider();
+ HibernateConstraintValidator.super.initialize(constraintDescriptor, initializationContext);
+ }
+
+ @Override
+ public boolean isValid(AssetStateStore assetState, ConstraintValidatorContext context) {
+
+ String type = assetState.getAssetType();
+ AssetTypeInfo assetModelInfo = ValueUtil.getAssetInfo(type).orElse(null);
+
+ return AssetValidator.validateAttribute(assetModelInfo, assetState.getAttribute(), context, clockProvider.getClock().instant());
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/validation/AssetValid.java b/model/src/main/java/org/openremote/model/validation/AssetValid.java
index 6f7c4befa..5930a24d4 100644
--- a/model/src/main/java/org/openremote/model/validation/AssetValid.java
+++ b/model/src/main/java/org/openremote/model/validation/AssetValid.java
@@ -19,23 +19,14 @@
*/
package org.openremote.model.validation;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.attribute.Attribute;
-import org.openremote.model.asset.AssetTypeInfo;
import org.openremote.model.util.TsIgnore;
-import org.openremote.model.util.ValueUtil;
-import org.openremote.model.value.AttributeDescriptor;
import jakarta.validation.Constraint;
-import jakarta.validation.ConstraintValidator;
-import jakarta.validation.ConstraintValidatorContext;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicBoolean;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@@ -43,12 +34,14 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({ FIELD, METHOD, PARAMETER, ANNOTATION_TYPE, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(AssetValid.List.class)
-@Constraint(validatedBy = AssetValid.AssetValidValidator.class)
+@Constraint(validatedBy = AssetValidator.class)
@Documented
@TsIgnore
public @interface AssetValid {
- String message() default "{org.openremote.model.validation.AssetValid.message}";
+ String MESSAGE_TEMPLATE = "{Asset.invalid.message}";
+
+ String message() default MESSAGE_TEMPLATE;
Class<?>[] groups() default { };
@@ -61,57 +54,4 @@ public @interface AssetValid {
AssetValid[] value();
}
-
- /**
- * A JSR-380 validator that uses {@link org.openremote.model.util.ValueUtil} to ensure that the
- * {@link Asset#getAttributes} are valid based on the {@link org.openremote.model.value.AttributeDescriptor}s
- * for the given {@link Asset} type.
- */
- @TsIgnore
- class AssetValidValidator implements ConstraintValidator<AssetValid, Asset<?>> {
-
- public static final String ASSET_TYPE_INVALID = "{Asset.type.Invalid}";
- public static final String ASSET_ATTRIBUTE_MISSING = "{Asset.attribute.Missing}";
- public static final String ASSET_ATTRIBUTE_TYPE_MISMATCH = "{Asset.attribute.type.Mismatch}";
-
- @Override
- public boolean isValid(Asset<?> value, ConstraintValidatorContext context) {
-
- String type = value.getType();
- AssetTypeInfo assetModelInfo = ValueUtil.getAssetInfo(type).orElse(null);
-
- if (assetModelInfo == null || value.getClass() != assetModelInfo.getAssetDescriptor().getType()) {
- context.buildConstraintViolationWithTemplate(ASSET_TYPE_INVALID).addConstraintViolation();
- return false;
- }
-
- // Validate the attributes
- AtomicBoolean valid = new AtomicBoolean(true);
- Arrays.stream(assetModelInfo.getAttributeDescriptors())
- .filter(attributeDescriptor -> !attributeDescriptor.isOptional())
- .forEach(requiredAttributeDescriptor -> {
- Attribute<?> foundAttribute = value.getAttribute(requiredAttributeDescriptor).orElse(null);
-
- if (foundAttribute == null) {
- context.buildConstraintViolationWithTemplate(ASSET_ATTRIBUTE_MISSING).addPropertyNode("attributes").addPropertyNode(requiredAttributeDescriptor.getName()).addConstraintViolation();
- valid.set(false);
- }
- });
-
- value.getAttributes().values().forEach(attribute -> {
- AttributeDescriptor<?> descriptor = Arrays.stream(assetModelInfo.getAttributeDescriptors())
- .filter(attributeDescriptor -> attributeDescriptor.getName().equals(attribute.getName()))
- .findFirst()
- .orElse(null);
-
- if (descriptor != null && !Objects.equals(attribute.getType(), descriptor.getType())) {
- context.buildConstraintViolationWithTemplate(ASSET_ATTRIBUTE_TYPE_MISMATCH).addPropertyNode("attributes").addPropertyNode(attribute.getName()).addConstraintViolation();
- valid.set(false);
- }
- }
- );
-
- return valid.get();
- }
- }
}
diff --git a/model/src/main/java/org/openremote/model/validation/AssetValidator.java b/model/src/main/java/org/openremote/model/validation/AssetValidator.java
new file mode 100644
index 000000000..0d73f8f0a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/AssetValidator.java
@@ -0,0 +1,118 @@
+package org.openremote.model.validation;
+
+import jakarta.validation.ClockProvider;
+import jakarta.validation.ConstraintValidatorContext;
+import jakarta.validation.metadata.ConstraintDescriptor;
+import org.hibernate.validator.constraintvalidation.HibernateConstraintValidator;
+import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetTypeInfo;
+import org.openremote.model.attribute.Attribute;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.TsIgnore;
+import org.openremote.model.util.ValueUtil;
+import org.openremote.model.value.AttributeDescriptor;
+
+import java.time.Instant;
+import java.util.Map;
+import java.util.Objects;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+/**
+ * A JSR-380 validator that uses {@link org.openremote.model.util.ValueUtil} to ensure that the
+ * {@link Asset#getAttributes} conforms to the {@link org.openremote.model.value.AttributeDescriptor}s for the
+ * given {@link Asset} type. Checks the following:
+ * <ul>
+ * <li>Required attributes are present and the type matches the {@link org.openremote.model.value.AttributeDescriptor};
+ * if no {@link AssetTypeInfo} can be found for the given {@link Asset} then this step is skipped</li>
+ * <li></li>
+ * </ul>
+ */
+@TsIgnore
+public class AssetValidator implements HibernateConstraintValidator<AssetValid, Asset<?>> {
+
+ public static final String ASSET_TYPE_INVALID = "{Asset.type.Invalid}";
+ public static final String ASSET_ATTRIBUTE_MISSING = "{Asset.attribute.Missing}";
+ public static final String ASSET_ATTRIBUTE_TYPE_MISMATCH = "{Asset.attribute.type.Mismatch}";
+ public static final System.Logger LOG = System.getLogger(AssetValidator.class.getName() + "." + SyslogCategory.MODEL_AND_VALUES.name());
+ protected ClockProvider clockProvider;
+ @Override
+ public void initialize(ConstraintDescriptor<AssetValid> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
+ clockProvider = initializationContext.getClockProvider();
+ HibernateConstraintValidator.super.initialize(constraintDescriptor, initializationContext);
+ }
+
+ @Override
+ public boolean isValid(Asset<?> asset, ConstraintValidatorContext context) {
+
+ String type = asset.getType();
+ AssetTypeInfo assetModelInfo = ValueUtil.getAssetInfo(type).orElse(null);
+
+ // Check the type of the asset matches the descriptor
+ if (assetModelInfo != null && !assetModelInfo.getAssetDescriptor().isDynamic() && asset.getClass() != assetModelInfo.getAssetDescriptor().getType()) {
+ context.buildConstraintViolationWithTemplate(ASSET_TYPE_INVALID).addConstraintViolation();
+ return false;
+ }
+
+ AtomicBoolean valid = new AtomicBoolean(true);
+
+ // Check for required attributes
+ if (assetModelInfo != null) {
+ assetModelInfo.getAttributeDescriptors().values().stream()
+ .filter(attributeDescriptor -> !attributeDescriptor.isOptional())
+ .forEach(requiredAttributeDescriptor -> {
+ Attribute<?> foundAttribute = asset.getAttribute(requiredAttributeDescriptor).orElse(null);
+
+ if (foundAttribute == null) {
+ context.buildConstraintViolationWithTemplate(ASSET_ATTRIBUTE_MISSING).addPropertyNode("attributes").addPropertyNode(requiredAttributeDescriptor.getName()).addConstraintViolation();
+ valid.set(false);
+ }
+ });
+ }
+
+ // Check attribute types match descriptors and value constraints are met
+ asset.getAttributes().values().forEach(attribute -> {
+ if (!validateAttribute(assetModelInfo, attribute, context, clockProvider.getClock().instant())) {
+ valid.set(false);
+ }
+ });
+
+ return valid.get();
+ }
+
+ @SuppressWarnings("OptionalGetWithoutIsPresent")
+ public static boolean validateAttribute(AssetTypeInfo assetModelInfo, Attribute<?> attribute, ConstraintValidatorContext context, Instant now) {
+ boolean valid = true;
+ AttributeDescriptor<?> descriptor = assetModelInfo == null ? null : assetModelInfo.getAttributeDescriptors().get(attribute.getName());
+
+ // Compare descriptor to the attribute value
+ if (descriptor != null) {
+ if (!Objects.equals(attribute.getType(), descriptor.getType())) {
+ context.buildConstraintViolationWithTemplate(ASSET_ATTRIBUTE_TYPE_MISMATCH).addPropertyNode("attributes").addPropertyNode(attribute.getName()).addConstraintViolation();
+ valid = false;
+ }
+
+ // Attribute value type must match the attributes descriptor value type
+ if (attribute.getValue().isPresent()) {
+ if (!descriptor.getType().getType().isAssignableFrom(attribute.getValue().map(Object::getClass).get())) {
+ context.buildConstraintViolationWithTemplate(ASSET_ATTRIBUTE_TYPE_MISMATCH).addPropertyNode("attributes").addPropertyNode(attribute.getName()).addConstraintViolation();
+ valid = false;
+ }
+ }
+ }
+
+ // Validate the value against the various constraints
+ ValueUtil.ConstraintViolationPathProvider pathProvider = (constraintViolationBuilder) ->
+ constraintViolationBuilder
+ .addPropertyNode("attributes")
+ .addPropertyNode("value")
+ .inContainer(Map.class, 1)
+ .inIterable().atKey(attribute.getName());
+
+ if (!ValueUtil.validateValue(descriptor, attribute.getType(), attribute, now, context, pathProvider, attribute.getValue().orElse(null))) {
+ valid = false;
+ }
+
+ return valid;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/value/AbstractNameValueDescriptorHolder.java b/model/src/main/java/org/openremote/model/value/AbstractNameValueDescriptorHolder.java
index 6fe5f97c0..6eab9f4b2 100644
--- a/model/src/main/java/org/openremote/model/value/AbstractNameValueDescriptorHolder.java
+++ b/model/src/main/java/org/openremote/model/value/AbstractNameValueDescriptorHolder.java
@@ -20,10 +20,8 @@
package org.openremote.model.value;
import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
+import jakarta.validation.constraints.Pattern;
import org.openremote.model.util.TsIgnoreTypeParams;
import java.util.Arrays;
@@ -32,6 +30,7 @@ import java.util.Objects;
@TsIgnoreTypeParams
public abstract class AbstractNameValueDescriptorHolder<T> implements ValueDescriptorHolder<T>, NameHolder {
+ @Pattern(regexp = "^\\w+$")
@JsonIgnore
protected String name;
@JsonIgnore
@@ -51,28 +50,29 @@ public abstract class AbstractNameValueDescriptorHolder<T> implements ValueDescr
this.constraints = constraints;
}
- @JsonProperty
+ public AbstractNameValueDescriptorHolder(String name, ValueDescriptor<T> type, ValueConstraint[] constraints, ValueFormat format, String[] units) {
+ this.name = name;
+ this.type = type;
+ this.constraints = constraints;
+ this.format = format;
+ this.units = units;
+ }
+
@Override
public String getName() {
return name;
}
- @JsonProperty
protected void setName(String name) {
this.name = name;
}
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonSerialize(converter = ValueDescriptor.NameHolderToStringConverter.class)
@Override
public ValueDescriptor<T> getType() {
return type;
}
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
protected void setType(ValueDescriptor<T> type) {
this.type = type;
}
diff --git a/model/src/main/java/org/openremote/model/value/AbstractNameValueHolder.java b/model/src/main/java/org/openremote/model/value/AbstractNameValueHolder.java
index 942a1d7c1..a784c4f74 100644
--- a/model/src/main/java/org/openremote/model/value/AbstractNameValueHolder.java
+++ b/model/src/main/java/org/openremote/model/value/AbstractNameValueHolder.java
@@ -19,110 +19,105 @@
*/
package org.openremote.model.value;
-import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import org.openremote.model.util.TextUtil;
-import org.openremote.model.util.ValueUtil;
-
+import jakarta.annotation.Nonnull;
+import jakarta.annotation.Nullable;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
-import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Pattern;
+import org.openremote.model.util.TextUtil;
+import org.openremote.model.util.ValueUtil;
+
import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;
-@JsonFilter("excludeNameFilter")
public abstract class AbstractNameValueHolder<T> implements NameValueHolder<T>, Serializable {
-
@JsonIgnore
protected ValueDescriptor<T> type;
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Valid
- @JsonIgnore
protected T value;
+ @JsonIgnore
+ protected String valueStr; // This is for lazy value initialisation when deserialising
@NotBlank(message = "{Asset.valueHolder.name.NotBlank}")
@Pattern(regexp = "^\\w+$")
- @JsonIgnore
protected String name;
protected AbstractNameValueHolder() {
}
- public AbstractNameValueHolder(@NotNull String name, @NotNull ValueDescriptor<T> type, T value) {
+ public AbstractNameValueHolder(@Nonnull String name, ValueDescriptor<T> type, T value) {
if (TextUtil.isNullOrEmpty(name)) {
throw new IllegalArgumentException("name cannot be null or empty");
}
- if (type == null) {
- throw new IllegalArgumentException("type cannot be null");
- }
this.name = name;
this.type = type;
this.value = value;
}
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonSerialize(converter = ValueDescriptor.NameHolderToStringConverter.class)
@Override
+ @Nullable
public ValueDescriptor<T> getType() {
return type;
}
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
- protected void setType(ValueDescriptor<T> type) {
- this.type = type;
+ @Override
+ public Class<?> getTypeClass() {
+ return getType() != null ? getType().getType() : Object.class;
}
+ @SuppressWarnings("unchecked")
@JsonProperty
@Override
public Optional<T> getValue() {
- return Optional.ofNullable(value);
+ return (Optional<T>)getValue(getTypeClass());
}
@SuppressWarnings("unchecked")
@Override
- public <U> Optional<U> getValueAs(Class<U> valueType) {
- if (valueType.isAssignableFrom(getType().getType())) {
- return Optional.ofNullable((U)value);
+ public <U> Optional<U> getValue(@Nonnull Class<U> valueType) {
+ if (value == null) {
+ return Optional.empty();
+ }
+ if (valueType.isAssignableFrom(value.getClass())) {
+ return Optional.of((U)value);
}
- return Optional.empty();
+ return ValueUtil.getValueCoerced(value, valueType);
}
@JsonProperty
public void setValue(T value) {
this.value = value;
+ valueStr = null;
}
- @JsonProperty
@Override
public String getName() {
return name;
}
- @JsonProperty
protected void setName(String name) {
this.name = name;
}
+ /**
+ * {@link #type} is transient so don't use it for equality checks
+ */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AbstractNameValueHolder<?> that = (AbstractNameValueHolder<?>) o;
return name.equals(that.name)
- && Objects.equals(type, that.type)
- && Objects.equals(ValueUtil.convert(value, JsonNode.class), ValueUtil.convert(that.value, JsonNode.class));
+ && ValueUtil.objectsEqualsWithJSONFallback(value, that.value);
}
@Override
public int hashCode() {
- return Objects.hash(value, type, name);
+ return Objects.hash(value, name);
}
}
diff --git a/model/src/main/java/org/openremote/model/value/AttributeDescriptor.java b/model/src/main/java/org/openremote/model/value/AttributeDescriptor.java
index 4000e1c31..128182102 100644
--- a/model/src/main/java/org/openremote/model/value/AttributeDescriptor.java
+++ b/model/src/main/java/org/openremote/model/value/AttributeDescriptor.java
@@ -19,6 +19,7 @@
*/
package org.openremote.model.value;
+import com.fasterxml.jackson.annotation.JsonIgnore;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
@@ -43,8 +44,9 @@ import java.util.Collection;
@TsIgnoreTypeParams
public class AttributeDescriptor<T> extends AbstractNameValueDescriptorHolder<T> implements MetaHolder {
+ @JsonIgnore
protected MetaMap meta;
- protected boolean optional;
+ protected Boolean optional;
AttributeDescriptor() {}
@@ -80,11 +82,11 @@ public class AttributeDescriptor<T> extends AbstractNameValueDescriptorHolder<T>
}
public boolean isOptional() {
- return optional;
+ return optional != null ? optional : false;
}
public AttributeDescriptor<T> withOptional(boolean optional) {
- AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<T>(name, type, meta);
+ AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<>(name, type, meta);
newDescriptor.format = format;
newDescriptor.constraints = constraints;
newDescriptor.units = units;
@@ -93,7 +95,7 @@ public class AttributeDescriptor<T> extends AbstractNameValueDescriptorHolder<T>
}
public AttributeDescriptor<T> withFormat(ValueFormat format) {
- AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<T>(name, type, meta);
+ AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<>(name, type, meta);
newDescriptor.format = format;
newDescriptor.constraints = constraints;
newDescriptor.units = units;
@@ -102,7 +104,7 @@ public class AttributeDescriptor<T> extends AbstractNameValueDescriptorHolder<T>
}
public AttributeDescriptor<T> withConstraints(ValueConstraint...constraints) {
- AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<T>(name, type, meta);
+ AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<>(name, type, meta);
newDescriptor.format = format;
newDescriptor.constraints = constraints;
newDescriptor.units = units;
@@ -111,7 +113,7 @@ public class AttributeDescriptor<T> extends AbstractNameValueDescriptorHolder<T>
}
public AttributeDescriptor<T> withUnits(String...units) {
- AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<T>(name, type, meta);
+ AttributeDescriptor<T> newDescriptor = new AttributeDescriptor<>(name, type, meta);
newDescriptor.format = format;
newDescriptor.constraints = constraints;
newDescriptor.units = units;
diff --git a/model/src/main/java/org/openremote/model/value/JsonPathFilter.java b/model/src/main/java/org/openremote/model/value/JsonPathFilter.java
index 9ed6a2d38..34fa52e3e 100644
--- a/model/src/main/java/org/openremote/model/value/JsonPathFilter.java
+++ b/model/src/main/java/org/openremote/model/value/JsonPathFilter.java
@@ -86,8 +86,7 @@ public class JsonPathFilter extends ValueFilter {
Object obj = jsonPathParser.parse(valueStr).read(path);
- if ((returnFirst || returnLast) && obj != null && ValueUtil.isArray(obj.getClass())) {
- ArrayNode arrayNode = ValueUtil.convert(obj, ArrayNode.class);
+ if ((returnFirst || returnLast) && obj instanceof ArrayNode arrayNode) {
obj = arrayNode.get(returnFirst ? 0 : arrayNode.size() - 1);
}
return obj;
diff --git a/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java b/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java
index ee16222e4..39fd87468 100644
--- a/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java
+++ b/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java
@@ -39,35 +39,26 @@ import org.openremote.model.util.ValueUtil;
public class MetaItemDescriptor<T> extends AbstractNameValueDescriptorHolder<T> {
/**
- * This class handles serialising {@link MetaItemDescriptor}s as strings
- */
- public static class MetaItemDescriptorStringConverter extends StdConverter<MetaItemDescriptor<?>, String> {
-
- @Override
- public String convert(MetaItemDescriptor<?> value) {
- return value.getName();
- }
- }
-
- /**
- * This class handles deserialising meta item descriptor names to {@link MetaItemDescriptor}s
+ * This class handles deserialising meta item descriptor names to {@link MetaItemDescriptor}s; to reuse instances
*/
public static class StringMetaItemDescriptorConverter extends StdConverter<String, MetaItemDescriptor<?>> {
@Override
public MetaItemDescriptor<?> convert(String value) {
- return ValueUtil.getMetaItemDescriptor(value).orElse(MetaItemDescriptor.UNKNOWN);
+ return ValueUtil.getMetaItemDescriptor(value).orElse(null);
}
}
- public static final MetaItemDescriptor<Object> UNKNOWN = new MetaItemDescriptor<>("unkown", ValueDescriptor.UNKNOWN);
-
MetaItemDescriptor() {}
public MetaItemDescriptor(String name, ValueDescriptor<T> valueDescriptor, ValueConstraint...constraints) {
super(name, valueDescriptor, constraints);
}
+ public MetaItemDescriptor(String name, ValueDescriptor<T> type, ValueConstraint[] constraints, ValueFormat format, String[] units) {
+ super(name, type, constraints, format, units);
+ }
+
public MetaItemDescriptor<T> setFormat(ValueFormat format) {
this.format = format;
return this;
diff --git a/model/src/main/java/org/openremote/model/value/MetaItemType.java b/model/src/main/java/org/openremote/model/value/MetaItemType.java
index 9ba0e7a23..b0666cde2 100644
--- a/model/src/main/java/org/openremote/model/value/MetaItemType.java
+++ b/model/src/main/java/org/openremote/model/value/MetaItemType.java
@@ -164,8 +164,8 @@ public final class MetaItemType {
public static final MetaItemDescriptor<String[]> UNITS = new MetaItemDescriptor<>("units", ValueType.TEXT.asArray());
/**
- * {@link ValueConstraint}s to be applied to the {@link Attribute} value; these override any constraints defined on
- * any of the descriptors associated with the attribute.
+ * {@link ValueConstraint}s to be applied to the {@link Attribute} value; these are added to any constraints defined
+ * on any of the descriptors associated with the attribute.
*/
public static final MetaItemDescriptor<ValueConstraint[]> CONSTRAINTS = new MetaItemDescriptor<>("constraints", ValueType.VALUE_CONSTRAINT.asArray());
@@ -187,7 +187,7 @@ public final class MetaItemType {
/**
* Indicates that the button input should send the true/on/pressed/closed value when pressed; and then send the
- * false/off/released/open value when released.
+ * false/off/released/open value when released (for use by UIs)
*/
public static final MetaItemDescriptor<Boolean> MOMENTARY = new MetaItemDescriptor<>("momentary", ValueType.BOOLEAN);
diff --git a/model/src/main/java/org/openremote/model/value/NameHolder.java b/model/src/main/java/org/openremote/model/value/NameHolder.java
index 1b570b686..08698b606 100644
--- a/model/src/main/java/org/openremote/model/value/NameHolder.java
+++ b/model/src/main/java/org/openremote/model/value/NameHolder.java
@@ -20,8 +20,7 @@
package org.openremote.model.value;
import com.fasterxml.jackson.annotation.JsonProperty;
-
-import jakarta.validation.constraints.Pattern;
+import com.fasterxml.jackson.databind.util.StdConverter;
/**
* Identifies an item that holds a named property, the name should be very simple, as we use them in SQL path
@@ -29,7 +28,17 @@ import jakarta.validation.constraints.Pattern;
*/
public interface NameHolder {
+ /**
+ * This class handles serialising {@link ValueDescriptor}s as strings
+ */
+ class NameHolderToStringConverter extends StdConverter<NameHolder, String> {
+
+ @Override
+ public String convert(NameHolder value) {
+ return value.getName();
+ }
+ }
+
@JsonProperty
- @Pattern(regexp = "^\\w+$")
String getName();
}
diff --git a/model/src/main/java/org/openremote/model/value/ValueConstraint.java b/model/src/main/java/org/openremote/model/value/ValueConstraint.java
index 9341669a5..470717b4c 100644
--- a/model/src/main/java/org/openremote/model/value/ValueConstraint.java
+++ b/model/src/main/java/org/openremote/model/value/ValueConstraint.java
@@ -23,9 +23,18 @@ import com.fasterxml.jackson.annotation.*;
import org.openremote.model.util.ValueUtil;
import java.io.Serializable;
+import java.lang.reflect.Array;
+import java.time.Instant;
import java.util.Arrays;
+import java.util.Collection;
+import java.util.Map;
import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.PatternSyntaxException;
+// TODO: Switch to JSONSchema with a validator that supports POJOs (something like
+// https://github.com/java-json-tools/json-schema-validator which is no longer maintained) or find a JSR-380
+// implementation that supports dynamic validators
/**
* Represents a constraint to apply to a value; these are based on JSR-380 validation.
*/
@@ -46,9 +55,19 @@ import java.util.Optional;
})
public abstract class ValueConstraint implements Serializable {
- public static ValueConstraint[] constraints(ValueConstraint...constraints) {
- return constraints;
- }
+ public static final String VALUE_CONSTRAINT_INVALID = "{ValueConstraint.Invalid}";
+ public static final String SIZE_MESSAGE_TEMPLATE = "{ValueConstraint.Size.message}";
+ public static final String MIN_MESSAGE_TEMPLATE = "{ValueConstraint.Min.message}";
+ public static final String MAX_MESSAGE_TEMPLATE = "{ValueConstraint.Max.message}";
+ public static final String PATTERN_MESSAGE_TEMPLATE = "{ValueConstraint.Pattern.message}";
+ public static final String ALLOWED_VALUES_MESSAGE_TEMPLATE = "{ValueConstraint.AllowedValues.message}";
+ public static final String PAST_MESSAGE_TEMPLATE = "{ValueConstraint.Past.message}";
+ public static final String PAST_OR_PRESENT_MESSAGE_TEMPLATE = "{ValueConstraint.PastOrPresent.message}";
+ public static final String FUTURE_MESSAGE_TEMPLATE = "{ValueConstraint.Future.message}";
+ public static final String FUTURE_OR_PRESENT_MESSAGE_TEMPLATE = "{ValueConstraint.FutureOrPresent.message}";
+ public static final String NOT_EMPTY_MESSAGE_TEMPLATE = "{ValueConstraint.NotEmpty.message}";
+ public static final String NOT_BLANK_MESSAGE_TEMPLATE = "{ValueConstraint.NotBlank.message}";
+ public static final String NOT_NULL_MESSAGE_TEMPLATE = "{ValueConstraint.NotNull.message}";
@JsonTypeName("size")
public static class Size extends ValueConstraint {
@@ -58,6 +77,7 @@ public abstract class ValueConstraint implements Serializable {
@JsonCreator
public Size(@JsonProperty("min") Integer min, @JsonProperty("max") Integer max) {
+ super(SIZE_MESSAGE_TEMPLATE);
this.min = min;
this.max = max;
}
@@ -74,6 +94,39 @@ public abstract class ValueConstraint implements Serializable {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return Map.of(
+ "min", min,
+ "max", max);
+ }
+
+ @SuppressWarnings("rawtypes")
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true; // Same behaviour as JSR-380
+ }
+
+ Class<?> clazz = value.getClass();
+
+ if (Map.class.isAssignableFrom(clazz)) {
+ int size = ((Map)value).size();
+ return size >= min && size <= max;
+ } else if (Collection.class.isAssignableFrom(clazz)) {
+ int size = ((Collection)value).size();
+ return size >= min && size <= max;
+ } else if (ValueUtil.isArray(clazz)) {
+ int size = Array.getLength(value);
+ return size >= min && size <= max;
+ } else if (ValueUtil.isString(clazz)) {
+ int size = ((CharSequence)value).length();
+ return size >= min && size <= max;
+ }
+
+ return false;
+ }
}
@JsonTypeName("min")
@@ -82,6 +135,7 @@ public abstract class ValueConstraint implements Serializable {
@JsonCreator
public Min(@JsonProperty("min") Number min) {
+ super(MIN_MESSAGE_TEMPLATE);
this.min = min;
}
@@ -93,6 +147,62 @@ public abstract class ValueConstraint implements Serializable {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return Map.of("value", min);
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Class<?> clazz = value.getClass();
+
+ if (!ValueUtil.isNumber(clazz)) {
+ return false;
+ }
+
+ if (min instanceof Integer minInt) {
+ if (value instanceof Long longValue) {
+ return Long.valueOf(minInt.longValue()).compareTo(longValue) <= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return minInt.compareTo(doubleValue.intValue()) <= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return minInt.compareTo(intValue) <= 0;
+ }
+ return false;
+ }
+ if (min instanceof Double minDouble) {
+ if (value instanceof Long longValue) {
+ return minDouble.compareTo(longValue.doubleValue()) <= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return minDouble.compareTo(doubleValue) <= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return minDouble.compareTo(intValue.doubleValue()) <= 0;
+ }
+ return false;
+ }
+ if (min instanceof Long minLong) {
+ if (value instanceof Long longValue) {
+ return minLong.compareTo(longValue) <= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return minLong.compareTo(doubleValue.longValue()) <= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return minLong.compareTo(intValue.longValue()) <= 0;
+ }
+ }
+
+ return false;
+ }
}
@JsonTypeName("max")
@@ -101,6 +211,7 @@ public abstract class ValueConstraint implements Serializable {
@JsonCreator
public Max(@JsonProperty("max") Number max) {
+ super(MAX_MESSAGE_TEMPLATE);
this.max = max;
}
@@ -112,39 +223,139 @@ public abstract class ValueConstraint implements Serializable {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return Map.of("value", max);
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Class<?> clazz = value.getClass();
+
+ if (!ValueUtil.isNumber(clazz)) {
+ return false;
+ }
+
+ if (max instanceof Integer maxInt) {
+ if (value instanceof Long longValue) {
+ return Long.valueOf(maxInt.longValue()).compareTo(longValue) >= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return maxInt.compareTo(doubleValue.intValue()) >= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return maxInt.compareTo(intValue) >= 0;
+ }
+ return false;
+ }
+ if (max instanceof Double maxDouble) {
+ if (value instanceof Long longValue) {
+ return maxDouble.compareTo(longValue.doubleValue()) >= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return maxDouble.compareTo(doubleValue) >= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return maxDouble.compareTo(intValue.doubleValue()) >= 0;
+ }
+ return false;
+ }
+ if (max instanceof Long maxLong) {
+ if (value instanceof Long longValue) {
+ return maxLong.compareTo(longValue) >= 0;
+ }
+ if (value instanceof Double doubleValue) {
+ return maxLong.compareTo(doubleValue.longValue()) >= 0;
+ }
+ if (value instanceof Integer intValue) {
+ return maxLong.compareTo(intValue.longValue()) >= 0;
+ }
+ }
+
+ return false;
+ }
}
@JsonTypeName("pattern")
public static class Pattern extends ValueConstraint {
+ private static final java.util.regex.Pattern ESCAPE_MESSAGE_PARAMETER_PATTERN = java.util.regex.Pattern.compile("([\\\\{}$])");
protected String regexp;
+ protected jakarta.validation.constraints.Pattern.Flag[] flags;
@JsonCreator
- public Pattern(@JsonProperty("regexp") String regexp) {
+ public Pattern(String regexp, jakarta.validation.constraints.Pattern.Flag[] flags) {
+ super(PATTERN_MESSAGE_TEMPLATE);
this.regexp = regexp;
+ this.flags = flags;
+ }
+
+ public Pattern(String regexp) {
+ this(regexp, null);
}
public String getRegexp() {
return regexp;
}
+ public jakarta.validation.constraints.Pattern.Flag[] getFlags() {
+ return flags;
+ }
+
public Pattern setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ String escapedRegexp = regexp != null ? ESCAPE_MESSAGE_PARAMETER_PATTERN.matcher(regexp).replaceAll( Matcher.quoteReplacement("\\") + "$1" ) : "null";
+ return Map.of("value", escapedRegexp);
+ }
+
+ @SuppressWarnings("MagicConstant")
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Class<?> clazz = value.getClass();
+
+ if (CharSequence.class.isAssignableFrom(clazz)) {
+ int intFlag = 0;
+ if (flags != null) {
+ for (jakarta.validation.constraints.Pattern.Flag flag : flags) {
+ intFlag = intFlag | flag.getValue();
+ }
+ }
+
+ try {
+ java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regexp, intFlag);
+ Matcher m = pattern.matcher((CharSequence)value);
+ return m.matches();
+ }
+ catch (PatternSyntaxException ignored) {}
+ }
+
+ return false;
+ }
}
@JsonTypeName("allowedValues")
public static class AllowedValues extends ValueConstraint {
Object[] allowedValues;
- String[] allowedValueNames;
-
@JsonCreator
- public AllowedValues(@JsonProperty("allowedValueNames") String[] allowedValueNames, @JsonProperty("allowedValues") Object...allowedValues) {
- this.allowedValueNames = allowedValueNames;
- this.allowedValues = allowedValues;
+ protected AllowedValues() {
+ super(ALLOWED_VALUES_MESSAGE_TEMPLATE);
}
- public AllowedValues(@JsonProperty("allowedValues") Object...allowedValues) {
+ public AllowedValues(Object...allowedValues) {
+ super(ALLOWED_VALUES_MESSAGE_TEMPLATE);
this.allowedValues = allowedValues;
}
@@ -152,12 +363,36 @@ public abstract class ValueConstraint implements Serializable {
return allowedValues;
}
- public String[] getAllowedValueNames() {
- return allowedValueNames;
+ @Override
+ public Map<String, Object> getParameters() {
+ return Map.of("values", Arrays.toString(allowedValues));
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+ if (allowedValues == null || allowedValues.length == 0) {
+ return false;
+ }
+
+ Class<?> clazz = value.getClass();
+ Object compareValue = null;
+
+ if (Enum.class.isAssignableFrom(clazz)) {
+ compareValue = ((Enum<?>) value).name();
+ } else if (ValueUtil.isString(clazz)) {
+ compareValue = ((CharSequence)value).toString();
+ } else if (ValueUtil.isNumber(clazz)) {
+ compareValue = value;
+ }
+
+ return Arrays.asList(allowedValues).contains(compareValue);
}
- public static AllowedValues fromEnum(Class<Enum<?>> enumClass) {
- Object[] allowedValues = Arrays.stream(enumClass.getEnumConstants()).map(enm -> ValueUtil.getStringCoerced(enm).orElse(null)).toArray(String[]::new);
+ public static <T extends Enum<T>> AllowedValues fromEnumValues(T[] enumValues) {
+ Object[] allowedValues = Arrays.stream(enumValues).map(enm -> ValueUtil.getStringCoerced(enm).orElse(null)).toArray(String[]::new);
return new AllowedValues(allowedValues);
}
}
@@ -165,69 +400,253 @@ public abstract class ValueConstraint implements Serializable {
@JsonTypeName("past")
public static class Past extends ValueConstraint {
+ public Past() {
+ super(PAST_MESSAGE_TEMPLATE);
+ }
+
public Past setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Instant valueInstant = ValueUtil.getValueCoerced(value, Instant.class).orElse(null);
+
+ if (valueInstant != null) {
+ int result = valueInstant.compareTo(now);
+ return result < 0;
+ }
+
+ return false;
+ }
}
@JsonTypeName("pastOrPresent")
public static class PastOrPresent extends ValueConstraint {
+ public PastOrPresent() {
+ super(PAST_OR_PRESENT_MESSAGE_TEMPLATE);
+ }
+
public PastOrPresent setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Instant valueInstant = ValueUtil.getValueCoerced(value, Instant.class).orElse(null);
+
+ if (valueInstant != null) {
+ int result = valueInstant.compareTo(now);
+ return result <= 0;
+ }
+
+ return false;
+ }
}
@JsonTypeName("future")
public static class Future extends ValueConstraint {
+ public Future() {
+ super(FUTURE_MESSAGE_TEMPLATE);
+ }
+
public Future setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Instant valueInstant = ValueUtil.getValueCoerced(value, Instant.class).orElse(null);
+
+ if (valueInstant != null) {
+ int result = valueInstant.compareTo(now);
+ return result > 0;
+ }
+
+ return false;
+ }
}
@JsonTypeName("futureOrPresent")
public static class FutureOrPresent extends ValueConstraint {
+ public FutureOrPresent() {
+ super(FUTURE_OR_PRESENT_MESSAGE_TEMPLATE);
+ }
+
public FutureOrPresent setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return true;
+ }
+
+ Instant valueInstant = ValueUtil.getValueCoerced(value, Instant.class).orElse(null);
+
+ if (valueInstant != null) {
+ int result = valueInstant.compareTo(now);
+ return result >= 0;
+ }
+
+ return false;
+ }
}
@JsonTypeName("notEmpty")
public static class NotEmpty extends ValueConstraint {
+ public NotEmpty() {
+ super(NOT_EMPTY_MESSAGE_TEMPLATE);
+ }
+
public NotEmpty setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ if (value == null) {
+ return false;
+ }
+
+ Class<?> clazz = value.getClass();
+
+ if (Map.class.isAssignableFrom(clazz)) {
+ return !((Map<?, ?>)value).isEmpty();
+ } else if (Collection.class.isAssignableFrom(clazz)) {
+ return !((Collection<?>) value).isEmpty();
+ } else if (ValueUtil.isArray(clazz)) {
+ return Array.getLength(value) > 0;
+ } else if (ValueUtil.isString(clazz)) {
+ return !((CharSequence) value).isEmpty();
+ }
+
+ return false;
+ }
+
+ @Override
+ public String toString() {
+ return NotEmpty.class.getSimpleName() + "{}";
+ }
}
@JsonTypeName("notBlank")
public static class NotBlank extends ValueConstraint {
+ public NotBlank() {
+ super(NOT_BLANK_MESSAGE_TEMPLATE);
+ }
public NotBlank setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ return value instanceof CharSequence && !value.toString().trim().isEmpty();
+ }
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return NotBlank.class.getSimpleName();
+ }
}
@JsonTypeName("notNull")
public static class NotNull extends ValueConstraint {
+ public NotNull() {
+ super(NOT_NULL_MESSAGE_TEMPLATE);
+ }
+
public NotNull setMessage(String message) {
this.message = message;
return this;
}
+
+ @Override
+ public boolean evaluate(Object value, Instant now) {
+ return value != null;
+ }
+
+ @Override
+ public Map<String, Object> getParameters() {
+ return null;
+ }
+
+ @Override
+ public String toString() {
+ return NotNull.class.getSimpleName();
+ }
}
protected String message;
+ protected ValueConstraint(String message) {
+ this.message = message;
+ }
+
+ public abstract boolean evaluate(Object value, Instant now);
+
+ public abstract Map<String, Object> getParameters();
+
public Optional<String> getMessage() {
return Optional.ofNullable(message);
}
+
+ public static ValueConstraint[] constraints(ValueConstraint...constraints) {
+ return constraints;
+ }
}
diff --git a/model/src/main/java/org/openremote/model/value/ValueDescriptor.java b/model/src/main/java/org/openremote/model/value/ValueDescriptor.java
index c03c58255..3fc30d784 100644
--- a/model/src/main/java/org/openremote/model/value/ValueDescriptor.java
+++ b/model/src/main/java/org/openremote/model/value/ValueDescriptor.java
@@ -19,18 +19,31 @@
*/
package org.openremote.model.value;
+import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonSerialize;
-import com.fasterxml.jackson.databind.util.StdConverter;
+import com.fasterxml.jackson.core.JacksonException;
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.JsonDeserializer;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
+import com.fasterxml.jackson.databind.deser.ResolvableDeserializer;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import jakarta.validation.constraints.Pattern;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.util.TsIgnoreTypeParams;
import org.openremote.model.util.ValueUtil;
+import java.io.IOException;
import java.io.Serializable;
import java.math.BigInteger;
-import java.util.*;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.Objects;
+import java.util.function.Function;
/**
* A simple wrapper around a {@link Class} that describes a value that can be used by {@link Attribute}s and
@@ -46,105 +59,69 @@ import java.util.*;
* <p>
* {@link ValueDescriptor#getName} must be globally unique within the context of the manager it is registered with.
*/
-//@JsonDeserialize(using = ValueDescriptor.ValueDescriptorDeserialiser.class)
@TsIgnoreTypeParams
public class ValueDescriptor<T> implements NameHolder, Serializable {
/**
- * This class handles serialising {@link ValueDescriptor}s as strings
+ * Custom deserialiser that will return the same instance of {@link ValueDescriptor} using the
+ * {@link #VALUE_DESCRIPTOR_PROVIDER} attribute; otherwise it will construct a new instance
*/
- public static class ValueDescriptorStringConverter extends StdConverter<ValueDescriptor<?>, String> {
+ public static class ValueDescriptorDeserializer extends StdDeserializer<ValueDescriptor<?>> implements ResolvableDeserializer {
- @Override
- public String convert(ValueDescriptor<?> value) {
- return value.getName();
- }
- }
+ public static final String VALUE_DESCRIPTOR_PROVIDER = "value-descriptor-provider";
+ protected static Function<String, ValueDescriptor<?>> DEFAULT_VALUE_DESCRIPTOR_PROVIDER = (name) -> ValueUtil.getValueDescriptor(name).orElse(null);
+ protected JsonDeserializer<ValueDescriptor<?>> defaultDeserializer;
- /**
- * This class handles deserialising value descriptor names to {@link ValueDescriptor}s
- */
- public static class StringValueDescriptorConverter extends StdConverter<String, ValueDescriptor<?>> {
+ public ValueDescriptorDeserializer(JsonDeserializer<ValueDescriptor<?>> deserializer) {
+ super(ValueDescriptor.class);
+ this.defaultDeserializer = deserializer;
+ }
+ @SuppressWarnings("unchecked")
@Override
- public ValueDescriptor<?> convert(String value) {
- return ValueUtil.getValueDescriptor(value).orElse(ValueDescriptor.UNKNOWN);
+ public ValueDescriptor<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JacksonException {
+ Function<String, ValueDescriptor<?>> valueDescriptorProvider = (Function<String, ValueDescriptor<?>>)ctxt.getAttribute(VALUE_DESCRIPTOR_PROVIDER);
+ if (valueDescriptorProvider == null) {
+ valueDescriptorProvider = DEFAULT_VALUE_DESCRIPTOR_PROVIDER;
+ }
+
+ if (p.currentToken() == JsonToken.VALUE_NULL) {
+ return null;
+ }
+
+ if (p.currentToken() == JsonToken.VALUE_STRING) {
+ String name = p.getText();
+ return valueDescriptorProvider.apply(name);
+ }
+
+ if (!p.isExpectedStartObjectToken()) {
+ throw JsonMappingException.from(p, "Value descriptor must be a string or object");
+ }
+
+ return defaultDeserializer.deserialize(p, ctxt);
}
- }
- /**
- * Just outputs simple class name for compactness but can still prove useful for discrimination purposes on UIs
- */
- public static class ValueTypeStringConverter extends StdConverter<Class<?>, String> {
-
+ // The wrapped deserializer might need some post-processing so check whether it implements it or not
@Override
- public String convert(Class<?> clazz) {
- return clazz.getSimpleName();
+ public void resolve(DeserializationContext ctxt) throws JsonMappingException {
+ if (defaultDeserializer instanceof ResolvableDeserializer resolvableDeserializer) {
+ resolvableDeserializer.resolve(ctxt);
+ }
}
}
-// public static class ValueDescriptorDeserialiser extends StdDeserializer<ValueDescriptor<?>> {
-//
-// public ValueDescriptorDeserialiser() {
-// super(ValueDescriptor.class);
-// }
-//
-// @Override
-// public ValueDescriptor<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
-//
-// String name;
-// String type;
-// MetaMap meta = null;
-// JsonNode node = p.getCodec().readTree(p);
-//
-// if (!node.isObject()) {
-// throw MismatchedInputException.from(p, ValueDescriptor.class, "Expected object but got: " + node.getNodeType());
-// }
-//
-// name = node.get("name").asText();
-// type = node.get("type").asText();
-// if (node.has("meta")) {
-// JsonParser metaParser = node.get("meta").traverse(p.getCodec());
-// metaParser.nextToken();
-// meta = ctxt.readValue(metaParser, MetaMap.class);
-// }
-//
-// // Look for an existing value descriptor with this name
-// MetaMap finalMeta = meta;
-// return AssetModelUtil.getValueDescriptor(name).orElseGet(() -> {
-// Class<?> typeClass = ValueType.JSON_OBJECT.type;
-// boolean isArray = name.endsWith("[]");
-//
-// switch (type) {
-// case "boolean":
-// typeClass = ValueType.BOOLEAN.type;
-// break;
-// case "number":
-// typeClass = ValueType.NUMBER.type;
-// break;
-// case "string":
-// typeClass = ValueType.STRING.type;
-// break;
-// case "array":
-// typeClass = Object[].class;
-// break;
-// }
-//
-// ValueDescriptor<?> valueDescriptor = new ValueDescriptor<>(name, typeClass, finalMeta);
-// return isArray ? valueDescriptor.asArray() : valueDescriptor;
-// });
-// }
-// }
-
- public static final ValueDescriptor<Object> UNKNOWN = new ValueDescriptor<>("Unknown", Object.class);
-
+ @Pattern(regexp = "^\\w+(\\[\\])?$")
protected String name;
- @JsonSerialize(converter = ValueDescriptor.ValueTypeStringConverter.class)
protected Class<T> type;
protected Integer arrayDimensions;
protected ValueConstraint[] constraints;
protected ValueFormat format;
protected String[] units;
+ /**
+ * A flag to indicate that this {@link ValueDescriptor} is intended for use in a {@link MetaItem}; this can be used
+ * for UI purposes but nothing actually stops the values being used in an {@link Attribute} also.
+ */
+ protected Boolean metaUseOnly;
@SuppressWarnings("unchecked")
public ValueDescriptor(String name, Class<T> type, ValueConstraint...constraints) {
@@ -154,7 +131,7 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
this.name = name;
this.type = type;
if (type.isEnum() && (constraints == null || Arrays.stream(constraints).noneMatch(c -> c instanceof ValueConstraint.AllowedValues))) {
- ValueConstraint.AllowedValues allowedValues = ValueConstraint.AllowedValues.fromEnum((Class<Enum<?>>) type);
+ ValueConstraint.AllowedValues allowedValues = ValueConstraint.AllowedValues.fromEnumValues((Enum[])type.getEnumConstants());
if (constraints != null) {
constraints = Arrays.copyOf(constraints, constraints.length+1);
constraints[constraints.length-1] = allowedValues;
@@ -165,6 +142,7 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
this.constraints = constraints;
}
+ @JsonCreator
protected ValueDescriptor(String name, Class<T> type, ValueConstraint[] constraints, ValueFormat format, String[] units, Integer arrayDimensions) {
this.name = name;
this.type = type;
@@ -174,19 +152,21 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
this.units = units;
}
+ @Pattern(regexp = "^\\w+(\\[\\])?$")
public String getName() {
return name;
}
+ @SuppressWarnings("unchecked")
public Class<T> getType() {
- return type;
+ return type != null ? type : (Class<T>)Object.class;
}
/**
* If this descriptor is an array type then this will get the inner type of the array(s)
*/
public Class<?> getBaseType() {
- Class<?> clazz = type;
+ Class<?> clazz = getType();
while (clazz.isArray()) {
clazz = clazz.getComponentType();
}
@@ -237,6 +217,12 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
return new ValueDescriptor<>(name, type, constraints, format, units, arrayDimensions);
}
+ public ValueDescriptor<T> forMetaUseOnly() {
+ ValueDescriptor<T> newValueDescriptor = new ValueDescriptor<>(name, type, constraints, format, units, arrayDimensions);
+ newValueDescriptor.metaUseOnly = true;
+ return newValueDescriptor;
+ }
+
public void updateConstraints(ValueConstraint...valueConstraints) {
constraints = valueConstraints;
}
@@ -261,20 +247,21 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
return arrayDimensions != null && arrayDimensions > 0;
}
+ public boolean isMetaUseOnly() {
+ return metaUseOnly != null ? metaUseOnly : false;
+ }
+
@Override
public int hashCode() {
return Objects.hashCode(name);
}
- /**
- * Value descriptor names are unique identifiers so can use this for equality purposes
- */
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || !(ValueDescriptor.class.isAssignableFrom(obj.getClass()))) return false;
ValueDescriptor<?> that = (ValueDescriptor<?>)obj;
- return Objects.equals(name, that.name);
+ return Objects.equals(name, that.name) && Objects.equals(type, that.type);
}
/**
@@ -308,6 +295,7 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
", arrayDimensions=" + arrayDimensions +
", constraints=" + Arrays.toString(constraints) +
", format=" + format +
+ ", metaUseOnly=" + isMetaUseOnly() +
", units=" + Arrays.toString(units) +
'}';
}
diff --git a/model/src/main/java/org/openremote/model/value/ValueDescriptorHolder.java b/model/src/main/java/org/openremote/model/value/ValueDescriptorHolder.java
index d4b3c91b6..3874785ea 100644
--- a/model/src/main/java/org/openremote/model/value/ValueDescriptorHolder.java
+++ b/model/src/main/java/org/openremote/model/value/ValueDescriptorHolder.java
@@ -20,7 +20,6 @@
package org.openremote.model.value;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import org.openremote.model.util.TsIgnoreTypeParams;
@@ -30,9 +29,7 @@ import org.openremote.model.util.TsIgnoreTypeParams;
@TsIgnoreTypeParams
public interface ValueDescriptorHolder<T> {
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonSerialize(converter = ValueDescriptor.NameHolderToStringConverter.class)
ValueDescriptor<T> getType();
@JsonProperty
diff --git a/model/src/main/java/org/openremote/model/value/ValueHolder.java b/model/src/main/java/org/openremote/model/value/ValueHolder.java
index d0df25034..1207e7dd2 100644
--- a/model/src/main/java/org/openremote/model/value/ValueHolder.java
+++ b/model/src/main/java/org/openremote/model/value/ValueHolder.java
@@ -20,7 +20,6 @@
package org.openremote.model.value;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import java.util.Optional;
@@ -30,16 +29,16 @@ import java.util.Optional;
*/
public interface ValueHolder<T> {
- @JsonProperty
- @JsonSerialize(converter = ValueDescriptor.ValueDescriptorStringConverter.class)
- @JsonDeserialize(converter = ValueDescriptor.StringValueDescriptorConverter.class)
+ @JsonSerialize(converter = ValueDescriptor.NameHolderToStringConverter.class)
ValueDescriptor<T> getType();
+ Class<?> getTypeClass();
+
@JsonProperty
Optional<T> getValue();
/**
* Provides basic type casting/coercion useful for unknown values
*/
- <U> Optional<U> getValueAs(Class<U> valueType);
+ <U> Optional<U> getValue(Class<U> valueType);
}
diff --git a/model/src/main/java/org/openremote/model/value/ValueType.java b/model/src/main/java/org/openremote/model/value/ValueType.java
index 292fa529c..bfd34781e 100644
--- a/model/src/main/java/org/openremote/model/value/ValueType.java
+++ b/model/src/main/java/org/openremote/model/value/ValueType.java
@@ -19,9 +19,6 @@
*/
package org.openremote.model.value;
-import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.fasterxml.jackson.databind.node.BaseJsonNode;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.model.Constants;
import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ConnectionStatus;
@@ -54,7 +51,7 @@ public final class ValueType {
public static class StringMap extends HashMap<String, String> {}
public static class IntegerMap extends HashMap<String, Integer> {}
public static class DoubleMap extends HashMap<String, Double> {}
- public static class BooleanMap extends HashMap<String, Double> {}
+ public static class BooleanMap extends HashMap<String, Boolean> {}
public static class MultivaluedStringMap extends HashMap<String, List<String>> {}
public static final ValueDescriptor<Boolean> BOOLEAN = new ValueDescriptor<>("boolean", Boolean.class);
@@ -81,12 +78,6 @@ public final class ValueType {
public static final ValueDescriptor<MultivaluedStringMap> MULTIVALUED_TEXT_MAP = new ValueDescriptor<>("multivaluedTextMap", MultivaluedStringMap.class);
- public static final ValueDescriptor<ObjectNode> JSON_OBJECT = new ValueDescriptor<>("JSONObject", ObjectNode.class);
-
- public static final ValueDescriptor<ArrayNode> JSON_ARRAY = new ValueDescriptor<>("JSONArray", ArrayNode.class);
-
- public static final ValueDescriptor<BaseJsonNode> JSON = new ValueDescriptor<>("JSON", BaseJsonNode.class);
-
public static final ValueDescriptor<Integer> POSITIVE_INTEGER = new ValueDescriptor<>("positiveInteger", Integer.class,
new ValueConstraint.Min(0)
);
@@ -110,7 +101,9 @@ public final class ValueType {
public static final ValueDescriptor<Byte> BYTE = new ValueDescriptor<>("byte", Byte.class);
- public static final ValueDescriptor<Long> TIMESTAMP = new ValueDescriptor<>("timestamp", Long.class);
+ public static final ValueDescriptor<Long> TIMESTAMP = new ValueDescriptor<>("timestamp", Long.class,
+ new ValueConstraint.Min(0)
+ );
public static final ValueDescriptor<String> TIMESTAMP_ISO8601 = new ValueDescriptor<>("timestampISO8601", String.class,
new ValueConstraint.Pattern(Constants.ISO8601_DATETIME_REGEXP)
@@ -165,11 +158,11 @@ public final class ValueType {
new ValueConstraint.Pattern(Constants.IP_REGEXP)
);
- public static final ValueDescriptor<AttributeLink> ATTRIBUTE_LINK = new ValueDescriptor<>("attributeLink", AttributeLink.class);
+ public static final ValueDescriptor<AttributeLink> ATTRIBUTE_LINK = new ValueDescriptor<>("attributeLink", AttributeLink.class).forMetaUseOnly();
- public static final ValueDescriptor<AttributeRef> ATTRIBUTE_REF = new ValueDescriptor<>("attributeReference", AttributeRef.class);
+ public static final ValueDescriptor<AttributeRef> ATTRIBUTE_REF = new ValueDescriptor<>("attributeReference", AttributeRef.class).forMetaUseOnly();
- public static final ValueDescriptor<AttributeState> ATTRIBUTE_STATE = new ValueDescriptor<>("attributeState", AttributeState.class);
+ public static final ValueDescriptor<AttributeState> ATTRIBUTE_STATE = new ValueDescriptor<>("attributeState", AttributeState.class).forMetaUseOnly();
public static final ValueDescriptor<GeoJSONPoint> GEO_JSON_POINT = new ValueDescriptor<>("GEO_JSONPoint", GeoJSONPoint.class);
@@ -187,11 +180,11 @@ public final class ValueType {
public static final ValueDescriptor<UsernamePassword> USERNAME_AND_PASSWORD = new ValueDescriptor<>("usernameAndPassword", UsernamePassword.class);
- public static final ValueDescriptor<ValueFormat> VALUE_FORMAT = new ValueDescriptor<>("valueFormat", ValueFormat.class);
+ public static final ValueDescriptor<ValueFormat> VALUE_FORMAT = new ValueDescriptor<>("valueFormat", ValueFormat.class).forMetaUseOnly();
- public static final ValueDescriptor<ValueConstraint> VALUE_CONSTRAINT = new ValueDescriptor<>("valueConstraint", ValueConstraint.class);
+ public static final ValueDescriptor<ValueConstraint> VALUE_CONSTRAINT = new ValueDescriptor<>("valueConstraint", ValueConstraint.class).forMetaUseOnly();
- public static final ValueDescriptor<AgentLink> VALUE_AGENT_LINK = new ValueDescriptor<>("agentLink", AgentLink.class);
+ public static final ValueDescriptor<AgentLink> VALUE_AGENT_LINK = new ValueDescriptor<>("agentLink", AgentLink.class).forMetaUseOnly();
public static final ValueDescriptor<CronExpressionParser> CRON_EXPRESSION = new ValueDescriptor<>("CRONExpression", CronExpressionParser.class);
@@ -203,9 +196,11 @@ public final class ValueType {
new ValueConstraint.Pattern(Constants.WS_URL_REGEXP)
);
- public static final ValueDescriptor<AssetQuery> ASSET_QUERY = new ValueDescriptor<>("assetQuery", AssetQuery.class);
+ public static final ValueDescriptor<AssetQuery> ASSET_QUERY = new ValueDescriptor<>("assetQuery", AssetQuery.class).forMetaUseOnly();
+
+ public static final ValueDescriptor<ForecastConfiguration> FORECAST_CONFIGURATION = new ValueDescriptor<>("forecastConfiguration", ForecastConfiguration.class).forMetaUseOnly();
- public static final ValueDescriptor<ForecastConfiguration> FORECAST_CONFIGURATION = new ValueDescriptor<>("forecastConfiguration", ForecastConfiguration.class);
+ public static final ValueDescriptor<ValueDescriptor> VALUE_DESCRIPTOR_VALUE_DESCRIPTOR = new ValueDescriptor<>("valueDescriptor", ValueDescriptor.class).forMetaUseOnly();
protected ValueType() {
}
diff --git a/model/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider b/model/src/main/resources/META-INF/services/jakarta.validation.spi.ValidationProvider
similarity index 100%
rename from model/src/main/resources/META-INF/services/javax.validation.spi.ValidationProvider
rename to model/src/main/resources/META-INF/services/jakarta.validation.spi.ValidationProvider
diff --git a/model/src/main/resources/ValidationMessages.properties b/model/src/main/resources/ValidationMessages.properties
index 977d88faa..e2d2aedfb 100644
--- a/model/src/main/resources/ValidationMessages.properties
+++ b/model/src/main/resources/ValidationMessages.properties
@@ -1,58 +1,68 @@
-Realm.displayName.NotNull = Realm name can not be empty.
-Realm.displayName.Size = Realm name must be at least {min} and not more than {max} characters long.
-Realm.realm.NotNull = Realm realm can not be empty.
-Realm.realm.Size = Realm realm must be at least {min} and not more than {max} characters long.
-Realm.realm.Pattern = Realm realm must be all lowercase characters and/or numbers.
-Realm.masterDeleted = The master realm can not be deleted.
-Realm.masterDisabled = The master realm can not be disabled.
-Realm.masterRealmChanged = The master realm identifier can not be changed.
+Realm.displayName.NotNull = Realm name can not be empty
+Realm.displayName.Size = Realm name must be at least {min} and not more than {max} characters long
+Realm.realm.NotNull = Realm realm can not be empty
+Realm.realm.Size = Realm realm must be at least {min} and not more than {max} characters long
+Realm.realm.Pattern = Realm realm must be all lowercase characters and/or numbers
+Realm.masterDeleted = The master realm can not be deleted
+Realm.masterDisabled = The master realm can not be disabled
+Realm.masterRealmChanged = The master realm identifier can not be changed
+User.username.NotNull = Username can not be empty
+User.username.Size = Username must be at least {min} and not more than {max} characters long
+User.username.Pattern = Username can only contain letters, numbers, underscore and dash
+User.firstName.Size = User's first name can not be more than {max} characters long
+User.lastName.Size = User's last name can not be more than {max} characters long
+User.email.Email = Please provide a valid email address
+User.masterAdminDeleted = The master realm admin user can not be deleted
+User.masterAdminDisabled = The master realm admin user can not be disabled
+Ruleset.name.NotNull = name can not be empty
+Ruleset.name.Size = name must be at least {min} and not more than {max} characters long
+Asset.id.Pattern = ID must be a valid BASE-62 encoded UUID (22 characters long)
+Asset.version.Min = version cannot be less than 0
+Asset.name.NotBlank = name can not be empty
+Asset.name.Size = name must be at least {min} and not more than {max} characters long
+Asset.type.NotBlank = type can not be empty
+Asset.type.Size = type must be at least {min} and not more than {max} characters long
+Asset.type.Invalid = type does not match any currently loaded Asset Descriptor
+Asset.parentId.Pattern = parent ID must be a valid BASE-62 encoded UUID (22 characters long)
+Asset.realm.NotBlank = realm can not be empty
+Asset.realm.Size = realm must be at least {min} and not more than {max} characters long
+Asset.attribute.Missing = required attribute is missing
+Asset.attribute.value.Missing = attribute value is missing
+Asset.attribute.type.Mismatch = attribute value type does not match the attribute descriptor
+Asset.valueHolder.name.NotBlank = attribute and meta item names can not be empty
+Dashboard.realm.NotBlank = Dashboard realm cannot be empty
+Dashboard.ownerId.NotBlank = Dashboard ownerId cannot be empty
+Dashboard.displayName.NotBlank = Dashboard displayName cannot be empty
+Dashboard.template.NotNull = Dashboard template cannot be null
+Dashboard.template.columns.Min = Template columns cannot empty nor set to 0
+Dashboard.template.maxScreenWidth.Min = Template maxScreenWidth cannot be empty nor set to 0
+Dashboard.template.screenPresets.Null = Template screenPresets cannot be null
+Dashboard.screenPreset.displayName.NotBlank = ScreenPreset displayName cannot be empty
+Dashboard.screenPreset.breakpoint.Min = ScreenPreset breakpoint cannot be empty nor set to 0
+Dashboard.screenPreset.scalingPreset.NotNull = ScreenPreset scalingPreset cannot be null
+Dashboard.widget.displayName.NotBlank = Widget displayName cannot be empty
+Dashboard.widget.gridItem.NotNull = Widget gridItem cannot be null
+Dashboard.widget.widgetTypeId.NotNull = Widget widgetTypeId cannot be null
+Dashboard.gridItem.w.Min = GridItem w (width) cannot be empty nor set to 0
+Dashboard.gridItem.h.Min = GridItem h (height) cannot be empty nor set to 0
+GatewayConnection.host.NotNull = Gateway connection host can not be empty
+GatewayConnection.host.Size = Gateway connection host must be at least {min} and not more than {max} characters long
+GatewayConnection.port.Range = Gateway connection port must be between {min} and {max}
+GatewayConnection.clientId.NotNull = Gateway connection client ID can not be empty
+GatewayConnection.clientId.Size = Gateway connection client ID must be at least {min} and not more than {max} characters long
+GatewayConnection.clientSecret.NotNull = Gateway connection client secret can not be empty
+GatewayConnection.clientSecret.Size = Gateway connection client secret must be at least {min} and not more than {max} characters long
-User.username.NotNull = Username can not be empty.
-User.username.Size = Username must be at least {min} and not more than {max} characters long.
-User.username.Pattern = Username can only contain letters, numbers, underscore and dash.
-User.firstName.Size = User's first name can not be more than {max} characters long.
-User.lastName.Size = User's last name can not be more than {max} characters long.
-User.email.Email = Please provide a valid email address.
-User.masterAdminDeleted = The master realm admin user can not be deleted.
-User.masterAdminDisabled = The master realm admin user can not be disabled.
-
-Ruleset.name.NotNull = Ruleset name can not be empty.
-Ruleset.name.Size = Ruleset name must be at least {min} and not more than {max} characters long.
-
-Asset.id.Pattern = Asset ID must be a valid BASE-62 encoded UUID (22 characters long).
-Asset.version.Min = Asset version cannot be less than 0.
-Asset.name.NotBlank = Asset name can not be empty.
-Asset.name.Size = Asset name must be at least {min} and not more than {max} characters long.
-Asset.type.NotBlank = Asset type can not be empty.
-Asset.type.Size = Asset type must be at least {min} and not more than {max} characters long.
-Asset.type.Invalid = Asset type does not match any currently loaded Asset Descriptor.
-Asset.parentId.Pattern = Asset parent ID must be a valid BASE-62 encoded UUID (22 characters long).
-Asset.realm.NotBlank = Asset realm can not be empty.
-Asset.realm.Size = Asset realm must be at least {min} and not more than {max} characters long.
-Asset.attribute.Missing = Asset required attribute is missing.
-Asset.attribute.type.Mismatch = Asset attribute value type does not match the attribute descriptor.
-Asset.valueHolder.name.NotBlank = Asset attribute and meta item names can not be empty.
-
-Dashboard.realm.NotBlank = Dashboard realm cannot be empty.
-Dashboard.ownerId.NotBlank = Dashboard ownerId cannot be empty.
-Dashboard.displayName.NotBlank = Dashboard displayName cannot be empty.
-Dashboard.template.NotNull = Dashboard template cannot be null.
-Dashboard.template.columns.Min = Template columns cannot empty nor set to 0.
-Dashboard.template.maxScreenWidth.Min = Template maxScreenWidth cannot be empty nor set to 0.
-Dashboard.template.screenPresets.Null = Template screenPresets cannot be null.
-Dashboard.screenPreset.displayName.NotBlank = ScreenPreset displayName cannot be empty.
-Dashboard.screenPreset.breakpoint.Min = ScreenPreset breakpoint cannot be empty nor set to 0.
-Dashboard.screenPreset.scalingPreset.NotNull = ScreenPreset scalingPreset cannot be null.
-Dashboard.widget.displayName.NotBlank = Widget displayName cannot be empty.
-Dashboard.widget.gridItem.NotNull = Widget gridItem cannot be null.
-Dashboard.widget.widgetTypeId.NotNull = Widget widgetTypeId cannot be null.
-Dashboard.gridItem.w.Min = GridItem w (width) cannot be empty nor set to 0.
-Dashboard.gridItem.h.Min = GridItem h (height) cannot be empty nor set to 0.
-
-GatewayConnection.host.NotNull = Gateway connection host can not be empty.
-GatewayConnection.host.Size = Gateway connection host must be at least {min} and not more than {max} characters long.
-GatewayConnection.port.Range = Gateway connection port must be between {min} and {max}.
-GatewayConnection.clientId.NotNull = Gateway connection client ID can not be empty.
-GatewayConnection.clientId.Size = Gateway connection client ID must be at least {min} and not more than {max} characters long.
-GatewayConnection.clientSecret.NotNull = Gateway connection client secret can not be empty.
-GatewayConnection.clientSecret.Size = Gateway connection client secret must be at least {min} and not more than {max} characters long.
+Asset.invalid.message = Asset is not valid
+ValueConstraint.Future.message = must be a future date
+ValueConstraint.FutureOrPresent.message = must be a date in the present or in the future
+ValueConstraint.Max.message = must be less than or equal to {value}
+ValueConstraint.Min.message = must be greater than or equal to {value}
+ValueConstraint.NotBlank.message = must not be blank
+ValueConstraint.NotEmpty.message = must not be empty
+ValueConstraint.NotNull.message = must not be null
+ValueConstraint.Past.message = must be a past date
+ValueConstraint.PastOrPresent.message = must be a date in the past or in the present
+ValueConstraint.Pattern.message = must match "{value}"
+ValueConstraint.Size.message = size must be between {min} and {max}
+ValueConstraint.AllowedValues.message = must be one of {values}
diff --git a/project.gradle b/project.gradle
index f5062f96b..5f41c4373 100644
--- a/project.gradle
+++ b/project.gradle
@@ -8,12 +8,27 @@ import static org.jetbrains.gradle.ext.ShortenCommandLine.MANIFEST
import org.jetbrains.gradle.ext.Application
import org.jetbrains.gradle.ext.JUnit
-
// Configure versions in gradle.properties (putting a gradle.properties file
// in a subproject only overrides root properties of same name for the actual
// subproject, not for its children!)
version = hasProperty("openremoteVersion") ? openremoteVersion : "0.0.0"
+configurations.all {
+ resolutionStrategy {
+
+ //failOnVersionConflict()
+
+ // This has been replaced with eclipse angus implementation
+ exclude group: "com.sun.activation", module: "jakarta.activation"
+
+ eachDependency { DependencyResolveDetails details ->
+ if (details.requested.group == 'org.eclipse.angus' && details.requested.name == 'angus-activation' && details.requested.version == '1.0.0') {
+ details.useVersion '2.0.0'
+ }
+ }
+ }
+}
+
// Ensure git hook creation task is executed
if (project == rootProject) {
@@ -315,6 +330,9 @@ plugins.withType(JavaPlugin).whenPluginAdded {
options.encoding = 'UTF-8'
}
+ // Allow dependencyInsight checks across all projects
+ task allDependencyInsight(type: DependencyInsightReportTask) {}
+
// JAR/ZIP base name is the fully qualified subproject name
archivesBaseName = "${rootProject.name}${path.replaceAll(":", "-")}"
}
diff --git a/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoSetup.java b/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoSetup.java
index 1e7ebd0b6..5b941e66d 100644
--- a/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoSetup.java
+++ b/setup/src/demo/java/org/openremote/setup/demo/ManagerDemoSetup.java
@@ -24,7 +24,6 @@ import org.openremote.agent.protocol.http.HTTPAgentLink;
import org.openremote.agent.protocol.simulator.SimulatorAgent;
import org.openremote.agent.protocol.simulator.SimulatorAgentLink;
import org.openremote.container.util.UniqueIdentifierGenerator;
-import org.openremote.manager.mqtt.ConnectionMonitorHandler;
import org.openremote.manager.security.ManagerIdentityProvider;
import org.openremote.manager.setup.ManagerSetup;
import org.openremote.model.Constants;
@@ -40,22 +39,23 @@ import org.openremote.model.attribute.MetaItem;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.security.Realm;
import org.openremote.model.simulator.SimulatorReplayDatapoint;
-import org.openremote.model.util.Pair;
import org.openremote.model.value.*;
-import org.openremote.setup.demo.model.*;
-import org.openremote.setup.demo.model.HarvestRobotAsset.*;
-
-import static org.openremote.model.Constants.*;
-import static org.openremote.model.value.MetaItemType.*;
+import org.openremote.setup.demo.model.HarvestRobotAsset;
+import org.openremote.setup.demo.model.HarvestRobotAsset.OperationMode;
+import org.openremote.setup.demo.model.HarvestRobotAsset.VegetableType;
+import org.openremote.setup.demo.model.IrrigationAsset;
+import org.openremote.setup.demo.model.SoilSensorAsset;
import java.time.Duration;
import java.time.LocalTime;
+import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
-import java.util.Arrays;
import java.util.function.Supplier;
import static java.time.temporal.ChronoField.SECOND_OF_DAY;
+import static org.openremote.model.Constants.*;
+import static org.openremote.model.value.MetaItemType.*;
import static org.openremote.model.value.ValueType.MultivaluedStringMap;
public class ManagerDemoSetup extends ManagerSetup {
@@ -828,7 +828,7 @@ public class ManagerDemoSetup extends ManagerSetup {
agentLink.setPollingMillis((int)halfHourInMillis);
weather.getAttributes().addOrReplace(
- new Attribute<>("currentWeather", ValueType.JSON_OBJECT)
+ new Attribute<>("currentWeather")
.addMeta(
new MetaItem<>(MetaItemType.AGENT_LINK, agentLink),
new MetaItem<>(MetaItemType.LABEL, "Open Weather Map API weather end point"),
diff --git a/setup/src/demo/java/org/openremote/setup/demo/model/ManufacturerAssetModelProvider.java b/setup/src/demo/java/org/openremote/setup/demo/model/ManufacturerAssetModelProvider.java
index 5f1959455..44ebac364 100644
--- a/setup/src/demo/java/org/openremote/setup/demo/model/ManufacturerAssetModelProvider.java
+++ b/setup/src/demo/java/org/openremote/setup/demo/model/ManufacturerAssetModelProvider.java
@@ -20,14 +20,6 @@
package org.openremote.setup.demo.model;
import org.openremote.model.AssetModelProvider;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.MetaItemDescriptor;
-import org.openremote.model.value.ValueDescriptor;
-
-import java.util.List;
-import java.util.Map;
public class ManufacturerAssetModelProvider implements AssetModelProvider {
@@ -35,29 +27,4 @@ public class ManufacturerAssetModelProvider implements AssetModelProvider {
public boolean useAutoScan() {
return true;
}
-
- @Override
- public AssetDescriptor<?>[] getAssetDescriptors() {
- return new AssetDescriptor[0];
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<ValueDescriptor<?>>> getValueDescriptors() {
- return null;
- }
-
- @Override
- public void onAssetModelFinished() {
-
- }
}
diff --git a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
index 02580aa19..73158fbf8 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/ManagerTestSetup.java
@@ -19,7 +19,6 @@
*/
package org.openremote.setup.integration;
-import com.fasterxml.jackson.databind.node.ObjectNode;
import org.openremote.agent.protocol.simulator.SimulatorAgent;
import org.openremote.agent.protocol.simulator.SimulatorAgentLink;
import org.openremote.container.util.UniqueIdentifierGenerator;
@@ -35,13 +34,13 @@ import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.security.Realm;
-import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.ValueConstraint;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.impl.ColourRGB;
import java.util.Arrays;
import java.util.List;
+import java.util.Map;
import static org.openremote.manager.datapoint.AssetDatapointService.OR_DATA_POINTS_MAX_AGE_DAYS_DEFAULT;
import static org.openremote.model.Constants.*;
@@ -146,7 +145,7 @@ public class ManagerTestSetup extends ManagerSetup {
lobby.setParent(groundFloor);
lobby.getAttributes().addOrReplace(
new Attribute<>(Asset.LOCATION, SMART_OFFICE_LOCATION),
- new Attribute<>("lobbyLocations", JSON_OBJECT.asArray())
+ new Attribute<>("lobbyLocations")
);
lobby = assetStorageService.merge(lobby);
lobbyId = lobby.getId();
@@ -460,8 +459,9 @@ public class ManagerTestSetup extends ManagerSetup {
apartment2Livingroom.setAccessPublicRead(true);
apartment2Livingroom.setParent(apartment2);
- ObjectNode objectMap = ValueUtil.createJsonObject();
- objectMap.put("cactus", 0.8);
+ Map<String, Object> objectMap = Map.of(
+ "cactus", 0.8
+ );
apartment2Livingroom.getAttributes().addOrReplace(
new Attribute<>(Asset.LOCATION, new GeoJSONPoint(5.454109, 51.446631)).addMeta(
@@ -508,7 +508,7 @@ public class ManagerTestSetup extends ManagerSetup {
new MetaItem<>(LABEL, "Lightswitch Trigger Times"),
new MetaItem<>(RULE_STATE, true)
),
- new Attribute<>("plantsWaterLevels", JSON_OBJECT, objectMap)
+ new Attribute<>("plantsWaterLevels", null, objectMap)
.addMeta(
new MetaItem<>(LABEL, "Water levels of the plants"),
new MetaItem<>(RULE_STATE, true)
diff --git a/setup/src/integration/java/org/openremote/setup/integration/model/TestAssetModelProvider.java b/setup/src/integration/java/org/openremote/setup/integration/model/TestAssetModelProvider.java
index 6194df9d2..f5d7f60d9 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/model/TestAssetModelProvider.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/model/TestAssetModelProvider.java
@@ -20,43 +20,10 @@
package org.openremote.setup.integration.model;
import org.openremote.model.AssetModelProvider;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.MetaItemDescriptor;
-import org.openremote.model.value.ValueDescriptor;
-
-import java.util.List;
-import java.util.Map;
public class TestAssetModelProvider implements AssetModelProvider {
@Override
public boolean useAutoScan() {
return true;
}
-
- @Override
- public AssetDescriptor<?>[] getAssetDescriptors() {
- return new AssetDescriptor[0];
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<MetaItemDescriptor<?>>> getMetaItemDescriptors() {
- return null;
- }
-
- @Override
- public Map<Class<? extends Asset<?>>, List<ValueDescriptor<?>>> getValueDescriptors() {
- return null;
- }
-
- @Override
- public void onAssetModelFinished() {
-
- }
}
diff --git a/setup/src/integration/java/org/openremote/setup/integration/model/asset/ModelTestAsset.java b/setup/src/integration/java/org/openremote/setup/integration/model/asset/ModelTestAsset.java
new file mode 100644
index 000000000..12b0075f2
--- /dev/null
+++ b/setup/src/integration/java/org/openremote/setup/integration/model/asset/ModelTestAsset.java
@@ -0,0 +1,110 @@
+package org.openremote.setup.integration.model.asset;
+
+import jakarta.persistence.Entity;
+import jakarta.validation.constraints.Max;
+import jakarta.validation.constraints.Min;
+import jakarta.validation.constraints.NotNull;
+import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetDescriptor;
+import org.openremote.model.attribute.MetaItem;
+import org.openremote.model.value.*;
+
+import java.io.Serializable;
+import java.util.Date;
+
+@Entity
+public class ModelTestAsset extends Asset<ModelTestAsset> {
+
+ public enum TestValue {
+ ENUM_1,
+ ENUM_2,
+ ENUM_3,
+ ENUM_4
+ }
+
+ public static class TestObject implements Serializable {
+ @Min(100)
+ @Max(200)
+ protected int range;
+ @NotNull
+ protected Boolean active;
+
+ public TestObject(int range, Boolean active) {
+ this.range = range;
+ this.active = active;
+ }
+
+ public int getRange() {
+ return range;
+ }
+
+ public Boolean getActive() {
+ return active;
+ }
+ }
+
+ public static final ValueDescriptor<TestValue> TEST_VALUE_DESCRIPTOR = new ValueDescriptor<>("testValue", TestValue.class);
+ public static final ValueDescriptor<TestObject> TEST_OBJECT_VALUE_DESCRIPTOR = new ValueDescriptor<>("testObjectValue", TestObject.class);
+
+ public static final AttributeDescriptor<Integer> REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("positiveInt", ValueType.POSITIVE_INTEGER,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotNull()))
+ );
+
+ public static final AttributeDescriptor<Integer> NEGATIVE_INT_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("negativeInt", ValueType.NEGATIVE_INTEGER).withOptional(true);
+
+ public static final AttributeDescriptor<String> SIZE_STRING_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("sizeString", ValueType.TEXT,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Size(5,10)))
+ ).withOptional(true);
+ public static final AttributeDescriptor<ValueType.DoubleMap> SIZE_MAP_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("sizeMap", ValueType.NUMBER_MAP,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Size(2,3)))
+ ).withOptional(true);
+ public static final AttributeDescriptor<String[]> SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("sizeArray", ValueType.TEXT.asArray(),
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Size(2,3)))
+ ).withOptional(true);
+
+ public static final AttributeDescriptor<TestValue> ALLOWED_VALUES_ENUM_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("allowedValuesEnum", TEST_VALUE_DESCRIPTOR).withOptional(true);
+ public static final AttributeDescriptor<TestObject> OBJECT_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("object", TEST_OBJECT_VALUE_DESCRIPTOR).withOptional(true);
+ public static final AttributeDescriptor<String> ALLOWED_VALUES_STRING_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("allowedValuesString", ValueType.TEXT,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.AllowedValues("Allowed1", "Allowed2")))
+ ).withOptional(true);
+ public static final AttributeDescriptor<Double> ALLOWED_VALUES_NUMBER_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("allowedValuesNumber", ValueType.NUMBER,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.AllowedValues(1.5d, 2.5d)))
+ ).withOptional(true);
+
+ public static final AttributeDescriptor<Long> PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("pastTimestamp", ValueType.TIMESTAMP,
+ new MetaItem<>(MetaItemType.CONSTRAINTS)
+ ).withConstraints(ValueConstraint.constraints(new ValueConstraint.Past())).withOptional(true);
+
+ public static final AttributeDescriptor<Date> PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("pastOrPresentDate", ValueType.DATE_AND_TIME,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.PastOrPresent()))
+ ).withOptional(true);
+ public static final AttributeDescriptor<String> FUTURE_ISO8601_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("futureISO8601", ValueType.TIMESTAMP_ISO8601,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Future()))
+ ).withOptional(true);
+ public static final AttributeDescriptor<Long> FUTURE_OR_PRESENT_TIMESTAMP_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("futureOrPresentTimestamp", ValueType.TIMESTAMP,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.FutureOrPresent()))
+ ).withOptional(true);
+ public static final AttributeDescriptor<String> NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("notEmptyString", ValueType.TEXT,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotEmpty()))
+ ).withOptional(true);
+ public static final AttributeDescriptor<Integer[]> NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("notEmptyArray", ValueType.INTEGER.asArray(),
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotEmpty()))
+ ).withOptional(true);
+ public static final AttributeDescriptor<ValueType.BooleanMap> NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("notEmptyMap", ValueType.BOOLEAN_MAP,
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotEmpty()))
+ ).withOptional(true);
+
+ public static final AttributeDescriptor<String> NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR = new AttributeDescriptor<>("notBlankString", ValueType.TEXT,
+ new MetaItem<>(MetaItemType.CONSTRAINTS)
+ ).withConstraints(ValueConstraint.constraints(new ValueConstraint.NotBlank().setMessage("Not blank custom message")))
+ .withOptional(true);
+
+ public static final AssetDescriptor<ModelTestAsset> MODEL_TEST_ASSET_DESCRIPTOR = new AssetDescriptor<>("", "", ModelTestAsset.class);
+
+ protected ModelTestAsset() {
+ }
+
+ public ModelTestAsset(String name) {
+ super(name);
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 55ce74671..ac1506a3c 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -52,7 +52,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
conditions.eventually {
assert agentService.protocolInstanceMap.get(managerTestSetup.agentId) != null
assert ((SimulatorProtocol) agentService.protocolInstanceMap.get(managerTestSetup.agentId)).linkedAttributes.size() == 4
- assert ((SimulatorProtocol) agentService.protocolInstanceMap.get(managerTestSetup.agentId)).linkedAttributes.get(new AttributeRef(managerTestSetup.thingId, "light1PowerConsumption")).getValueAs(Double.class).orElse(0d) == 12.345d
+ assert ((SimulatorProtocol) agentService.protocolInstanceMap.get(managerTestSetup.agentId)).linkedAttributes.get(new AttributeRef(managerTestSetup.thingId, "light1PowerConsumption")).getValue(Double.class).orElse(0d) == 12.345d
}
when: "an attribute linked to the simulator agent receives some values"
@@ -67,7 +67,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAs(Double.class) }.orElse(null) == 13.3d
+ assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValue(Double.class) }.orElse(null) == 13.3d
}
when: "a simulated sensor receives a new value"
@@ -78,7 +78,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAs(Double.class) }.orElse(null) == 13.5d
+ assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValue(Double.class) }.orElse(null) == 13.5d
}
when: "a simulated sensor receives a new value"
@@ -89,7 +89,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAs(Double.class) }.orElse(null) == 14.4d
+ assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValue(Double.class) }.orElse(null) == 14.4d
}
when: "a simulated sensor receives a new value"
@@ -100,7 +100,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValueAs(Double.class) }.orElse(null) == 15.5d
+ assert thing.getAttribute("light1PowerConsumption").flatMap { it.getValue(Double.class) }.orElse(null) == 15.5d
}
when: "a simulated sensor receives a new value"
@@ -191,7 +191,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert !thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValueAs(Boolean.class) }.orElse(null)
+ assert !thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValue(Boolean.class) }.orElse(null)
}
when: "a simulated sensor receives a new value"
@@ -202,7 +202,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValueAs(Boolean.class) }.orElse(null)
+ assert thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValue(Boolean.class) }.orElse(null)
}
when: "a simulated sensor receives a new value"
@@ -213,7 +213,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
then: "the attribute should be updated"
conditions.eventually {
def thing = assetStorageService.find(managerTestSetup.thingId, true)
- assert !thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValueAs(Boolean.class) }.orElse(null)
+ assert !thing.getAttribute(thingLightToggleAttributeName).flatMap { it.getValue(Boolean.class) }.orElse(null)
}
expect: "the datapoints to be stored"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index 218f9bdb6..595dca23e 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -1,20 +1,21 @@
package org.openremote.test.assets
+
+import jakarta.ws.rs.WebApplicationException
+import org.jboss.resteasy.api.validation.ViolationReport
import org.openremote.container.util.UniqueIdentifierGenerator
import org.openremote.manager.setup.SetupService
-import org.openremote.setup.integration.KeycloakTestSetup
-import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.impl.RoomAsset
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
import org.openremote.model.value.ValueType
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.WebApplicationException
-
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
@@ -60,9 +61,13 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
assetResource.update(null, testAsset.getId(), testAsset)
- then: "the request should be bad"
+ then: "the request should fail validation and return a validation report indicating the failure(s)"
WebApplicationException ex = thrown()
ex.response.status == 400
+ def report = ex.response.readEntity(ViolationReport)
+ report != null
+ report.propertyViolations.size() == 1
+ report.propertyViolations.get(0).path == "attributes[illegal- Attribute:name&&&].name"
when: "an asset is stored with a non-empty attribute value"
testAsset = assetResource.get(null, testAsset.getId())
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 26aa4cb42..66a7f6ce2 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -1,5 +1,7 @@
package org.openremote.test.assets
+import jakarta.ws.rs.ForbiddenException
+import jakarta.ws.rs.WebApplicationException
import org.openremote.manager.setup.SetupService
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetResource
@@ -9,15 +11,12 @@ import org.openremote.model.attribute.*
import org.openremote.model.query.AssetQuery
import org.openremote.model.query.filter.ParentPredicate
import org.openremote.model.query.filter.RealmPredicate
-import org.openremote.test.ManagerContainerTrait
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
+import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.ForbiddenException
-import jakarta.ws.rs.WebApplicationException
-
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
@@ -637,18 +636,18 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment1Livingroom.name == "Living Room 1"
def resultAttributes = apartment1Livingroom.getAttributes()
resultAttributes.size() == 7
- def currentTemperatureAttr = apartment1Livingroom.getAttribute("currentTemperature", NUMBER.type).orElse(null)
+ def currentTemperatureAttr = apartment1Livingroom.getAttribute("currentTemperature").orElse(null)
currentTemperatureAttr.getType() == NUMBER
!currentTemperatureAttr.getValue().isPresent()
MetaMap resultMeta = currentTemperatureAttr.getMeta()
resultMeta.size() == 8
- resultMeta.getValueOrDefault(LABEL) == "Current temperature"
+ resultMeta.get(LABEL).flatMap {it.value}.orElse(null) == "Current temperature"
resultMeta.getValue(READ_ONLY).orElse(false)
resultMeta.has(AGENT_LINK)
- resultMeta.getValueOrDefault(ACCESS_RESTRICTED_READ)
- resultMeta.getValueOrDefault(UNITS) != null
- resultMeta.getValueOrDefault(UNITS)[0] == UNITS_CELSIUS
+ resultMeta.getValue(ACCESS_RESTRICTED_READ).orElse(false)
+ resultMeta.getValue(UNITS).isPresent()
+ resultMeta.getValue(UNITS).get()[0] == UNITS_CELSIUS
when: "an asset is retrieved by ID in a foreign realm"
assetResource.get(null, managerTestSetup.thingId)
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 893b5a765..d5b386142 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -193,5 +193,12 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
then: "result should match"
userAssetLinks.length == 0
+
+ when: "all of a user assets are deleted"
+ assetResource.deleteAllUserAssetLinks(null, keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id)
+ userAssetLinks = assetResource.getUserAssetLinks(null, keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id, null)
+
+ then: "result should match"
+ userAssetLinks.length == 0
}
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AttributeLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AttributeLinkingTest.groovy
index 2bcaec374..417ec6a82 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AttributeLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AttributeLinkingTest.groovy
@@ -43,7 +43,7 @@ class AttributeLinkingTest extends Specification implements ManagerContainerTrai
asset1.setRealm(Constants.MASTER_REALM)
asset1.addOrReplaceAttributes(
new Attribute<>("button", TEXT, "RELEASED"),
- new Attribute<>("array", JSON_OBJECT.asArray(), null),
+ new Attribute<>("array", null, null),
new Attribute<>("crossRealm", TEXT, null)
)
asset1 = assetStorageService.merge(asset1)
@@ -62,16 +62,18 @@ class AttributeLinkingTest extends Specification implements ManagerContainerTrai
assert asset2.id != null
when: "attributes from one asset is linked to attributes on the other"
- def converterOnOff = ValueUtil.createJsonObject()
- converterOnOff.put("PRESSED", "@TOGGLE")
- converterOnOff.put("RELEASED", "@IGNORE")
- converterOnOff.put("LONG_PRESSED", "@IGNORE")
+ def converterOnOff = Map.of(
+ "PRESSED", "@TOGGLE",
+ "RELEASED", "@IGNORE",
+ "LONG_PRESSED", "@IGNORE"
+ )
def attributeLinkOnOff = new AttributeLink(new AttributeRef(asset2.id, "lightOnOff"), converterOnOff, null)
- def converterCounter = ValueUtil.createJsonObject()
- converterCounter.put("PRESSED", "@INCREMENT")
- converterCounter.put("RELEASED", "@DECREMENT")
- converterCounter.put("LONG_PRESSED", "@IGNORE")
+ def converterCounter = Map.of(
+ "PRESSED", "@INCREMENT",
+ "RELEASED", "@DECREMENT",
+ "LONG_PRESSED", "@IGNORE"
+ )
def attributeLinkCounter = new AttributeLink(new AttributeRef(asset2.id, "counter"), converterCounter, null)
def attributeLinkProp = new AttributeLink(new AttributeRef(asset2.id, "item2Prop1"), null, [
@@ -98,7 +100,7 @@ class AttributeLinkingTest extends Specification implements ManagerContainerTrai
then: "the linked attribute value should be toggled on"
conditions.eventually {
asset2 = assetStorageService.find(asset2.id, true)
- assert asset2.getAttribute("lightOnOff", Boolean.class).flatMap{it.value}.orElse(false)
+ assert asset2.getAttribute("lightOnOff").flatMap{it.value}.orElse(false)
}
when: "the button is pressed again for a short period"
@@ -106,6 +108,7 @@ class AttributeLinkingTest extends Specification implements ManagerContainerTrai
new AttributeState(new AttributeRef(asset1.id, "button"), "PRESSED")
)
assetProcessingService.sendAttributeEvent(buttonPressed)
+ Thread.sleep(200)
advancePseudoClock(1, TimeUnit.SECONDS, container)
buttonReleased = new AttributeEvent(
new AttributeState(new AttributeRef(asset1.id, "button"), "RELEASED")
@@ -115,7 +118,7 @@ class AttributeLinkingTest extends Specification implements ManagerContainerTrai
then: "the linked attribute value should be toggled off"
conditions.eventually {
asset2 = assetStorageService.find(asset2.id, true)
- assert !asset2.getAttribute("lightOnOff", Boolean.class).flatMap{it.value}.orElse(false)
+ assert !asset2.getAttribute("lightOnOff").flatMap{it.value}.orElse(false)
}
when: "a long button press occurs"
def buttonLongPressed = new AttributeEvent(
diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
index df23907bd..05c35b808 100644
--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
@@ -1,7 +1,9 @@
package org.openremote.test.console
-import com.fasterxml.jackson.databind.node.ObjectNode
+
import com.google.firebase.messaging.Message
+import jakarta.ws.rs.WebApplicationException
+import net.sf.saxon.s9api.push.Push
import org.openremote.container.timer.TimerService
import org.openremote.container.util.UniqueIdentifierGenerator
import org.openremote.manager.asset.AssetStorageService
@@ -12,8 +14,6 @@ import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
import org.openremote.manager.setup.SetupService
-import org.openremote.setup.integration.KeycloakTestSetup
-import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.impl.ConsoleAsset
@@ -28,34 +28,36 @@ import org.openremote.model.notification.NotificationSendResult
import org.openremote.model.notification.PushNotificationMessage
import org.openremote.model.query.filter.RadialGeofencePredicate
import org.openremote.model.rules.AssetRuleset
+import org.openremote.model.rules.RealmRuleset
import org.openremote.model.rules.RulesResource
import org.openremote.model.rules.Ruleset
-import org.openremote.model.rules.RealmRuleset
import org.openremote.model.value.MetaItemType
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.setup.integration.ManagerTestSetup
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.WebApplicationException
+import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.TimeUnit
import java.util.stream.IntStream
-import static org.openremote.setup.integration.ManagerTestSetup.DEMO_RULE_STATES_SMART_BUILDING
-import static org.openremote.setup.integration.ManagerTestSetup.SMART_BUILDING_LOCATION
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
import static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD
import static org.openremote.model.asset.AssetResource.Util.getWriteAttributeUrl
import static org.openremote.model.rules.RulesetStatus.DEPLOYED
import static org.openremote.model.util.TextUtil.isNullOrEmpty
import static org.openremote.model.util.ValueUtil.parse
+import static org.openremote.setup.integration.ManagerTestSetup.DEMO_RULE_STATES_SMART_BUILDING
+import static org.openremote.setup.integration.ManagerTestSetup.SMART_BUILDING_LOCATION
class ConsoleTest extends Specification implements ManagerContainerTrait {
def "Check full console behaviour"() {
- def notificationIds = []
- def targetTypes = []
- def targetIds = []
- def messages = []
+ def notificationIds = new CopyOnWriteArrayList()
+ def targetTypes = new CopyOnWriteArrayList()
+ def targetIds = new CopyOnWriteArrayList()
+ def messages = new CopyOnWriteArrayList()
given: "the container environment is started"
def conditions = new PollingConditions(timeout: 20, delay: 0.2)
@@ -82,7 +84,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
notificationIds << id
targetTypes << target.type
targetIds << target.id
- messages << message
+ messages << "${message.title}_${message.data.get("action")}"
callRealMethod()
}
// Assume sent to FCM
@@ -152,7 +154,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
true,
true,
false,
- (ObjectNode)parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ (Map)parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
))
}
},
@@ -180,7 +182,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert consolePushProvider.requiresPermission
assert consolePushProvider.hasPermission
assert !consolePushProvider.disabled
- assert consolePushProvider.data.get("token").asText() == "23123213ad2313b0897efd"
+ assert consolePushProvider.data.get("token") == "23123213ad2313b0897efd"
and: "the console should have been linked to the authenticated user"
def userAssets = assetStorageService.findUserAssetLinks(keycloakTestSetup.realmBuilding.name, keycloakTestSetup.testuser3Id, consoleId)
@@ -219,7 +221,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert consolePushProvider.requiresPermission
assert consolePushProvider.hasPermission
assert !consolePushProvider.disabled
- assert consolePushProvider.data.get("token").asText() == "23123213ad2313b0897efd"
+ assert consolePushProvider.data.get("token") == "23123213ad2313b0897efd"
assert consoleTestProvider != null
assert consoleTestProvider.version == "Test 1.0"
assert !consoleTestProvider.requiresPermission
@@ -248,7 +250,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert consolePushProvider.requiresPermission
assert consolePushProvider.hasPermission
assert !consolePushProvider.disabled
- assert consolePushProvider.data.get("token").asText() == "23123213ad2313b0897efd"
+ assert consolePushProvider.data.get("token") == "23123213ad2313b0897efd"
assert consoleTestProvider != null
assert consoleTestProvider.version == "Test 1.0"
assert !consoleTestProvider.requiresPermission
@@ -289,7 +291,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert consolePushProvider.requiresPermission
assert consolePushProvider.hasPermission
assert !consolePushProvider.disabled
- assert consolePushProvider.data.get("token").asText() == "23123213ad2313b0897efd"
+ assert consolePushProvider.data.get("token") == "23123213ad2313b0897efd"
when: "an invalid console registration is registered"
def invalidRegistration = new ConsoleRegistration(null, null, "1.0", null, null, null, null)
@@ -326,7 +328,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
assert consolePushProvider.requiresPermission
assert consolePushProvider.hasPermission
assert !consolePushProvider.disabled
- assert consolePushProvider.data.get("token").asText() == "23123213ad2313b0897efd"
+ assert consolePushProvider.data.get("token") == "23123213ad2313b0897efd"
and: "the console should not have been linked to any users"
assert userAssets.isEmpty()
@@ -354,7 +356,9 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "each created consoles should have been sent notifications to refresh their geofences"
conditions.eventually {
assert notificationIds.size() == 3
- assert messages.count { ((PushNotificationMessage) it).data.get("action").asText() == "GEOFENCE_REFRESH" } == 3
+ assert messages.any {it == "${testUser3Console1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${testUser3Console2.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${anonymousConsole1.id}_GEOFENCE_REFRESH"}
}
////////////////////////////////////////////////////
@@ -546,8 +550,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences"
conditions.eventually {
assert notificationIds.size() == 2
- assert ((PushNotificationMessage) messages[0]).data.get("action").asText() == "GEOFENCE_REFRESH"
- assert ((PushNotificationMessage) messages[1]).data.get("action").asText() == "GEOFENCE_REFRESH"
+ assert messages.any {it == "${testUser3Console1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${anonymousConsole1.id}_GEOFENCE_REFRESH"}
}
then: "the geofences of testUser3Console1 should contain the welcome home geofence and new radial geofence (but not the rectangular and duplicate predicates)"
@@ -586,11 +590,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "a push notification should have been sent to the two remaining consoles telling them to refresh their geofences (from the realm engine and asset engine)"
conditions.eventually {
- assert messages.stream()
- .filter({ it instanceof PushNotificationMessage })
- .filter({
- ((PushNotificationMessage) it).data.get("action").asText() == "GEOFENCE_REFRESH"
- }).count() == 2
+ assert messages.any {it == "${anonymousConsole1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${testUser3Console1.id}_GEOFENCE_REFRESH"}
}
then: "the geofences of testUser3Console1 should still contain two geofences but the location of the second should have been updated"
@@ -640,11 +641,8 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
and: "the consoles should have been notified to refresh their geofences"
conditions.eventually {
- assert messages.stream()
- .filter({ it instanceof PushNotificationMessage })
- .filter({
- ((PushNotificationMessage) it).data.get("action").asText() == "GEOFENCE_REFRESH"
- }).count() == 2
+ assert messages.any {it == "${testUser3Console1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${anonymousConsole1.id}_GEOFENCE_REFRESH"}
}
when: "previous notification messages are cleared"
@@ -657,7 +655,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
testUser3Console1.id = null
testUser3Console1.name = "Test Console $it"
return assetStorageService.merge(testUser3Console1)
- }).collect({ it })
+ }).collect({ it as ConsoleAsset })
testUser3Console1.id = testUser3Console1Id
then: "the extra consoles should have been added"
@@ -665,10 +663,16 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
and: "a push notifications should have been sent to each new console to refresh their geofence rules"
conditions.eventually {
- assert messages.stream()
- .filter({it instanceof PushNotificationMessage})
- .filter({((PushNotificationMessage)it).data.get("action").asText() == "GEOFENCE_REFRESH"})
- .count() == 10
+ assert messages.any {it == "${extraConsoles.get(0).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(1).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(2).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(3).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(4).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(5).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(6).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(7).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(8).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(9).id}_GEOFENCE_REFRESH"}
}
when: "previous notification messages are cleared"
@@ -681,12 +685,18 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
then: "a push notification should have been sent to all consoles telling them to refresh their geofences"
conditions.eventually {
- assert messages.stream()
- .filter({ it instanceof PushNotificationMessage })
- .filter({
- ((PushNotificationMessage) it).data.get("action").asText() == "GEOFENCE_REFRESH"
- })
- .count() == 12
+ assert messages.any {it == "${testUser3Console1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${anonymousConsole1.id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(0).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(1).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(2).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(3).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(4).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(5).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(6).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(7).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(8).id}_GEOFENCE_REFRESH"}
+ assert messages.any {it == "${extraConsoles.get(9).id}_GEOFENCE_REFRESH"}
}
when: "the RULE_STATE meta is set to false on a console's location attribute"
diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
index 5fb8f98cb..f538c876b 100644
--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
@@ -97,8 +97,8 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
conditions.eventually {
gateway = assetStorageService.find(gateway.getId(), true)
assert gateway.getAttribute("clientId").isPresent()
- assert !isNullOrEmpty(gateway.getAttribute("clientId", String.class).flatMap{it.getValue()}.orElse(""))
- assert !isNullOrEmpty(gateway.getAttribute("clientSecret", String.class).flatMap{it.getValue()}.orElse(""))
+ assert !isNullOrEmpty(gateway.getAttribute("clientId").flatMap{it.getValue()}.orElse(""))
+ assert !isNullOrEmpty(gateway.getAttribute("clientSecret").flatMap{it.getValue()}.orElse(""))
}
and: "a gateway connector should have been created for this gateway"
@@ -367,7 +367,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
then: "the descendant asset in the local manager should contain the new attribute value"
conditions.eventually {
def building1Room1Asset = assetStorageService.find(mapAssetId(gateway.id, assetIds[1], false))
- assert building1Room1Asset.getAttribute("tempSetpoint", Double.class).flatMap {it.getValue()}.orElse(0d) == 20d
+ assert building1Room1Asset.getAttribute("tempSetpoint").flatMap {it.getValue()}.orElse(0d) == 20d
}
when: "an asset is added on the gateway and the local manager is notified"
@@ -431,7 +431,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
assert localBuilding1Room5Asset.getRealm() == managerTestSetup.realmBuildingName
assert localBuilding1Room5Asset.getParentId() == mapAssetId(gateway.id, assetIds[0], false)
assert localBuilding1Room5Asset.getAttributes().size() == 7
- assert localBuilding1Room5Asset.getAttribute("co2Level", Integer.class).flatMap{it.getValue()}.orElse(0i) == 500i
+ assert localBuilding1Room5Asset.getAttribute("co2Level").flatMap{it.getValue()}.orElse(0i) == 500i
}
when: "an asset is deleted on the gateway and the local manager is notified"
@@ -581,7 +581,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
}
when: "the gateway asset client secret attribute is updated"
- def newSecret = UniqueIdentifierGenerator.generateId()
+ def newSecret = UUID.randomUUID().toString()
assetProcessingService.sendAttributeEvent(new AttributeEvent(gateway.getId(), GatewayAsset.CLIENT_SECRET, newSecret))
then: "the service user secret should be updated"
@@ -801,8 +801,8 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
"127.0.0.1",
serverPort,
managerTestSetup.realmBuildingName,
- gateway.getAttribute("clientId", String.class).flatMap{it.getValue()}.orElse(""),
- gateway.getAttribute("clientSecret", String.class).flatMap{it.getValue()}.orElse(""),
+ gateway.getAttribute("clientId").flatMap{it.getValue()}.orElse(""),
+ gateway.getAttribute("clientSecret").flatMap{it.getValue()}.orElse(""),
false,
false
)
@@ -840,7 +840,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
assert mirroredMicrophone != null
assert mirroredMicrophone.getAttributes().get(MicrophoneAsset.SOUND_LEVEL).flatMap{it.getMetaItem(READ_ONLY)}.flatMap{it.getValue()}.orElse(false)
assert mirroredMicrophone.getAttribute("test").isPresent()
- assert mirroredMicrophone.getAttribute("test", Double.class).flatMap{it.getValue()}.orElse(0d) == 100d
+ assert mirroredMicrophone.getAttribute("test").flatMap{it.getValue()}.orElse(0d) == 100d
}
when: "a gateway client asset is added"
diff --git a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
index f0aeccc04..f0cb4a86b 100644
--- a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
@@ -1,12 +1,17 @@
package org.openremote.test.model
import com.fasterxml.jackson.databind.node.ObjectNode
+import jakarta.ws.rs.WebApplicationException
+import org.jboss.resteasy.api.validation.ViolationReport
import org.openremote.agent.protocol.http.HTTPAgentLink
import org.openremote.agent.protocol.simulator.SimulatorAgent
import org.openremote.agent.protocol.velbus.VelbusTCPAgent
+import org.openremote.container.persistence.PersistenceService
+import org.openremote.container.timer.TimerService
import org.openremote.manager.asset.AssetModelService
-import org.openremote.model.asset.Asset
-import org.openremote.model.asset.AssetModelResource
+import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.setup.SetupService
+import org.openremote.model.asset.*
import org.openremote.model.asset.agent.AgentDescriptor
import org.openremote.model.asset.agent.AgentLink
import org.openremote.model.asset.agent.DefaultAgentLink
@@ -14,22 +19,32 @@ import org.openremote.model.asset.impl.GroupAsset
import org.openremote.model.asset.impl.LightAsset
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
+import org.openremote.model.attribute.AttributeMap
import org.openremote.model.attribute.MetaItem
+import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.rules.AssetState
-import org.openremote.model.asset.AssetTypeInfo
-import org.openremote.model.value.MetaItemType
-import org.openremote.model.value.SubStringValueFilter
-import org.openremote.model.value.ValueConstraint
-import org.openremote.model.value.ValueFilter
-import org.openremote.model.value.ValueType
+import org.openremote.model.util.TimeUtil
import org.openremote.model.util.ValueUtil
+import org.openremote.model.value.*
import org.openremote.model.value.impl.ColourRGB
-import org.openremote.test.ManagerContainerTrait
+import org.openremote.setup.integration.ManagerTestSetup
+import org.openremote.setup.integration.model.asset.ModelTestAsset
import org.openremote.setup.integration.protocol.http.HTTPServerTestAgent
+import org.openremote.test.ManagerContainerTrait
import spock.lang.Shared
import spock.lang.Specification
-import static org.openremote.model.Constants.MASTER_REALM
+import java.lang.reflect.Array
+import java.nio.file.Files
+import java.nio.file.Paths
+import java.nio.file.StandardOpenOption
+import java.time.format.DateTimeFormatter
+import java.time.temporal.ChronoUnit
+
+import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD
+import static org.openremote.container.security.IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
+import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.model.Constants.*
import static org.openremote.model.value.ValueType.BIG_NUMBER
// TODO: Define new asset model tests (setValue - equality checking etc.)
@@ -38,30 +53,333 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
@Shared
static AssetModelResource assetModelResource
+ static String CUSTOM_ASSET_TYPE = "CustomAsset"
+ static ValueDescriptor[] dynamicValueDescriptors = [new ValueDescriptor("dynamicValue", null, ValueConstraint.constraints(new ValueConstraint.AllowedValues("value1", "value2")), null, null, null)]
+
def setupSpec() {
- def container = startContainer(defaultConfig(), defaultServices())
- def assetModelService = container.getService(AssetModelService.class)
+ // A dynamic asset type is added
+ def storageDir = Paths.get(PersistenceService.OR_STORAGE_DIR_DEFAULT, AssetModelService.DIRECTORY_NAME)
+ Files.createDirectories(storageDir)
+ MetaItemDescriptor[] dynamicMetaDescriptors = [new MetaItemDescriptor("dynamicMeta", dynamicValueDescriptors[0])]
+ AttributeDescriptor[] dynamicAttributeDescriptors = [
+ new AttributeDescriptor<>("dynamic1", dynamicValueDescriptors[0]),
+ new AttributeDescriptor<>("dynamic2", ValueType.POSITIVE_INTEGER).withOptional(true)
+ ]
+ def dynamicAssetDescriptor = new AssetDescriptor(CUSTOM_ASSET_TYPE, "", "")
+ def assetTypeInfo = new AssetTypeInfo(dynamicAssetDescriptor, dynamicAttributeDescriptors, dynamicMetaDescriptors, dynamicValueDescriptors)
+ def assetTypeInfoStr = AssetModelService.JSON.writeValueAsString(assetTypeInfo)
+ Files.writeString(storageDir.resolve("CustomAsset"), assetTypeInfoStr, StandardOpenOption.CREATE, StandardOpenOption.WRITE)
+ startContainer(defaultConfig(), defaultServices())
+ // Ensure the asset model is re-initialised (just in case container is reused)
+ container.getService(AssetModelService).initDynamicModel()
+ ValueUtil.doInitialise()
assetModelResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM).proxy(AssetModelResource.class)
}
- def "Retrieving all asset model info"() {
+ def "Check AttributeMap equality checking"() {
+ given: "required services"
+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
+
+ when: "we take the AttributeMap of an asset and serialize it then deserialize it"
+ def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id)
+ def attributeMapJson = ValueUtil.asJSON(apartment1.attributes).orElseThrow()
+ def attributes1 = ValueUtil.parse(attributeMapJson, AttributeMap).orElse(null)
+ def attributes2 = ValueUtil.parse(attributeMapJson, AttributeMap).orElse(null)
+
+ then: "attributes should be equal"
+ Objects.equals(attributes1, attributes2)
+ }
+
+ def "Serialise/Deserialise asset and attribute events and test validation"() {
+
+ given: "an authenticated admin user"
+ def accessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
+ ).token
+ stopPseudoClock()
+
+ and: "the asset resource"
+ def assetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetResource.class)
+
+ expect: "the custom asset type to be loaded"
+ ValueUtil.getAssetDescriptor("CustomAsset").isPresent()
+
+ when: "A well known asset is instantiated"
+ def persistenceService = container.getService(PersistenceService.class)
+ def timerService = container.getService(TimerService.class)
+ def modelTestAsset = new ModelTestAsset("Test Asset")
+ modelTestAsset.setRealm("master")
+
+ and: "try to save the asset without meeting constraints on required attributes"
+ assetResource.create(null, modelTestAsset)
+
+ then: "a constraint violation exception should be thrown"
+ WebApplicationException ex = thrown()
+ ex.response.status == 400
+ def report = ex.response.readEntity(ViolationReport)
+ report.propertyViolations.size() == 1
+ report.propertyViolations.get(0).path == "attributes[positiveInt].value"
+ report.propertyViolations.get(0).message == "must not be null"
+ report.classViolations.size() == 1
+ report.classViolations.get(0).path == ""
+ report.classViolations.get(0).message == "Asset is not valid"
+
+ when: "the issue is fixed and the asset is saved again"
+ modelTestAsset.getAttribute(ModelTestAsset.REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR).map(attr -> attr.setValue(1))
+ modelTestAsset = assetResource.create(null, modelTestAsset)
+
+ then: "the save should succeed"
+ modelTestAsset != null
+ modelTestAsset.getAttribute(ModelTestAsset.REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == 1
+
+ when: "other optional attributes are added with valid values"
+ modelTestAsset.addAttributes(
+ new Attribute<>(ModelTestAsset.NEGATIVE_INT_ATTRIBUTE_DESCRIPTOR, -1),
+ new Attribute<>(ModelTestAsset.SIZE_STRING_ATTRIBUTE_DESCRIPTOR, "abcde"),
+ new Attribute<>(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR, [
+ ("key1"): 1d,
+ ("key2"): 2d,
+ ("key3"): 3d
+ ] as ValueType.DoubleMap
+ ),
+ new Attribute<>(ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR, [
+ "arrayValue1",
+ "arrayValue2"
+ ] as String[]),
+ new Attribute<>(ModelTestAsset.ALLOWED_VALUES_ENUM_ATTRIBUTE_DESCRIPTOR, ModelTestAsset.TestValue.ENUM_2).addMeta(
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotNull()))
+ ),
+ new Attribute<>(ModelTestAsset.ALLOWED_VALUES_STRING_ATTRIBUTE_DESCRIPTOR, "Allowed1"),
+ new Attribute<>(ModelTestAsset.ALLOWED_VALUES_NUMBER_ATTRIBUTE_DESCRIPTOR, 1.5d),
+ new Attribute<>(ModelTestAsset.PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR, timerService.getCurrentTimeMillis()-1000L),
+ new Attribute<>(ModelTestAsset.PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR, timerService.getNow().toDate()),
+ new Attribute<>(ModelTestAsset.FUTURE_ISO8601_ATTRIBUTE_DESCRIPTOR, DateTimeFormatter.ISO_INSTANT.format(timerService.getNow().plusMillis(100000))),
+ new Attribute<>(ModelTestAsset.FUTURE_OR_PRESENT_TIMESTAMP_ATTRIBUTE_DESCRIPTOR, timerService.getCurrentTimeMillis()+100000),
+ new Attribute<>(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR, "abcde"),
+ new Attribute<>(ModelTestAsset.NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR, [1] as Integer[]),
+ new Attribute<>(ModelTestAsset.NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR, [
+ ("key1"): true
+ ] as ValueType.BooleanMap),
+ new Attribute<>(ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR, "abcde"),
+ new Attribute<>(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR, new ModelTestAsset.TestObject(110, true)),
+ // Custom attributes
+ new Attribute<>("custom1"),
+ new Attribute<>("custom2", ValueType.GEO_JSON_POINT, new GeoJSONPoint(1.234, 5.678)).addMeta(
+ new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.NotNull()))
+ )
+ )
+ def updatedModelTestAsset = assetResource.update(null, modelTestAsset.id, modelTestAsset)
+
+ then: "the save should succeed and correct values should be stored"
+ modelTestAsset != null
+ modelTestAsset.getAttribute(ModelTestAsset.REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == 1
+ modelTestAsset.getAttribute(ModelTestAsset.NEGATIVE_INT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == -1
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == "abcde"
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).size() == 3
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).get("key1") == 1d
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).get("key2") == 2d
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).get("key3") == 3d
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).size() == 2
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null)[0] == "arrayValue1"
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null)[1] == "arrayValue2"
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_ENUM_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == ModelTestAsset.TestValue.ENUM_2
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == "Allowed1"
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_NUMBER_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == 1.5d
+ modelTestAsset.getAttribute(ModelTestAsset.PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) < timerService.getCurrentTimeMillis()
+ modelTestAsset.getAttribute(ModelTestAsset.PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).getTime() <= timerService.getCurrentTimeMillis()
+ modelTestAsset.getAttribute(ModelTestAsset.FUTURE_ISO8601_ATTRIBUTE_DESCRIPTOR).map { TimeUtil.parseTimeIso8601(it.value.orElse(null)).toEpochMilli()}.orElse(null) > timerService.getCurrentTimeMillis()
+ modelTestAsset.getAttribute(ModelTestAsset.FUTURE_OR_PRESENT_TIMESTAMP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) >= timerService.getCurrentTimeMillis()
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == "abcde"
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).size() == 1
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).get("key1") == true
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null).length == 1
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null)[0] == 1
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == "abcde"
+ modelTestAsset.getAttribute("custom1").flatMap {it.value}.orElse(null) == null
+ modelTestAsset.getAttribute("custom2").flatMap {it.value}.orElse(null).x == 1.234d
+ modelTestAsset.getAttribute("custom2").flatMap {it.value}.orElse(null).y == 5.678d
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value} != null
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) != null
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.get().range == 110
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.get().active != null
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.get().active.booleanValue()
+
+ when: "The attribute values violate the constraints"
+ modelTestAsset.getAttribute(ModelTestAsset.REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = -1}
+ modelTestAsset.getAttribute(ModelTestAsset.NEGATIVE_INT_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = 1}
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_STRING_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = "abc"}
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = [
+ ("key1"): 1d
+ ] as ValueType.DoubleMap}
+ modelTestAsset.getAttribute(ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = [
+ "arrayValue1"
+ ] as String[]}
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_ENUM_ATTRIBUTE_DESCRIPTOR).ifPresent {
+ it.value = null
+ }
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_STRING_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = "NotAllowed"}
+ modelTestAsset.getAttribute(ModelTestAsset.ALLOWED_VALUES_NUMBER_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = 3.0d}
+ modelTestAsset.getAttribute(ModelTestAsset.PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = timerService.getCurrentTimeMillis() + 100000}
+ modelTestAsset.getAttribute(ModelTestAsset.PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = timerService.getNow().plusMillis(100000).toDate()}
+ modelTestAsset.getAttribute(ModelTestAsset.FUTURE_ISO8601_ATTRIBUTE_DESCRIPTOR).ifPresent { it.value = DateTimeFormatter.ISO_INSTANT.format(timerService.getNow().minus(1, ChronoUnit.DAYS))}
+ modelTestAsset.getAttribute(ModelTestAsset.FUTURE_OR_PRESENT_TIMESTAMP_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = timerService.getNow().minus(1, ChronoUnit.DAYS).toEpochMilli()}
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = ""}
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = [] as ValueType.BooleanMap}
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = [] as Integer[]}
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = " "}
+ modelTestAsset.getAttribute(ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR).ifPresent {it.value = new ModelTestAsset.TestObject(90, null)}
+ modelTestAsset.getAttribute("custom1").ifPresent {it.value = 123}
+ modelTestAsset.getAttribute("custom2").ifPresent {it.value = null}
+ modelTestAsset = assetResource.update(null, modelTestAsset.id, modelTestAsset)
+
+ then: "a constraint violation exception should be thrown"
+ ex = thrown()
+ ex.response.status == 400
+
+ when: "the report is extracted"
+ report = ex.response.readEntity(ViolationReport)
+
+ then: "it should contain all the errors"
+ report.propertyViolations.size() == 19
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.REQUIRED_POSITIVE_INT_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be greater than or equal to 0"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.NEGATIVE_INT_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be less than or equal to 0"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.SIZE_STRING_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "size must be between 5 and 10"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.SIZE_MAP_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "size must be between 2 and 3"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.SIZE_ARRAY_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "size must be between 2 and 3"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.ALLOWED_VALUES_ENUM_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must not be null"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.ALLOWED_VALUES_STRING_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be one of [Allowed1, Allowed2]"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.ALLOWED_VALUES_NUMBER_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be one of [1.5, 2.5]"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be a past date"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be a date in the past or in the present"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.FUTURE_ISO8601_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be a future date"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.FUTURE_OR_PRESENT_TIMESTAMP_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must be a date in the present or in the future"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must not be empty"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.NOT_EMPTY_MAP_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must not be empty"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.NOT_EMPTY_ARRAY_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "must not be empty"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR.name}].value" && it.message == "Not blank custom message"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR.name}].value.range" && it.message == "must be greater than or equal to 100"}
+ report.propertyViolations.any {it.path == "attributes[${ModelTestAsset.OBJECT_ATTRIBUTE_DESCRIPTOR.name}].value.active" && it.message == "must not be null"}
+ report.classViolations.size() == 1
+ report.classViolations.get(0).path == ""
+ report.classViolations.get(0).message == "Asset is not valid"
+
+ when: "we convert the asset to JSON object so we can manipulate it"
+ modelTestAsset = updatedModelTestAsset // Reset attributes to valid values
+ def assetObjectNode = ValueUtil.convert(modelTestAsset, ObjectNode) as ObjectNode
+
+ and: "we simulate an attribute descriptor being removed or changed (by changing the attribute name)"
+ def noDescriptorAttr = ((ObjectNode)assetObjectNode.get("attributes")).remove(ModelTestAsset.PAST_TIMESTAMP_ATTRIBUTE_DESCRIPTOR.name) as ObjectNode
+ noDescriptorAttr.put("name", "missingAttr")
+ ((ObjectNode)assetObjectNode.get("attributes")).set("missingAttr", noDescriptorAttr)
+
+ and: "we simulate a meta item descriptor being removed or changed (by changing the meta item name)"
+ def noDescriptorMeta = ((ObjectNode)((ObjectNode)((ObjectNode)assetObjectNode.get("attributes")).get(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR.name)).get("meta")).remove(MetaItemType.CONSTRAINTS.name)
+ ((ObjectNode)((ObjectNode)((ObjectNode)assetObjectNode.get("attributes")).get(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR.name)).get("meta")).set("missingMeta", noDescriptorMeta)
+
+ and: "we simulate a value descriptor being removed or changed (by changing the type name of an attribute)"
+ ((ObjectNode)((ObjectNode)assetObjectNode.get("attributes")).get(ModelTestAsset.PAST_OR_PRESENT_DATE_ATTRIBUTE_DESCRIPTOR.name)).put("type", "missingType")
+
+ and: "we deserialise the object back into an Asset"
+ modelTestAsset = ValueUtil.parse(assetObjectNode.toString(), Asset).orElse(null) as ModelTestAsset
- when: "an asset info is serialised"
- def thingAssetInfo = ValueUtil.getAssetInfo(ThingAsset.class).orElse(null)
- def thingAssetInfoStr = ValueUtil.asJSON(thingAssetInfo)
+ then: "the attribute with the missing attribute descriptor should still have the correct value type and value should have deserialised correctly"
+ modelTestAsset.getAttribute("missingAttr").map {it.type}.orElse(null) == ValueType.TIMESTAMP
+ modelTestAsset.getAttribute("missingAttr").flatMap {it.value}.orElse(null) instanceof Long
- then: "it should contain the right information"
- thingAssetInfoStr.isPresent()
+ and: "the meta item with the missing meta item descriptor should now have no value type and the value should be an array of generic maps representing the value constraints"
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.getMeta().get("missingMeta")}.orElse(null) != null
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.getMeta().get("missingMeta")}.orElse(null).type == null
+ modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.getMeta().get("missingMeta")}.flatMap {it.value}.orElse(null).getClass().isArray()
+ Array.getLength(modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.getMeta().get("missingMeta")}.flatMap {it.value}.orElse(null)) == 1
+ Array.get(modelTestAsset.getAttribute(ModelTestAsset.NOT_EMPTY_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.getMeta().get("missingMeta")}.flatMap {it.value}.orElse(null), 0) instanceof Map
- when: "the JSON representation is deserialised"
- def thingAssetInfo2 = ValueUtil.parse(thingAssetInfoStr.get(), AssetTypeInfo.class)
+ when: "the attribute with the missing attribute descriptor now violates its' previous constraint"
+ modelTestAsset.getAttribute("missingAttr").ifPresent {it.value = timerService.getCurrentTimeMillis() + 100000}
- then: "it should have been successfully deserialised"
- thingAssetInfo2.isPresent()
- thingAssetInfo2.get().getAssetDescriptor().type == ThingAsset.class
- thingAssetInfo2.get().attributeDescriptors.find { (it == Asset.LOCATION) } != null
- !thingAssetInfo2.get().attributeDescriptors.find { (it == Asset.LOCATION) }.optional
- thingAssetInfo2.get().attributeDescriptors.find { (it == Asset.LOCATION) }.type == ValueType.GEO_JSON_POINT
+ and: "this asset is now merged"
+ modelTestAsset = assetResource.update(null, modelTestAsset.id, modelTestAsset)
+
+ then: "it should succeed and attribute value should be correct"
+ modelTestAsset != null
+ modelTestAsset.getAttribute("missingAttr").flatMap {it.value}.orElse(null) == timerService.getCurrentTimeMillis() + 100000
+
+ when: "we simulate a missing asset type"
+ def updateResult = persistenceService.doReturningTransaction {em ->
+ def query = em.createNativeQuery("update asset set type = 'MissingAssetType' where id = '" + modelTestAsset.id + "';")
+ return query.executeUpdate()
+ }
+
+ then: "it should have succeeded"
+ updateResult == 1
+
+ when: "the model test asset is now fetched"
+ def missingAssetTypeAsset = assetResource.get(null, modelTestAsset.id)
+
+ then: "the missing type string should still be present"
+ missingAssetTypeAsset != null
+ missingAssetTypeAsset.type == "MissingAssetType"
+
+ when: "an attribute value violates one of the original asset type attribute descriptor constraints"
+ missingAssetTypeAsset.getAttribute(ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR).ifPresent { it.value = " "}
+ missingAssetTypeAsset = assetResource.update(null, missingAssetTypeAsset.id, missingAssetTypeAsset)
+
+ then: "the update should succeed because the descriptor is no longer associated with the asset"
+ missingAssetTypeAsset.getAttribute(ModelTestAsset.NOT_BLANK_STRING_ATTRIBUTE_DESCRIPTOR).flatMap {it.value}.orElse(null) == " "
+
+ when: "a custom asset type is persisted (using dynamic CustomAsset)"
+ def customAsset = new ThingAsset("Custom asset").setRealm(MASTER_REALM)
+ .addAttributes(
+ new Attribute<>("attr1", ValueType.TIMESTAMP, getClockTimeOf(container)),
+ new Attribute<>("attr2", ValueType.POSITIVE_INTEGER, 3)
+ )
+ customAsset.type = CUSTOM_ASSET_TYPE
+ customAsset = assetResource.create(null, customAsset)
+
+ then: "a constraint violation exception should be thrown"
+ ex = thrown()
+ ex.response.status == 400
+
+ when: "the report is extracted"
+ report = ex.response.readEntity(ViolationReport)
+
+ then: "the missing required attribute should be included"
+ report.propertyViolations.size() == 1
+ report.propertyViolations.get(0).path == "attributes.dynamic1"
+ report.propertyViolations.get(0).message == "required attribute is missing"
+ report.classViolations.size() == 1
+ report.classViolations.get(0).path == ""
+ report.classViolations.get(0).message == "Asset is not valid"
+
+ when: "the issue is resolved"
+ customAsset.addAttributes(
+ new Attribute<>("dynamic1", dynamicValueDescriptors[0] , "value1")
+ )
+ customAsset = assetResource.create(null, customAsset)
+
+ then: "it should have been persisted"
+ customAsset != null
+ customAsset.type == "CustomAsset"
+ customAsset.getAttribute("attr1").get().type == ValueType.TIMESTAMP
+ customAsset.getAttribute("attr2").get().type == ValueType.POSITIVE_INTEGER
+ customAsset.getAttribute("attr2").get().value.orElse(0) == 3
+
+ when: "we fetch the custom asset again directly from the DB"
+ customAsset = assetResource.get(null, customAsset.id)
+
+ then: "it should still have the correct custom type"
+ customAsset != null
+ customAsset.type == "CustomAsset"
+ customAsset.getAttribute("attr1").get().type == ValueType.TIMESTAMP
+ customAsset.getAttribute("attr2").get().type == ValueType.POSITIVE_INTEGER
+ customAsset.getAttribute("attr2").get().value.orElse(0) == 3
+ }
+
+ def "Retrieving all asset model info"() {
when: "the asset type value descriptor is retrieved"
def assetValueType = ValueUtil.getValueDescriptor(ValueType.ASSET_TYPE.getName())
@@ -73,16 +391,49 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
(assetValueType.get().constraints.find {it instanceof ValueConstraint.AllowedValues} as ValueConstraint.AllowedValues).allowedValues.length == ValueUtil.getAssetInfos().length
(assetValueType.get().constraints.find {it instanceof ValueConstraint.AllowedValues} as ValueConstraint.AllowedValues).allowedValues.any { (it == GroupAsset.class.getSimpleName()) }
- when: "All asset model infos are retrieved"
- def assetInfos = assetModelResource.getAssetInfos(null, null, null);
+ when: "all asset model infos are retrieved"
+ def assetInfos = assetModelResource.getAssetInfos(null, null, null)
then: "the asset model infos should be available"
assetInfos.size() > 0
- assetInfos.size() == ValueUtil.assetTypeMap.size()
+ assetInfos.size() == ValueUtil.assetInfoMap.size()
def velbusTcpAgent = assetInfos.find {it.assetDescriptor.type == VelbusTCPAgent.class}
velbusTcpAgent != null
- velbusTcpAgent.attributeDescriptors.any {it == VelbusTCPAgent.VELBUS_HOST && !it.optional}
- velbusTcpAgent.attributeDescriptors.any {it == VelbusTCPAgent.VELBUS_PORT && !it.optional}
+ !velbusTcpAgent.attributeDescriptors.get(VelbusTCPAgent.HOST.name).optional
+ !velbusTcpAgent.attributeDescriptors.get(VelbusTCPAgent.PORT.name).optional
+
+ when: "all value descriptors are retrieved"
+ def valueDescriptors = assetModelResource.getValueDescriptors(null, null)
+
+ then: "the value descriptors should be correctly serialised/deserialised"
+ valueDescriptors.size() > 0
+ valueDescriptors.every {it.value.name == it.key && it.value.type != null & it.value.jsonType != null}
+ valueDescriptors.get(ValueType.ASSET_QUERY.name) == ValueType.ASSET_QUERY
+ valueDescriptors.get(ValueType.ASSET_QUERY.name).jsonType == ValueType.ASSET_QUERY.jsonType
+
+ when: "represented as JSON"
+ def valueDescriptorsJSON = ValueUtil.parse(ValueUtil.asJSON(valueDescriptors).orElse(null), Object).get()
+
+ then: "should be a map of objects"
+ valueDescriptorsJSON instanceof Map
+ ((Map)valueDescriptorsJSON).size() == valueDescriptors.size()
+ ((Map)valueDescriptorsJSON).get(ValueType.TIMESTAMP.name) instanceof Map
+
+ when: "all meta item descriptors are retrieved"
+ def metaItemDescriptors = assetModelResource.getMetaItemDescriptors(null, null)
+
+ then: "the meta item descriptors should be correctly serialised/deserialised"
+ metaItemDescriptors.size() > 0
+
+ when: "represented as JSON"
+ def metaItemDescriptorsJSON = ValueUtil.parse(ValueUtil.asJSON(metaItemDescriptors).orElse(null), Object).get()
+
+ then: "should be an array of string values"
+ metaItemDescriptorsJSON instanceof Map
+ ((Map)metaItemDescriptorsJSON).size() == metaItemDescriptors.size()
+ ((Map)metaItemDescriptorsJSON).get(MetaItemType.ATTRIBUTE_LINKS.name) instanceof Map
+ ((Map)((Map)metaItemDescriptorsJSON).get(MetaItemType.ATTRIBUTE_LINKS.name)).get("name") == MetaItemType.ATTRIBUTE_LINKS.name
+ ((Map)((Map)metaItemDescriptorsJSON).get(MetaItemType.ATTRIBUTE_LINKS.name)).get("type") == "${ValueType.ATTRIBUTE_LINK.name}[]"
}
def "Retrieving a specific asset model info"() {
@@ -95,7 +446,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
thingAssetInfo.attributeDescriptors != null
thingAssetInfo.metaItemDescriptors != null
thingAssetInfo.valueDescriptors != null
- thingAssetInfo.attributeDescriptors.contains(Asset.LOCATION)
+ thingAssetInfo.attributeDescriptors.get(Asset.LOCATION.name) == Asset.LOCATION
thingAssetInfo.metaItemDescriptors.contains(MetaItemType.AGENT_LINK)
ValueUtil.getAssetDescriptor(ThingAsset.class) != null
ValueUtil.getAgentDescriptor(SimulatorAgent.class) != null
@@ -174,9 +525,9 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
asset2.getColourRGB().map{it.getR()}.orElse(null) == asset.getColourRGB().map{it.getR()}.orElse(null)
asset2.getColourRGB().map{it.getG()}.orElse(null) == asset.getColourRGB().map{it.getG()}.orElse(null)
asset2.getColourRGB().map{it.getB()}.orElse(null) == asset.getColourRGB().map{it.getB()}.orElse(null)
- asset2.getAttribute("testAttribute", BIG_NUMBER.type).flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.orElse(null) instanceof HTTPAgentLink
- asset2.getAttribute("testAttribute", BIG_NUMBER.type).flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgentLink)it}.flatMap{it.path}.orElse("") == "test_path"
- asset2.getAttribute("testAttribute", BIG_NUMBER.type).flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgentLink)it}.flatMap{it.pagingMode}.orElse(false)
+ asset2.getAttribute("testAttribute").flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.orElse(null) instanceof HTTPAgentLink
+ asset2.getAttribute("testAttribute").flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgentLink)it}.flatMap{it.path}.orElse("") == "test_path"
+ asset2.getAttribute("testAttribute").flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgentLink)it}.flatMap{it.pagingMode}.orElse(false)
when: "an attribute is cloned"
def attribute = asset2.getAttribute(LightAsset.COLOUR_RGB).get()
diff --git a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
index 3031bb40c..745419001 100644
--- a/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy
@@ -488,7 +488,7 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
newClientId = "newClient"
def username2 = keycloakTestSetup.realmBuilding.name + ":" + keycloakTestSetup.serviceUser2.username // realm and OAuth client id
def password2 = keycloakTestSetup.serviceUser2.secret
- newClient = new MQTT_IOClient(newClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username2, password2), null, new MQTTLastWill("${keycloakTestSetup.realmBuilding.name}/$newClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/motionSensor/$managerTestSetup.apartment1HallwayId".toString(), ValueUtil.parse("1000").orElse(null), false))
+ newClient = new MQTT_IOClient(newClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username2, password2), null, new MQTTLastWill("${keycloakTestSetup.realmBuilding.name}/$newClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/motionSensor/$managerTestSetup.apartment1HallwayId".toString(), "1000", false))
newClient.connect()
then: "the client should be connected"
@@ -566,7 +566,7 @@ class MqttBrokerTest extends Specification implements ManagerContainerTrait {
when: "the new client reconnects using a last will topic for an unauthorised asset/attribute"
def asset = assetStorageService.find(managerTestSetup.apartment2LivingroomId)
def currentCO2Level = asset.getAttribute("co2Level").flatMap{it.getValue()}.orElse(0d)
- newClient = new MQTT_IOClient(newClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username2, password2), null, new MQTTLastWill("${keycloakTestSetup.realmBuilding.name}/$mqttClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/co2Level/$managerTestSetup.apartment2LivingroomId".toString(), ValueUtil.parse("1000").orElse(null), false))
+ newClient = new MQTT_IOClient(newClientId, mqttHost, mqttPort, false, true, new UsernamePassword(username2, password2), null, new MQTTLastWill("${keycloakTestSetup.realmBuilding.name}/$mqttClientId/$DefaultMQTTHandler.ATTRIBUTE_VALUE_WRITE_TOPIC/co2Level/$managerTestSetup.apartment2LivingroomId".toString(), "1000", false))
newClient.connect()
then: "the client should be connected"
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index efa9e3ccb..151dde221 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -1,7 +1,6 @@
package org.openremote.test.notification
-import com.fasterxml.jackson.databind.JsonNode
-import com.fasterxml.jackson.databind.node.ObjectNode
+
import com.fasterxml.jackson.databind.node.TextNode
import jakarta.mail.Message
import jakarta.mail.internet.InternetAddress
@@ -158,7 +157,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
true,
true,
false,
- (ObjectNode) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ (Map) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
))
}
},
@@ -333,7 +332,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
notificationIds.clear()
notificationTargetIds.clear()
def testUser3Console1Asset = assetStorageService.find(testuser3Console1.id) as ConsoleAsset
- testUser3Console1Asset.getConsoleProviders().map{it.get(PushNotificationMessage.TYPE)}.get().getData().set("token", null)
+ testUser3Console1Asset.getConsoleProviders().map{it.get(PushNotificationMessage.TYPE)}.get().getData().put("token", null)
testUser3Console1Asset = assetStorageService.merge(testUser3Console1Asset)
then: "the cached FCM token should be removed from the handler"
diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
index f57ca1d83..31e723776 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -235,13 +235,13 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
conditions.eventually {
def mockAsset = assetStorageService.find(mockThing.id, true)
// Check all valid linked attributes have the new values
- assert mockAsset.getAttributes().<Boolean>getValue("lightToggle1").orElse(false)
- assert mockAsset.getAttribute("tempTarget1", Double.class).flatMap{it.getValue()}.orElse(0d) == 25.5d
+ assert mockAsset.getAttribute("lightToggle1").flatMap{it.getValue()}.orElse(false)
+ assert mockAsset.getAttribute("tempTarget1").flatMap{it.getValue()}.orElse(0d) == 25.5d
// Check invalid attributes don't have the new values
- assert !mockAsset.getAttribute("lightToggle2", Boolean.class).get().getValue().isPresent()
- assert !mockAsset.getAttribute("tempTarget2", Double.class).get().getValue().isPresent()
- assert !mockAsset.getAttribute("lightToggle3", Boolean.class).get().getValue().isPresent()
- assert !mockAsset.getAttribute("tempTarget3", Double.class).get().getValue().isPresent()
+ assert !mockAsset.getAttribute("lightToggle2").get().getValue().isPresent()
+ assert !mockAsset.getAttribute("tempTarget2").get().getValue().isPresent()
+ assert !mockAsset.getAttribute("lightToggle3").get().getValue().isPresent()
+ assert !mockAsset.getAttribute("tempTarget3").get().getValue().isPresent()
}
when: "the disabled agent is enabled"
@@ -314,7 +314,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
then: "the target temp attributes value should be updated"
conditions.eventually {
mockThing = assetStorageService.find(mockThing.id, true) as ThingAsset
- assert mockThing.getAttribute("tempTarget1").get().getValueAs(Double.class).orElse(0d) == 30d
+ assert mockThing.getAttribute("tempTarget1").get().getValue(Double.class).orElse(0d) == 30d
}
when: "a sensor value is received that links to an attribute using a regex filter"
@@ -324,7 +324,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
then: "the linked attributes value should be updated with the filtered result"
conditions.eventually {
mockThing = assetStorageService.find(mockThing.id, true) as ThingAsset
- assert mockThing.getAttribute("filterRegex").get().getValueAs(Double.class).orElse(0d) == 1212d
+ assert mockThing.getAttribute("filterRegex").get().getValue(Double.class).orElse(0d) == 1212d
}
when: "the same attribute receives a sensor value that doesn't match the regex filter (match index invalid)"
diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
index 53911a8dc..514881431 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy
@@ -19,7 +19,11 @@
*/
package org.openremote.test.protocol.http
-import com.fasterxml.jackson.databind.node.ObjectNode
+
+import jakarta.ws.rs.HttpMethod
+import jakarta.ws.rs.client.ClientRequestContext
+import jakarta.ws.rs.client.ClientRequestFilter
+import jakarta.ws.rs.core.*
import org.jboss.resteasy.specimpl.ResteasyUriInfo
import org.jboss.resteasy.util.BasicAuthHelper
import org.openremote.agent.protocol.http.HTTPAgent
@@ -48,10 +52,6 @@ import spock.lang.Shared
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import jakarta.ws.rs.HttpMethod
-import jakarta.ws.rs.client.ClientRequestContext
-import jakarta.ws.rs.client.ClientRequestFilter
-import jakarta.ws.rs.core.*
import java.util.regex.Pattern
import static org.openremote.model.value.MetaItemType.AGENT_LINK
@@ -167,11 +167,11 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
&& requestContext.getHeaderString("Content-type") == MediaType.APPLICATION_JSON) {
String bodyStr = (String)requestContext.getEntity()
- ObjectNode body = ValueUtil.parse(bodyStr).orElse(null)
- if (body.has("prop1")
- && body.get("prop1").get("myProp1").asInt() == 123
- && body.get("prop1").get("myProp2").asBoolean()
- && body.has("prop2") && body.get("prop2").asText() == "prop2Value") {
+ Map body = (Map)ValueUtil.parse(bodyStr).orElse(null)
+ if (body.containsKey("prop1")
+ && ((Map)body.get("prop1")).get("myProp1") == 123
+ && ((Map)body.get("prop1")).get("myProp2")
+ && body.containsKey("prop2") && body.get("prop2") == "prop2Value") {
putRequestWithHeadersCalled = true
requestContext.abortWith(Response.ok().build())
return
@@ -294,7 +294,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.setParent(agent)
.addOrReplaceAttributes(
// attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
- new Attribute<>("putRequestWithHeaders", JSON_OBJECT)
+ new Attribute<>("putRequestWithHeaders")
.addMeta(
new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath("put_request_with_headers")
@@ -319,7 +319,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.addMeta(
new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath('value/{$value}/set')
- .setWriteValueConverter((ObjectNode)ValueUtil.parse("{\n" +
+ .setWriteValueConverter((Map)ValueUtil.parse("{\n" +
" \"TRUE\": \"on\",\n" +
" \"FALSE\": \"off\"\n" +
"}").get())
@@ -363,9 +363,9 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
new SubStringValueFilter(22, 24)
] as ValueFilter[]
)
- .setValueConverter(ValueUtil.JSON.createObjectNode()
- .put("00", "OFF")
- .put("01", "ON")
+ .setValueConverter(Map.of(
+ "00", "OFF",
+ "01", "ON")
)
)
),
@@ -381,9 +381,9 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
new SubStringValueFilter(4, 6)
] as ValueFilter[]
)
- .setValueConverter(ValueUtil.JSON.createObjectNode()
- .put("00", "OFF")
- .put("01", "ON")
+ .setValueConverter(Map.of(
+ "00", "OFF",
+ "01", "ON")
)
)
)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy
index 97005535e..973996879 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/mqtt/MQTTClientProtocolTest.groovy
@@ -120,7 +120,7 @@ class MQTTClientProtocolTest extends Specification implements ManagerContainerTr
conditions.eventually {
def livingRoom = assetStorageService.find(managerTestSetup.apartment1LivingroomId)
assert livingRoom != null
- assert livingRoom.getAttribute("targetTemperature", Double.class).flatMap{it.value}.orElse(0d) == 99d
+ assert livingRoom.getAttribute("targetTemperature").flatMap{it.value}.orElse(0d) == 99d
}
then: "the agent linked attribute should also have the updated value of the subscribed attribute"
@@ -138,7 +138,7 @@ class MQTTClientProtocolTest extends Specification implements ManagerContainerTr
then: "the linked targetTemperature attribute should contain this written value (it should have been written to the target temp attribute and then read back again)"
conditions.eventually {
asset = assetStorageService.find(asset.getId(), true)
- assert asset.getAttribute("readWriteTargetTemp", Double.class).flatMap{it.getValue()}.orElse(null) == 19.5d
+ assert asset.getAttribute("readWriteTargetTemp").flatMap{it.getValue()}.orElse(null) == 19.5d
}
}
}
diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
index f2edc7311..1778daa51 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy
@@ -105,9 +105,11 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
break
case "https://mockapi/targetTemperature":
attribute1SubscriptionDone = true
+ requestContext.abortWith(Response.ok().build())
break
case "https://mockapi/co2Level":
attribute2SubscriptionDone = true
+ requestContext.abortWith(Response.ok().build())
break
}
@@ -272,8 +274,8 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
conditions.eventually {
def livingRoom = assetStorageService.find(managerTestSetup.apartment1LivingroomId)
assert livingRoom != null
- assert livingRoom.getAttribute("targetTemperature", Double.class).flatMap{it.value}.orElse(0d) == 99d
- assert livingRoom.getAttribute("co2Level", Integer.class).flatMap{it.value}.orElse(0i) == 50i
+ assert livingRoom.getAttribute("targetTemperature").flatMap{it.value}.orElse(0d) == 99d
+ assert livingRoom.getAttribute("co2Level").flatMap{it.value}.orElse(0i) == 50i
}
then: "the linked attributes should also have the updated values of the subscribed attributes"
@@ -292,7 +294,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
then: "the linked targetTemperature attribute should contain this written value (it should have been written to the target temp attribute and then read back again)"
conditions.eventually {
asset = assetStorageService.find(asset.getId(), true)
- assert asset.getAttribute("readWriteTargetTemp", Double.class).flatMap{it.getValue()}.orElse(null) == 19.5d
+ assert asset.getAttribute("readWriteTargetTemp").flatMap{it.getValue()}.orElse(null) == 19.5d
}
when: "the co2level changes"
diff --git a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
index b3415ca82..3f1e0b3ee 100644
--- a/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/provisioning/UserAndAssetProvisioningTest.groovy
@@ -360,7 +360,7 @@ class UserAndAssetProvisioningTest extends Specification implements ManagerConta
and: "the connected attribute of the provisioned asset should show as not connected"
conditions.eventually {
- weatherAsset = ((SuccessResponseMessage)device1Responses.get(0)).asset
+ weatherAsset = assetStorageService.find (weatherAsset.id)
assert !weatherAsset.getAttribute("connected").flatMap{it.value}.orElse(true)
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
index 6aeddd465..87303309b 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
@@ -170,41 +170,12 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
when: "time advances"
advancePseudoClock(1, TimeUnit.SECONDS, container)
- then: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"
+ and: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"
def globalLastFireTimestamp = rulesImport.globalEngine.lastFireTimestamp
def masterLastFireTimestamp = rulesImport.masterEngine.lastFireTimestamp
def realmALastFireTimestamp = rulesImport.realmBuildingEngine.lastFireTimestamp
def apartment2LastFireTimestamp = rulesImport.apartment2Engine.lastFireTimestamp
def apartment3LastFireTimestamp = rulesImport.apartment3Engine.lastFireTimestamp
- def apartment2LivingRoomWindowOpenChange = new AttributeEvent(
- managerTestSetup.apartment2LivingroomId, "windowOpen", true
- )
- assetProcessingService.sendAttributeEvent(apartment2LivingRoomWindowOpenChange)
-
- then: "the attribute event should have been processed"
- conditions.eventually {
- def apartment2LivingRoom = assetStorageService.find(managerTestSetup.apartment2LivingroomId, true)
- assert apartment2LivingRoom.getAttribute("windowOpen").flatMap{it.getValueAs(Boolean.class)}.orElse(false)
- }
-
- then: "the rules engines should not have fired"
- conditions.eventually {
- assert rulesImport.globalEngine.lastFireTimestamp == globalLastFireTimestamp
- assert rulesImport.masterEngine.lastFireTimestamp == masterLastFireTimestamp
- assert rulesImport.realmBuildingEngine.lastFireTimestamp == realmALastFireTimestamp
- assert rulesImport.apartment2Engine.lastFireTimestamp == apartment2LastFireTimestamp
- assert rulesImport.apartment3Engine.lastFireTimestamp == apartment3LastFireTimestamp
- }
-
- when: "time advances"
- advancePseudoClock(1, TimeUnit.SECONDS, container)
-
- and: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"
- globalLastFireTimestamp = rulesImport.globalEngine.lastFireTimestamp
- masterLastFireTimestamp = rulesImport.masterEngine.lastFireTimestamp
- realmALastFireTimestamp = rulesImport.realmBuildingEngine.lastFireTimestamp
- apartment2LastFireTimestamp = rulesImport.apartment2Engine.lastFireTimestamp
- apartment3LastFireTimestamp = rulesImport.apartment3Engine.lastFireTimestamp
asset.addOrReplaceAttributes(
new Attribute<>("testString", ValueType.TEXT, "test")
.addOrReplaceMeta(
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
index 0bd84c125..af0cadd20 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
@@ -1,7 +1,6 @@
package org.openremote.test.rules.residence
-import com.fasterxml.jackson.databind.JsonNode
-import com.fasterxml.jackson.databind.node.ObjectNode
+
import com.google.firebase.messaging.Message
import jakarta.mail.internet.InternetAddress
import jakarta.ws.rs.client.ClientRequestContext
@@ -42,7 +41,6 @@ import org.openremote.model.notification.NotificationSendResult
import org.openremote.model.notification.PushNotificationMessage
import org.openremote.model.rules.RealmRuleset
import org.openremote.model.rules.Ruleset
-import org.openremote.model.rules.RulesetStatus
import org.openremote.model.rules.json.JsonRulesetDefinition
import org.openremote.model.util.ValueUtil
import org.openremote.model.value.MetaItemType
@@ -88,10 +86,10 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
break
case "https://basicserver/webhookjson":
if (requestContext.method == "POST" && requestContext.mediaType == MediaType.APPLICATION_JSON_TYPE && requestContext.getHeaderString('test-header') == "test-value" && requestContext.hasEntity()) {
- Optional<JsonNode> jsonBody = parse(requestContext.entity.toString())
- if (jsonBody.isPresent() && jsonBody.get().size() == 1
- && jsonBody.get().iterator().next().get(0).get("assetName").asText() == "TestThing"
- && jsonBody.get().iterator().next().get(0).get("value").asText() == "test_message") {
+ def jsonBody = parse(requestContext.entity.toString()).get() as Map
+ if (jsonBody.size() == 1
+ && ((Map)((Object[])jsonBody.values()[0])[0]).get("assetName") == "TestThing"
+ && ((Map)((Object[])jsonBody.values()[0])[0]).get("value") == "test_message") {
successCount++
requestContext.abortWith(Response.ok().build()); return
}
@@ -185,11 +183,11 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "the room lights in an apartment to be on"
conditions.eventually {
def livingroomAsset = assetStorageService.find(managerTestSetup.apartment2LivingroomId, true)
- assert livingroomAsset.getAttribute("lightSwitch", Boolean.class).get().value.get()
- assert livingroomAsset.getAttribute("lightSwitchTriggerTimes", String[].class).get().value.get().length == 2
- assert livingroomAsset.getAttribute("plantsWaterLevels", ObjectNode.class).get().value.get().get("cactus").asDouble() == 0.8d
+ assert livingroomAsset.getAttribute("lightSwitch").get().value.get()
+ assert livingroomAsset.getAttribute("lightSwitchTriggerTimes").get().value.get().length == 2
+ assert livingroomAsset.getAttribute("plantsWaterLevels").get().getValue(Map.class).get().get("cactus") == 0.8d
def bathRoomAsset = assetStorageService.find(managerTestSetup.apartment2BathroomId, true)
- assert bathRoomAsset.getAttribute("lightSwitch", Boolean.class).get().value.get()
+ assert bathRoomAsset.getAttribute("lightSwitch").get().value.get()
}
when: "a user authenticates"
@@ -234,7 +232,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
true,
true,
false,
- ((ObjectNode) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ (Map<String, Object>)(parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
)))
}
},
@@ -266,7 +264,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
true,
true,
false,
- ((ObjectNode) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ (Map<String, Object>)(parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
)))
}
},
@@ -313,8 +311,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
def assetState = realmBuildingEngine.assetStates.find {it.id == consoleRegistration.id && it.name == Asset.LOCATION.name}
assert assetState != null
assert assetState.getValue().isPresent()
- assert assetState.getValueAs(GeoJSONPoint.class).map{it.x == ManagerTestSetup.SMART_BUILDING_LOCATION.x}.orElse(false)
- assert assetState.getValueAs(GeoJSONPoint.class).map{it.y == ManagerTestSetup.SMART_BUILDING_LOCATION.y}.orElse(false)
+ assert assetState.getValue(GeoJSONPoint.class).map{it.x == ManagerTestSetup.SMART_BUILDING_LOCATION.x}.orElse(false)
+ assert assetState.getValue(GeoJSONPoint.class).map{it.y == ManagerTestSetup.SMART_BUILDING_LOCATION.y}.orElse(false)
}
when: "the console device moves outside the home geofence (as defined in the rule)"
@@ -325,8 +323,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
conditions.eventually {
def livingroomAsset = assetStorageService.find(managerTestSetup.apartment2LivingroomId, true)
assert !livingroomAsset.getAttribute("lightSwitch").get().value.get()
- assert livingroomAsset.getAttribute("lightSwitchTriggerTimes", String[].class).flatMap{it.value}.map{it.length}.orElse(0) == 2
- assert livingroomAsset.getAttribute("plantsWaterLevels", ObjectNode.class).get().getValue().map{it.get("cactus").asDouble()}.orElse(null) == 0.8
+ assert livingroomAsset.getAttribute("lightSwitchTriggerTimes").flatMap{it.value}.map{it.length}.orElse(0) == 2
+ assert livingroomAsset.getAttribute("plantsWaterLevels").get().getValue(Map.class).get().get("cactus") == 0.8
def bathRoomAsset = assetStorageService.find(managerTestSetup.apartment2BathroomId, true)
assert !bathRoomAsset.getAttribute("lightSwitch").get().value.get()
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 64d3ec48f..a55e49503 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -4,7 +4,6 @@ package org.openremote.test.rules.residence
import com.google.firebase.messaging.Message
import net.fortuna.ical4j.model.Date
import net.fortuna.ical4j.model.Recur
-import net.fortuna.ical4j.model.parameter.Value
import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
@@ -31,8 +30,6 @@ import org.openremote.model.notification.NotificationSendResult
import org.openremote.model.notification.PushNotificationMessage
import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.Ruleset
-import org.openremote.model.rules.TemporaryFact
-import com.fasterxml.jackson.databind.node.ObjectNode
import org.openremote.model.util.ValueUtil
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
@@ -41,8 +38,6 @@ import spock.util.concurrent.PollingConditions
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
-import java.time.ZoneOffset
-import java.time.ZonedDateTime
import java.time.temporal.ChronoField
import java.time.temporal.ChronoUnit
import java.util.concurrent.TimeUnit
@@ -161,7 +156,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
true,
true,
false,
- ((ObjectNode) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
+ ((Map) parse("{\"token\": \"23123213ad2313b0897efd\"}").orElse(null)
)))
}
},
@@ -180,7 +175,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
then: "that value should be stored"
conditions.eventually {
def asset = assetStorageService.find(managerTestSetup.apartment1Id, true)
- assert asset.getAttribute("alarmEnabled", Boolean.class).get().getValue().orElse(false)
+ assert asset.getAttribute("alarmEnabled").get().getValue().orElse(false)
}
when: "the presence is detected in Living room of apartment 1"
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
index 70480d537..6c4a5623f 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
@@ -1,7 +1,6 @@
package org.openremote.setup.integration.rules
import org.openremote.manager.rules.RulesBuilder
-import org.openremote.model.asset.impl.BuildingAsset
import org.openremote.model.asset.impl.RoomAsset
import org.openremote.model.query.AssetQuery
import static org.openremote.model.value.ValueType.*
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
index 20153fb5b..636744162 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceSmartSwitch.groovy
@@ -91,7 +91,7 @@ rules.add()
}.filter { modeNowOn ->
// Begin/end time of cycle is greater than zero
smartSwitchAttributeMatch(facts, modeNowOn, SmartSwitchAttribute.BeginEnd)
- .flatMap { it.getValueAs(Long.class) }
+ .flatMap { it.getValue(Long.class) }
.map { it > 0 }
.orElse(false)
}.findFirst().map { modeNowOn ->
diff --git a/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy b/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
index ffe110a20..d337fccf8 100644
--- a/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/ResidenceVacationMode.groovy
@@ -66,7 +66,7 @@ rules.add()
new AssetQuery().types(BuildingAsset)
.attributeValue("vacationUntil", LESS_EQUALS, facts.clock.currentTimeMillis)
).filter { residenceWithVacationUntilInPast ->
- residenceWithVacationUntilInPast.getValueAs(Double.class).isPresent()
+ residenceWithVacationUntilInPast.getValue(Double.class).isPresent()
}.filter { residenceWithVacationUntilInPast ->
facts.match(VacationMode).noneMatch {
vacationMode -> vacationMode.residenceId == residenceWithVacationUntilInPast.id
diff --git a/test/src/test/resources/org/openremote/test/rules/SmartCityCamera.groovy b/test/src/test/resources/org/openremote/test/rules/SmartCityCamera.groovy
index 9a8460f45..bd6693417 100644
--- a/test/src/test/resources/org/openremote/test/rules/SmartCityCamera.groovy
+++ b/test/src/test/resources/org/openremote/test/rules/SmartCityCamera.groovy
@@ -27,10 +27,10 @@ rules.add()
.attributeName("cameraCountIn"))
.map(
{
- new Tuple(it.id, it.getValueAs(Double.class).orElse(0d) - facts.matchFirstAssetState(new AssetQuery()
+ new Tuple(it.id, it.getValue(Double.class).orElse(0d) - facts.matchFirstAssetState(new AssetQuery()
.names(new StringPredicate(AssetQuery.Match.BEGIN, "Camera"))
.attributeName("cameraCountOut"))
- .map({ it.getValueAs(Double.class).orElse(0d)}).orElse(0d))
+ .map({ it.getValue(Double.class).orElse(0d)}).orElse(0d))
})
.filter(
{
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index d7aced87e..8f578f0c6 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -520,8 +520,8 @@ export class Manager implements EventProviderFactory {
const valueDescriptorResponse = await rest.api.AssetModelResource.getValueDescriptors();
AssetModelUtil._assetTypeInfos = assetInfosResponse.data;
- AssetModelUtil._metaItemDescriptors = metaItemDescriptorResponse.data;
- AssetModelUtil._valueDescriptors = valueDescriptorResponse.data;
+ AssetModelUtil._metaItemDescriptors = Object.values(metaItemDescriptorResponse.data);
+ AssetModelUtil._valueDescriptors = Object.values(valueDescriptorResponse.data);
} catch (e) {
console.error(e);
return false;
diff --git a/ui/component/model/build.gradle b/ui/component/model/build.gradle
index cb6864a0f..f98a98922 100644
--- a/ui/component/model/build.gradle
+++ b/ui/component/model/build.gradle
@@ -40,7 +40,6 @@ generateTypeScript {
"org.openremote.model.flow.**",
"java.io.**",
"org.hibernate.**",
- "com.vladmihalcea.**",
"jakarta.**"
]
customTypeProcessor = "CustomTypeProcessor"
@@ -69,7 +68,7 @@ generateTypeScript {
"com.fasterxml.jackson.module.paramnames.ParameterNamesModule"
]
extensions = [
- "AssetModelInfoExtension",
+ "org.openremote.model.util.AssetModelInfoExtension",
"CustomExtension",
"JsonSerializeExtension"
]
diff --git a/ui/component/model/src/main/java/EnumWithInterfacesExtension.java b/ui/component/model/src/main/java/EnumWithInterfacesExtension.java
index de9ca94b2..a69442479 100644
--- a/ui/component/model/src/main/java/EnumWithInterfacesExtension.java
+++ b/ui/component/model/src/main/java/EnumWithInterfacesExtension.java
@@ -11,8 +11,6 @@ import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.module.SimpleModule;
import cz.habarta.typescript.generator.*;
import cz.habarta.typescript.generator.compiler.ModelCompiler;
-import cz.habarta.typescript.generator.compiler.ModelTransformer;
-import cz.habarta.typescript.generator.compiler.SymbolTable;
import cz.habarta.typescript.generator.compiler.TsModelTransformer;
import cz.habarta.typescript.generator.emitter.*;
import cz.habarta.typescript.generator.util.Pair;
@@ -259,12 +257,12 @@ public class EnumWithInterfacesExtension extends Extension {
fieldsStr = TMPL_ENUM_FIELD_SEPARATOR + fieldsStr;
}
- final Map<String, String> replacements = new LinkedHashMap<>();
- replacements.put("\"", settings.quotes);
- replacements.put("/*export*/ ", exportKeyword ? "export " : "");
- replacements.put(TMPL_ENUM_NAME, tsEnum.getName().getSimpleName());
- replacements.put(TMPL_ENUM_IMPLEMENTS, implementsStr);
- replacements.put(TMPL_ENUM_FIELDS, fieldsStr);
+ final Map<String, String> replacements = Map.of(
+ "\"", settings.quotes,
+ "/*export*/ ", exportKeyword ? "export " : "",
+ TMPL_ENUM_NAME, tsEnum.getName().getSimpleName(),
+ TMPL_ENUM_IMPLEMENTS, implementsStr,
+ TMPL_ENUM_FIELDS, fieldsStr);
Emitter.writeTemplate(writer, settings, ENUM_CLASS_HEADER_TEMPLATE, replacements);
enumInterfaceModel.getMemberModels().forEach(enumInterfaceMemberModel -> {
diff --git a/ui/component/model/src/main/java/AssetModelInfoExtension.java b/ui/component/model/src/main/java/org/openremote/model/util/AssetModelInfoExtension.java
similarity index 91%
rename from ui/component/model/src/main/java/AssetModelInfoExtension.java
rename to ui/component/model/src/main/java/org/openremote/model/util/AssetModelInfoExtension.java
index f1bb0c7c0..360728197 100644
--- a/ui/component/model/src/main/java/AssetModelInfoExtension.java
+++ b/ui/component/model/src/main/java/org/openremote/model/util/AssetModelInfoExtension.java
@@ -18,6 +18,8 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+package org.openremote.model.util;
+
import cz.habarta.typescript.generator.Extension;
import cz.habarta.typescript.generator.Settings;
import cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures;
@@ -25,12 +27,15 @@ import cz.habarta.typescript.generator.emitter.TsModel;
import org.openremote.agent.protocol.AgentModelProvider;
import org.openremote.model.Constants;
import org.openremote.model.rules.Ruleset;
-import org.openremote.model.util.ValueUtil;
import org.openremote.model.value.MetaItemDescriptor;
-import java.util.*;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
+
/**
* Outputs enums for well known Asset types, attribute names and meta item names
* Outputs fields from {@link org.openremote.model.Constants} that begin with "UNITS" as a UNITS enum
@@ -38,10 +43,11 @@ import java.util.concurrent.atomic.AtomicInteger;
public class AssetModelInfoExtension extends Extension {
public AssetModelInfoExtension() {
+ // Ensure the asset model is initialised
+ ValueUtil.initialise(null);
// Service loader doesn't seem to work so manually load the agent model provider
ValueUtil.getModelProviders().add(new AgentModelProvider());
- // Ensure the asset model is initialised
- ValueUtil.initialise();
+ ValueUtil.doInitialise();
}
@Override
@@ -63,7 +69,7 @@ public class AssetModelInfoExtension extends Extension {
assetMap.put(assetDescriptorName.toUpperCase(Locale.ROOT), assetDescriptorName);
// Store attributes
- Arrays.stream(assetModelInfo.getAttributeDescriptors()).forEach(attributeDescriptor -> {
+ assetModelInfo.getAttributeDescriptors().values().forEach(attributeDescriptor -> {
String attributeName = attributeDescriptor.getName();
otherMap.put(attributeName.toUpperCase(Locale.ROOT), attributeName);
});
@@ -75,7 +81,7 @@ public class AssetModelInfoExtension extends Extension {
emitEnum(writer, "WellknownAttributes", otherMap);
otherMap.clear();
- Arrays.stream(ValueUtil.getMetaItemDescriptors()).forEach(metaItemDescriptor -> {
+ ValueUtil.getMetaItemDescriptors().values().forEach(metaItemDescriptor -> {
String metaName = metaItemDescriptor.getName();
otherMap.put(metaName.toUpperCase(Locale.ROOT), metaName);
});
@@ -83,7 +89,7 @@ public class AssetModelInfoExtension extends Extension {
emitEnum(writer, "WellknownMetaItems", otherMap);
otherMap.clear();
- Arrays.stream(ValueUtil.getValueDescriptors()).forEach(valueDescriptor -> {
+ ValueUtil.getValueDescriptors().values().forEach(valueDescriptor -> {
String valueTypeName = valueDescriptor.getName();
otherMap.put(valueTypeName.toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9]", ""), valueTypeName);
});
diff --git a/ui/component/model/src/util.ts b/ui/component/model/src/util.ts
index e00b59409..92037e75e 100644
--- a/ui/component/model/src/util.ts
+++ b/ui/component/model/src/util.ts
@@ -127,9 +127,9 @@ export class AssetModelUtil {
return valueDescriptor;
}
- public static resolveValueTypeFromValue(value: any): string {
+ public static resolveValueTypeFromValue(value: any): string | undefined {
if (value === null || value === undefined) {
- return WellknownValueTypes.JSON;
+ return undefined;
}
if (typeof value === "number") {
@@ -152,6 +152,10 @@ export class AssetModelUtil {
let valueType = this.resolveValueTypeFromValue(v);
+ if (!valueType) {
+ return;
+ }
+
while (dimensions > 0) {
valueType += "[]";
dimensions--;
@@ -161,8 +165,6 @@ export class AssetModelUtil {
}
if (value instanceof Date) {
return WellknownValueTypes.DATEANDTIME;
- } else {
- return WellknownValueTypes.JSONOBJECT;
}
}
diff --git a/ui/component/or-asset-viewer/src/or-add-attribute-panel.ts b/ui/component/or-asset-viewer/src/or-add-attribute-panel.ts
index d20f5f159..ac79e8fe9 100644
--- a/ui/component/or-asset-viewer/src/or-add-attribute-panel.ts
+++ b/ui/component/or-asset-viewer/src/or-add-attribute-panel.ts
@@ -78,6 +78,10 @@ export class OrAddAttributePanel extends LitElement {
this.attributeValueTypes = (AssetModelUtil.getAssetTypeInfo(this.asset.type!)?.valueDescriptors || [])
.sort(Util.sortByString((descriptor) => descriptor[0]))
+ .filter(descriptorName => {
+ const valueDescriptor = AssetModelUtil.getValueDescriptor(descriptorName);
+ return !valueDescriptor || !valueDescriptor.metaUseOnly;
+ })
.map((descriptor) => {
return [
descriptor,
diff --git a/ui/component/or-mwc-components/src/or-mwc-input.ts b/ui/component/or-mwc-components/src/or-mwc-input.ts
index 6127f10d0..07d5844e6 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -346,7 +346,7 @@ export const getValueHolderInputTemplateProvider: ValueInputProviderGenerator =
pattern = ".+";
}
if (allowedValuesConstraint && allowedValuesConstraint.allowedValues) {
- const allowedLabels = allowedValuesConstraint.allowedValueNames && allowedValuesConstraint.allowedValueNames.length === allowedValuesConstraint.allowedValues.length ? allowedValuesConstraint.allowedValueNames : undefined;
+ const allowedLabels = allowedValuesConstraint.allowedValues;
selectOptions = allowedValuesConstraint.allowedValues.map((v, i) => {
let label = allowedLabels ? allowedLabels[i] : "" + v;
label = Util.getAllowedValueLabel(label)!;
diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.ts
index 860c63bac..48d2fbd02 100644
--- a/ui/component/or-rules/src/index.ts
+++ b/ui/component/or-rules/src/index.ts
@@ -206,7 +206,6 @@ export const RuleViewInfoMap: {[key in RulesetLang]: RuleViewInfo} = {
"import org.openremote.model.rules.Assets\n" +
"import org.openremote.model.rules.Notifications\n" +
"import org.openremote.model.rules.Users\n" +
- "import org.simplejavamail.email.Email\n" +
"\n" +
"import java.util.logging.Logger\n" +
"import java.util.stream.Collectors\n" +
diff --git a/ui/component/rest/build.gradle b/ui/component/rest/build.gradle
index e2425d53e..e8059dd54 100644
--- a/ui/component/rest/build.gradle
+++ b/ui/component/rest/build.gradle
@@ -40,7 +40,6 @@ task generateTypescriptModelInfo(type: cz.habarta.typescript.generator.gradle.Ge
"java.io.**",
"java.lang.**",
"org.hibernate.**",
- "com.vladmihalcea.**",
"jakarta.**"
]
customTypeProcessor = "CustomTypeProcessor"
@@ -87,7 +86,6 @@ generateTypeScript {
"java.io.**",
"java.lang.**",
"org.hibernate.**",
- "com.vladmihalcea.**",
"jakarta.**"
]
moduleDependencies = [