Skip to content

armgit / core

Public Imported from GitHub
0

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

UI and model updates (WIP or-json-forms usage in asset editor)

Rich Turner0647f57777c0
diff --git a/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetAgent.java b/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetAgent.java
index 6a271bc20..49d046f56 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/artnet/ArtnetAgent.java
@@ -21,7 +21,7 @@ package org.openremote.agent.protocol.artnet;
import org.openremote.agent.protocol.io.IOAgent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.util.ModelIgnore;
import javax.persistence.Entity;
@@ -29,10 +29,10 @@ import javax.persistence.Entity;
@ModelIgnore
@Entity
-public class ArtnetAgent extends IOAgent<ArtnetAgent, ArtnetProtocol, AgentLink.Default> {
+public class ArtnetAgent extends IOAgent<ArtnetAgent, ArtnetProtocol, DefaultAgentLink> {
- public static final AgentDescriptor<ArtnetAgent, ArtnetProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- ArtnetAgent.class, ArtnetProtocol.class, AgentLink.Default.class
+ public static final AgentDescriptor<ArtnetAgent, ArtnetProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
+ ArtnetAgent.class, ArtnetProtocol.class, DefaultAgentLink.class
);
/**
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 12f09bda9..112378cbb 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
@@ -5,7 +5,7 @@ import org.openremote.agent.protocol.io.AbstractIOClientProtocol;
import org.openremote.agent.protocol.io.AbstractNettyIOClient;
import org.openremote.agent.protocol.udp.UDPIOClient;
import org.openremote.model.asset.AssetTreeNode;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
@@ -18,7 +18,7 @@ import java.util.concurrent.Future;
import java.util.function.Consumer;
import java.util.function.Supplier;
-public class ArtnetProtocol extends AbstractIOClientProtocol<ArtnetProtocol, ArtnetAgent, ArtnetPacket, UDPIOClient<ArtnetPacket>, AgentLink.Default> implements ProtocolAssetImport {
+public class ArtnetProtocol extends AbstractIOClientProtocol<ArtnetProtocol, ArtnetAgent, ArtnetPacket, UDPIOClient<ArtnetPacket>, DefaultAgentLink> implements ProtocolAssetImport {
public static final String PROTOCOL_DISPLAY_NAME = "Artnet";
protected final Map<AttributeRef, Consumer<ArtnetPacket>> protocolMessageConsumers = new HashMap<>();
@@ -55,7 +55,7 @@ public class ArtnetProtocol extends AbstractIOClientProtocol<ArtnetProtocol, Art
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
// AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
// ArtnetLight light = lights.get(assetId);
//
@@ -100,7 +100,7 @@ public class ArtnetProtocol extends AbstractIOClientProtocol<ArtnetProtocol, Art
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
// Attribute<?> assetAttribute = getLinkedAttribute(attribute.getReference().orElse(null));
// if(assetAttribute != null) {
// String assetId = assetAttribute.getAssetId().orElse(null);
@@ -129,7 +129,7 @@ public class ArtnetProtocol extends AbstractIOClientProtocol<ArtnetProtocol, Art
}
@Override
- protected ArtnetPacket createWriteMessage(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected ArtnetPacket createWriteMessage(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
// // TODO check for group later here
// AttributeRef attributeRef = event.getAttributeRef();
//
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgent.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgent.java
index 6368fbb58..e9d00b3d7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgent.java
@@ -21,81 +21,16 @@ package org.openremote.agent.protocol.controller;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.util.ModelIgnore;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
import javax.persistence.Entity;
-import java.util.List;
-import java.util.Map;
import java.util.Optional;
@ModelIgnore
@Entity
-public class ControllerAgent extends Agent<ControllerAgent, ControllerProtocol, ControllerAgent.ControllerAgentLink> {
-
- public static class ControllerAgentLink extends AgentLink<ControllerAgentLink> {
-
- protected String deviceName;
- protected String sensorName;
- protected String commandDeviceName;
- protected String commandName;
- protected Map<String, List<String>> commandsMap;
-
- // For Hydrators
- protected ControllerAgentLink() {}
-
- public ControllerAgentLink(String id, String deviceName) {
- super(id);
- this.deviceName = deviceName;
- }
-
- public Optional<String> getDeviceName() {
- return Optional.ofNullable(deviceName);
- }
-
- public ControllerAgentLink setDeviceName(String deviceName) {
- this.deviceName = deviceName;
- return this;
- }
-
- public Optional<String> getSensorName() {
- return Optional.ofNullable(sensorName);
- }
-
- public ControllerAgentLink setSensorName(String sensorName) {
- this.sensorName = sensorName;
- return this;
- }
-
- public Optional<String> getCommandDeviceName() {
- return Optional.ofNullable(commandDeviceName);
- }
-
- public ControllerAgentLink setCommandDeviceName(String commandDeviceName) {
- this.commandDeviceName = commandDeviceName;
- return this;
- }
-
- public Optional<String> getCommandName() {
- return Optional.ofNullable(commandName);
- }
-
- public ControllerAgentLink setCommandName(String commandName) {
- this.commandName = commandName;
- return this;
- }
-
- public Optional<Map<String, List<String>>> getCommandsMap() {
- return Optional.ofNullable(commandsMap);
- }
-
- public ControllerAgentLink setCommandsMap(Map<String, List<String>> commandsMap) {
- this.commandsMap = commandsMap;
- return this;
- }
- }
+public class ControllerAgent extends Agent<ControllerAgent, ControllerProtocol, ControllerAgentLink> {
public static final AttributeDescriptor<String> CONTROLLER_URI = new AttributeDescriptor<>("controllerURI", ValueType.TEXT);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgentLink.java
new file mode 100644
index 000000000..2ac0bd193
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerAgentLink.java
@@ -0,0 +1,89 @@
+/*
+ * 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.agent.protocol.controller;
+
+import org.openremote.model.asset.agent.AgentLink;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+public class ControllerAgentLink extends AgentLink<ControllerAgentLink> {
+
+ protected String deviceName;
+ protected String sensorName;
+ protected String commandDeviceName;
+ protected String commandName;
+ protected Map<String, List<String>> commandsMap;
+
+ // For Hydrators
+ protected ControllerAgentLink() {
+ }
+
+ public ControllerAgentLink(String id, String deviceName) {
+ super(id);
+ this.deviceName = deviceName;
+ }
+
+ public Optional<String> getDeviceName() {
+ return Optional.ofNullable(deviceName);
+ }
+
+ public ControllerAgentLink setDeviceName(String deviceName) {
+ this.deviceName = deviceName;
+ return this;
+ }
+
+ public Optional<String> getSensorName() {
+ return Optional.ofNullable(sensorName);
+ }
+
+ public ControllerAgentLink setSensorName(String sensorName) {
+ this.sensorName = sensorName;
+ return this;
+ }
+
+ public Optional<String> getCommandDeviceName() {
+ return Optional.ofNullable(commandDeviceName);
+ }
+
+ public ControllerAgentLink setCommandDeviceName(String commandDeviceName) {
+ this.commandDeviceName = commandDeviceName;
+ return this;
+ }
+
+ public Optional<String> getCommandName() {
+ return Optional.ofNullable(commandName);
+ }
+
+ public ControllerAgentLink setCommandName(String commandName) {
+ this.commandName = commandName;
+ return this;
+ }
+
+ public Optional<Map<String, List<String>>> getCommandsMap() {
+ return Optional.ofNullable(commandsMap);
+ }
+
+ public ControllerAgentLink setCommandsMap(Map<String, List<String>> commandsMap) {
+ this.commandsMap = commandsMap;
+ return this;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java
index 3f2ae0676..83765ddd3 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/controller/ControllerProtocol.java
@@ -55,7 +55,6 @@ import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.openremote.agent.protocol.controller.ControllerAgent.*;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
import static org.openremote.container.web.WebTargetBuilder.CONNECTION_POOL_SIZE;
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
index f8b0c7a4b..81b26a154 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgent.java
@@ -21,109 +21,15 @@ package org.openremote.agent.protocol.http;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
import org.openremote.model.value.ValueType;
import javax.persistence.Entity;
-import java.util.List;
-import java.util.Map;
import java.util.Optional;
@Entity
-public class HTTPAgent extends Agent<HTTPAgent, HTTPProtocol, HTTPAgent.HTTPAgentLink> {
-
- public static class HTTPAgentLink extends AgentLink<HTTPAgentLink> {
-
- protected Map<String, List<String>> headers;
- protected Map<String, List<String>> queryParameters;
- protected Integer pollingMillis;
- protected Boolean pagingMode;
- protected String path;
- protected HTTPMethod method;
- protected String contentType;
- protected String pollingAttribute;
-
- // For Hydrators
- protected HTTPAgentLink() {}
-
- public HTTPAgentLink(String id) {
- super(id);
- }
-
- public Optional<Map<String, List<String>>> getHeaders() {
- return Optional.ofNullable(headers);
- }
-
- public HTTPAgentLink setHeaders(ValueType.MultivaluedStringMap headers) {
- this.headers = headers;
- return this;
- }
-
- public Optional<Map<String, List<String>>> getQueryParameters() {
- return Optional.ofNullable(queryParameters);
- }
-
- public HTTPAgentLink setQueryParameters(ValueType.MultivaluedStringMap queryParameters) {
- this.queryParameters = queryParameters;
- return this;
- }
-
- public Optional<Integer> getPollingMillis() {
- return Optional.ofNullable(pollingMillis);
- }
-
- public HTTPAgentLink setPollingMillis(Integer pollingMillis) {
- this.pollingMillis = pollingMillis;
- return this;
- }
-
- public Optional<Boolean> getPagingMode() {
- return Optional.ofNullable(pagingMode);
- }
-
- public HTTPAgentLink setPagingMode(Boolean pagingMode) {
- this.pagingMode = pagingMode;
- return this;
- }
-
- public Optional<String> getPath() {
- return Optional.ofNullable(path);
- }
-
- public HTTPAgentLink setPath(String path) {
- this.path = path;
- return this;
- }
-
- public Optional<HTTPMethod> getMethod() {
- return Optional.ofNullable(method);
- }
-
- public HTTPAgentLink setMethod(HTTPMethod method) {
- this.method = method;
- return this;
- }
-
- public Optional<String> getContentType() {
- return Optional.ofNullable(contentType);
- }
-
- public HTTPAgentLink setContentType(String contentType) {
- this.contentType = contentType;
- return this;
- }
-
- public Optional<String> getPollingAttribute() {
- return Optional.ofNullable(pollingAttribute);
- }
-
- public HTTPAgentLink setPollingAttribute(String pollingAttribute) {
- this.pollingAttribute = pollingAttribute;
- return this;
- }
- }
+public class HTTPAgent extends Agent<HTTPAgent, HTTPProtocol, HTTPAgentLink> {
public static final ValueDescriptor<HTTPMethod> VALUE_HTTP_METHOD = new ValueDescriptor<>("HTTPMethod", HTTPMethod.class);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java
new file mode 100644
index 000000000..24668d6c5
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPAgentLink.java
@@ -0,0 +1,119 @@
+/*
+ * 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.agent.protocol.http;
+
+import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.value.ValueType;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+public class HTTPAgentLink extends AgentLink<HTTPAgentLink> {
+
+ protected Map<String, List<String>> headers;
+ protected Map<String, List<String>> queryParameters;
+ protected Integer pollingMillis;
+ protected Boolean pagingMode;
+ protected String path;
+ protected HTTPMethod method;
+ protected String contentType;
+ protected String pollingAttribute;
+
+ // For Hydrators
+ protected HTTPAgentLink() {
+ }
+
+ public HTTPAgentLink(String id) {
+ super(id);
+ }
+
+ public Optional<Map<String, List<String>>> getHeaders() {
+ return Optional.ofNullable(headers);
+ }
+
+ public HTTPAgentLink setHeaders(ValueType.MultivaluedStringMap headers) {
+ this.headers = headers;
+ return this;
+ }
+
+ public Optional<Map<String, List<String>>> getQueryParameters() {
+ return Optional.ofNullable(queryParameters);
+ }
+
+ public HTTPAgentLink setQueryParameters(ValueType.MultivaluedStringMap queryParameters) {
+ this.queryParameters = queryParameters;
+ return this;
+ }
+
+ public Optional<Integer> getPollingMillis() {
+ return Optional.ofNullable(pollingMillis);
+ }
+
+ public HTTPAgentLink setPollingMillis(Integer pollingMillis) {
+ this.pollingMillis = pollingMillis;
+ return this;
+ }
+
+ public Optional<Boolean> getPagingMode() {
+ return Optional.ofNullable(pagingMode);
+ }
+
+ public HTTPAgentLink setPagingMode(Boolean pagingMode) {
+ this.pagingMode = pagingMode;
+ return this;
+ }
+
+ public Optional<String> getPath() {
+ return Optional.ofNullable(path);
+ }
+
+ public HTTPAgentLink setPath(String path) {
+ this.path = path;
+ return this;
+ }
+
+ public Optional<HTTPMethod> getMethod() {
+ return Optional.ofNullable(method);
+ }
+
+ public HTTPAgentLink setMethod(HTTPMethod method) {
+ this.method = method;
+ return this;
+ }
+
+ public Optional<String> getContentType() {
+ return Optional.ofNullable(contentType);
+ }
+
+ public HTTPAgentLink setContentType(String contentType) {
+ this.contentType = contentType;
+ return this;
+ }
+
+ public Optional<String> getPollingAttribute() {
+ return Optional.ofNullable(pollingAttribute);
+ }
+
+ public HTTPAgentLink setPollingAttribute(String pollingAttribute) {
+ this.pollingAttribute = pollingAttribute;
+ return this;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
index 701469e23..564d51278 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/http/HTTPProtocol.java
@@ -59,7 +59,6 @@ import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.openremote.agent.protocol.http.HTTPAgent.*;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.container.web.QueryParameterInjectorFilter.QUERY_PARAMETERS_PROPERTY;
import static org.openremote.container.web.WebTargetBuilder.createClient;
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 fbed52883..f79ed7413 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
@@ -21,68 +21,16 @@ package org.openremote.agent.protocol.knx;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
import org.openremote.model.value.ValueType;
import javax.persistence.Entity;
-import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.util.Optional;
@Entity
-public class KNXAgent extends Agent<KNXAgent, KNXProtocol, KNXAgent.KNXAgentLink> {
-
- public static class KNXAgentLink extends AgentLink<KNXAgentLink> {
-
- @NotNull
- @Pattern(regexp = "^\\d{1,3}\\.\\d{1,3}$")
- protected String dpt;
-
- @Pattern(regexp = "^\\d{1,3}/\\d{1,3}/\\d{1,3}$")
- protected String actionGroupAddress;
-
- @Pattern(regexp = "^\\d{1,3}/\\d{1,3}/\\d{1,3}$")
- protected String statusGroupAddress;
-
- // For Hydrators
- protected KNXAgentLink() {}
-
- public KNXAgentLink(String id, String dpt, String actionGroupAddress, String statusGroupAddress) {
- super(id);
- this.dpt = dpt;
- this.actionGroupAddress = actionGroupAddress;
- this.statusGroupAddress = statusGroupAddress;
- }
-
- public Optional<String> getDpt() {
- return Optional.ofNullable(dpt);
- }
-
- public KNXAgentLink setDpt(String dpt) {
- this.dpt = dpt;
- return this;
- }
-
- public Optional<String> getActionGroupAddress() {
- return Optional.ofNullable(actionGroupAddress);
- }
-
- public KNXAgentLink setActionGroupAddress(String actionGroupAddress) {
- this.actionGroupAddress = actionGroupAddress;
- return this;
- }
-
- public Optional<String> getStatusGroupAddress() {
- return Optional.ofNullable(statusGroupAddress);
- }
-
- public KNXAgentLink setStatusGroupAddress(String statusGroupAddress) {
- this.statusGroupAddress = statusGroupAddress;
- return this;
- }
- }
+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);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgentLink.java
new file mode 100644
index 000000000..8d236b7dd
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXAgentLink.java
@@ -0,0 +1,77 @@
+/*
+ * 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.agent.protocol.knx;
+
+import org.openremote.model.asset.agent.AgentLink;
+
+import javax.validation.constraints.NotNull;
+import javax.validation.constraints.Pattern;
+import java.util.Optional;
+
+public class KNXAgentLink extends AgentLink<KNXAgentLink> {
+
+ @NotNull
+ @Pattern(regexp = "^\\d{1,3}\\.\\d{1,3}$")
+ protected String dpt;
+
+ @Pattern(regexp = "^\\d{1,3}/\\d{1,3}/\\d{1,3}$")
+ protected String actionGroupAddress;
+
+ @Pattern(regexp = "^\\d{1,3}/\\d{1,3}/\\d{1,3}$")
+ protected String statusGroupAddress;
+
+ // For Hydrators
+ protected KNXAgentLink() {
+ }
+
+ public KNXAgentLink(String id, String dpt, String actionGroupAddress, String statusGroupAddress) {
+ super(id);
+ this.dpt = dpt;
+ this.actionGroupAddress = actionGroupAddress;
+ this.statusGroupAddress = statusGroupAddress;
+ }
+
+ public Optional<String> getDpt() {
+ return Optional.ofNullable(dpt);
+ }
+
+ public KNXAgentLink setDpt(String dpt) {
+ this.dpt = dpt;
+ return this;
+ }
+
+ public Optional<String> getActionGroupAddress() {
+ return Optional.ofNullable(actionGroupAddress);
+ }
+
+ public KNXAgentLink setActionGroupAddress(String actionGroupAddress) {
+ this.actionGroupAddress = actionGroupAddress;
+ return this;
+ }
+
+ public Optional<String> getStatusGroupAddress() {
+ return Optional.ofNullable(statusGroupAddress);
+ }
+
+ public KNXAgentLink setStatusGroupAddress(String statusGroupAddress) {
+ this.statusGroupAddress = statusGroupAddress;
+ return this;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
index 2dc1323ab..7e96e0bf4 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/knx/KNXProtocol.java
@@ -44,7 +44,7 @@ import static org.openremote.model.value.MetaItemType.AGENT_LINK;
/**
* This protocol is used to connect to a KNX bus via an IP interface.
*/
-public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgent.KNXAgentLink> implements ProtocolAssetImport {
+public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgentLink> implements ProtocolAssetImport {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, KNXProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "KNX";
@@ -91,7 +91,7 @@ public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgent.KNXAgentLin
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, KNXAgent.KNXAgentLink agentLink) throws RuntimeException {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, KNXAgentLink agentLink) throws RuntimeException {
final AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
// Check there is a META_KNX_DPT
@@ -126,7 +126,7 @@ public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgent.KNXAgentLin
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, KNXAgent.KNXAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, KNXAgentLink agentLink) {
final AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
// If this attribute is registered for status updates then un-subscribe it
@@ -137,7 +137,7 @@ public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgent.KNXAgentLin
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, KNXAgent.KNXAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, KNXAgentLink agentLink, AttributeEvent event, Object processedValue) {
synchronized (attributeActionMap) {
Datapoint datapoint = attributeActionMap.get(event.getAttributeRef());
@@ -298,7 +298,7 @@ public class KNXProtocol extends AbstractProtocol<KNXAgent, KNXAgent.KNXAgentLin
String attrName = assetName.replaceAll(" ", "");
ValueDescriptor<?> type = TypeMapper.toAttributeType(datapoint);
- KNXAgent.KNXAgentLink agentLink = new KNXAgent.KNXAgentLink(
+ KNXAgentLink agentLink = new KNXAgentLink(
agent.getId(),
datapoint.getDPT(),
!isStatusGA ? datapoint.getMainAddress().toString() : null,
diff --git a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialAgent.java b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialAgent.java
index b3d740308..cd63e64fc 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialAgent.java
@@ -22,18 +22,18 @@ package org.openremote.agent.protocol.serial;
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.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.value.AttributeDescriptor;
import javax.persistence.Entity;
@Entity
-public class SerialAgent extends IOAgent<SerialAgent, SerialProtocol, AgentLink.Default> {
+public class SerialAgent extends IOAgent<SerialAgent, SerialProtocol, DefaultAgentLink> {
public static final AttributeDescriptor<String> SERIAL_PORT = Agent.SERIAL_PORT.withOptional(false);
- public static final AgentDescriptor<SerialAgent, SerialProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- SerialAgent.class, SerialProtocol.class, AgentLink.Default.class
+ public static final AgentDescriptor<SerialAgent, SerialProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
+ SerialAgent.class, SerialProtocol.class, DefaultAgentLink.class
);
/**
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 8f3f0110f..666bf5775 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
@@ -20,7 +20,7 @@
package org.openremote.agent.protocol.serial;
import io.netty.channel.ChannelHandler;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeExecuteStatus;
@@ -44,7 +44,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* handle the communication and all messages are processed as strings; if you require custom message type handling
* then please sub class the {@link AbstractSerialProtocol}).
*/
-public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, SerialAgent, AgentLink.Default, String, SerialIOClient<String>> {
+public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, SerialAgent, DefaultAgentLink, String, SerialIOClient<String>> {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, SerialProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "Serial";
@@ -61,7 +61,7 @@ public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, Seria
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
Consumer<String> messageConsumer = ProtocolUtil.createGenericAttributeMessageConsumer(assetId, attribute, agentLink, timerService::getCurrentTimeMillis, this::updateLinkedAttribute);
@@ -74,7 +74,7 @@ public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, Seria
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
protocolMessageConsumers.removeIf(attRefConsumerPair -> attRefConsumerPair.key.equals(attributeRef));
}
@@ -94,7 +94,7 @@ public class SerialProtocol extends AbstractSerialProtocol<SerialProtocol, Seria
}
@Override
- protected String createWriteMessage(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected String createWriteMessage(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
if (attribute.getType().equals(ValueType.EXECUTION_STATUS)) {
AttributeExecuteStatus status = event.getValue()
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgent.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgent.java
index c2f954ab4..3f1c02590 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgent.java
@@ -19,41 +19,13 @@
*/
package org.openremote.agent.protocol.simulator;
-import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
-import org.openremote.model.simulator.SimulatorReplayDatapoint;
-import org.openremote.model.value.AttributeDescriptor;
import javax.persistence.Entity;
-import java.util.Optional;
@Entity
-public class SimulatorAgent extends Agent<SimulatorAgent, SimulatorProtocol, SimulatorAgent.SimulatorAgentLink> {
-
- public static class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {
-
- @JsonPropertyDescription("Used to store 24h dataset of values that should be replayed (i.e. written to the" +
- " linked attribute) in a continuous loop.")
- protected SimulatorReplayDatapoint[] replayData;
-
- // For Hydrators
- protected SimulatorAgentLink() {}
-
- public SimulatorAgentLink(String id) {
- super(id);
- }
-
- public Optional<SimulatorReplayDatapoint[]> getReplayData() {
- return Optional.ofNullable(replayData);
- }
-
- public SimulatorAgentLink setReplayData(SimulatorReplayDatapoint[] replayData) {
- this.replayData = replayData;
- return this;
- }
- }
+public class SimulatorAgent extends Agent<SimulatorAgent, SimulatorProtocol, SimulatorAgentLink> {
public static final AgentDescriptor<SimulatorAgent, SimulatorProtocol, SimulatorAgentLink> DESCRIPTOR = new AgentDescriptor<>(
SimulatorAgent.class, SimulatorProtocol.class, SimulatorAgentLink.class
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java
new file mode 100644
index 000000000..06037da3e
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorAgentLink.java
@@ -0,0 +1,50 @@
+/*
+ * 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.agent.protocol.simulator;
+
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.simulator.SimulatorReplayDatapoint;
+
+import java.util.Optional;
+
+public class SimulatorAgentLink extends AgentLink<SimulatorAgentLink> {
+
+ @JsonPropertyDescription("Used to store 24h dataset of values that should be replayed (i.e. written to the" +
+ " linked attribute) in a continuous loop.")
+ protected SimulatorReplayDatapoint[] replayData;
+
+ // For Hydrators
+ protected SimulatorAgentLink() {
+ }
+
+ public SimulatorAgentLink(String id) {
+ super(id);
+ }
+
+ public Optional<SimulatorReplayDatapoint[]> getReplayData() {
+ return Optional.ofNullable(replayData);
+ }
+
+ public SimulatorAgentLink setReplayData(SimulatorReplayDatapoint[] replayData) {
+ this.replayData = replayData;
+ return this;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
index a04a46463..57e21c259 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/simulator/SimulatorProtocol.java
@@ -40,7 +40,7 @@ import java.util.logging.Logger;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
-public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, SimulatorAgent.SimulatorAgentLink> {
+public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, SimulatorAgentLink> {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, SimulatorProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "Simulator";
@@ -71,7 +71,7 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, SimulatorAgent.SimulatorAgentLink agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, SimulatorAgentLink agentLink) {
// Look for replay data
agentLink.getReplayData()
@@ -89,7 +89,7 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, SimulatorAgent.SimulatorAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, SimulatorAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
ScheduledFuture<?> updateValueFuture = replayMap.remove(attributeRef);
@@ -99,7 +99,7 @@ public class SimulatorProtocol extends AbstractProtocol<SimulatorAgent, Simulato
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, SimulatorAgent.SimulatorAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, SimulatorAgentLink agentLink, AttributeEvent event, Object processedValue) {
if (replayMap.containsKey(event.getAttributeRef())) {
LOG.info("Attempt to write to linked attribute that is configured for value replay so ignoring: " + attribute);
return;
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 bc606af99..beb579115 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
@@ -3,40 +3,14 @@ package org.openremote.agent.protocol.snmp;
import com.fasterxml.jackson.annotation.JsonValue;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
import javax.persistence.Entity;
-import javax.validation.constraints.NotNull;
import java.util.Optional;
@Entity
-public class SNMPAgent extends Agent<SNMPAgent, SNMPProtocol, SNMPAgent.SNMPAgentLink> {
-
- public static class SNMPAgentLink extends AgentLink<SNMPAgent.SNMPAgentLink> {
-
- @NotNull
- protected String oid;
-
- // For Hydrators
- protected SNMPAgentLink() {}
-
- public SNMPAgentLink(String id, String oid) {
- super(id);
-
- this.oid = oid;
- }
-
- public Optional<String> getOID() {
- return Optional.ofNullable(oid);
- }
-
- public SNMPAgent.SNMPAgentLink setOID(String oid) {
- this.oid = oid;
- return this;
- }
- }
+public class SNMPAgent extends Agent<SNMPAgent, SNMPProtocol, SNMPAgentLink> {
public enum SNMPVersion
{
diff --git a/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgentLink.java
new file mode 100644
index 000000000..d55f1ba1a
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/snmp/SNMPAgentLink.java
@@ -0,0 +1,50 @@
+/*
+ * 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.agent.protocol.snmp;
+
+import org.openremote.model.asset.agent.AgentLink;
+
+import javax.validation.constraints.NotNull;
+import java.util.Optional;
+
+public class SNMPAgentLink extends AgentLink<SNMPAgentLink> {
+
+ @NotNull
+ protected String oid;
+
+ // For Hydrators
+ protected SNMPAgentLink() {
+ }
+
+ public SNMPAgentLink(String id, String oid) {
+ super(id);
+
+ this.oid = oid;
+ }
+
+ public Optional<String> getOID() {
+ return Optional.ofNullable(oid);
+ }
+
+ public SNMPAgentLink setOID(String oid) {
+ this.oid = oid;
+ return this;
+ }
+}
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 57daa47e9..51a134237 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
@@ -25,7 +25,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* <p>
* To use this protocol create a {@link SNMPAgent}.
*/
-public class SNMPProtocol extends AbstractProtocol<SNMPAgent, SNMPAgent.SNMPAgentLink> {
+public class SNMPProtocol extends AbstractProtocol<SNMPAgent, SNMPAgentLink> {
public static final String PROTOCOL_DISPLAY_NAME = "SNMP Client";
protected static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, SNMPProtocol.class);
@@ -100,7 +100,7 @@ public class SNMPProtocol extends AbstractProtocol<SNMPAgent, SNMPAgent.SNMPAgen
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, SNMPAgent.SNMPAgentLink agentLink) throws RuntimeException {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, SNMPAgentLink agentLink) throws RuntimeException {
String oid = agentLink.getOID().orElseThrow(() -> {
String msg = "No OID provided for protocol: " + this;
LOG.info(msg);
@@ -117,12 +117,12 @@ public class SNMPProtocol extends AbstractProtocol<SNMPAgent, SNMPAgent.SNMPAgen
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, SNMPAgent.SNMPAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, SNMPAgentLink agentLink) {
agentLink.getOID().ifPresent(oidMap::remove);
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, SNMPAgent.SNMPAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, SNMPAgentLink agentLink, AttributeEvent event, Object processedValue) {
// Nothing to do here
}
}
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 bf65f466f..070265272 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
@@ -21,19 +21,19 @@ package org.openremote.agent.protocol.tcp;
import org.openremote.agent.protocol.io.IOAgent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.value.AttributeDescriptor;
import javax.persistence.Entity;
@Entity
-public class TCPAgent extends IOAgent<TCPAgent, TCPProtocol, AgentLink.Default> {
+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 AgentDescriptor<TCPAgent, TCPProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- TCPAgent.class, TCPProtocol.class, AgentLink.Default.class
+ 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/tcp/TCPProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPProtocol.java
index 33e8ff4e3..a72e30f17 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPProtocol.java
@@ -20,7 +20,7 @@
package org.openremote.agent.protocol.tcp;
import io.netty.channel.ChannelHandler;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
@@ -44,7 +44,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* <p>
* To use this protocol create a {@link TCPAgent}.
*/
-public class TCPProtocol extends AbstractTCPClientProtocol<TCPProtocol, TCPAgent, AgentLink.Default, String, TCPIOClient<String>> {
+public class TCPProtocol extends AbstractTCPClientProtocol<TCPProtocol, TCPAgent, DefaultAgentLink, String, TCPIOClient<String>> {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, TCPProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "TCP Client";
@@ -61,7 +61,7 @@ public class TCPProtocol extends AbstractTCPClientProtocol<TCPProtocol, TCPAgent
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
Consumer<String> messageConsumer = ProtocolUtil.createGenericAttributeMessageConsumer(assetId, attribute, agentLink, timerService::getCurrentTimeMillis, this::updateLinkedAttribute);
@@ -74,7 +74,7 @@ public class TCPProtocol extends AbstractTCPClientProtocol<TCPProtocol, TCPAgent
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
protocolMessageConsumers.removeIf(attRefConsumerPair -> attRefConsumerPair.key.equals(attributeRef));
}
@@ -94,7 +94,7 @@ public class TCPProtocol extends AbstractTCPClientProtocol<TCPProtocol, TCPAgent
}
@Override
- protected String createWriteMessage(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected String createWriteMessage(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
return Values.convert(processedValue, String.class);
}
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAgent.java b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAgent.java
index 05d982002..ff42e8c7c 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/tradfri/TradfriAgent.java
@@ -21,7 +21,7 @@ package org.openremote.agent.protocol.tradfri;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.util.ModelIgnore;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
@@ -31,10 +31,10 @@ import java.util.Optional;
@ModelIgnore
@Entity
-public class TradfriAgent extends Agent<TradfriAgent, TradfriProtocol, AgentLink.Default> {
+public class TradfriAgent extends Agent<TradfriAgent, TradfriProtocol, DefaultAgentLink> {
- public static final AgentDescriptor<TradfriAgent, TradfriProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- TradfriAgent.class, TradfriProtocol.class, AgentLink.Default.class
+ public static final AgentDescriptor<TradfriAgent, TradfriProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
+ TradfriAgent.class, TradfriProtocol.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 f241f38b0..885b8b008 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
@@ -9,8 +9,8 @@ import org.openremote.container.util.UniqueIdentifierGenerator;
import org.openremote.model.Container;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.agent.Agent;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.asset.agent.ConnectionStatus;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.MetaItem;
@@ -31,7 +31,7 @@ import static org.openremote.model.value.MetaItemType.AGENT_LINK;
* {@link Agent}; {@link Asset}s are automatically added/removed depending on whether they are available on the gateway,
* for a given {@link Agent} a device {@link Asset} will have a consistent ID.
*/
-public class TradfriProtocol extends AbstractProtocol<TradfriAgent, AgentLink.Default> {
+public class TradfriProtocol extends AbstractProtocol<TradfriAgent, DefaultAgentLink> {
/**
* The logger for the IKEA TRÅDFRI protocol.
@@ -122,17 +122,17 @@ public class TradfriProtocol extends AbstractProtocol<TradfriAgent, AgentLink.De
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
// Nothing to do here as assets are already connected to devices
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
// Nothing to do here
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
Device device = tradfriDevices.get(event.getAttributeRef().getId());
@@ -243,7 +243,7 @@ public class TradfriProtocol extends AbstractProtocol<TradfriAgent, AgentLink.De
// Add agent links
lightAsset.getAttributes().get(BRIGHTNESS).ifPresent(attribute -> attribute.addOrReplaceMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.getId()))
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.getId()))
));
asset = lightAsset;
}
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 3ab682508..0d2016120 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
@@ -21,19 +21,19 @@ package org.openremote.agent.protocol.udp;
import org.openremote.agent.protocol.io.IOAgent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.value.AttributeDescriptor;
import javax.persistence.Entity;
@Entity
-public class UDPAgent extends IOAgent<UDPAgent, UDPProtocol, AgentLink.Default> {
+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 AgentDescriptor<UDPAgent, UDPProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- UDPAgent.class, UDPProtocol.class, AgentLink.Default.class
+ 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/udp/UDPProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPProtocol.java
index aea596b04..fa85beec7 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/udp/UDPProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPProtocol.java
@@ -20,7 +20,7 @@
package org.openremote.agent.protocol.udp;
import io.netty.channel.ChannelHandler;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
@@ -44,7 +44,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* <p>
* To use this protocol create a {@link UDPAgent}.
*/
-public class UDPProtocol extends AbstractUDPProtocol<UDPProtocol, UDPAgent, AgentLink.Default, String, UDPIOClient<String>> {
+public class UDPProtocol extends AbstractUDPProtocol<UDPProtocol, UDPAgent, DefaultAgentLink, String, UDPIOClient<String>> {
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, UDPProtocol.class);
public static final String PROTOCOL_DISPLAY_NAME = "UDP Client";
@@ -60,7 +60,7 @@ public class UDPProtocol extends AbstractUDPProtocol<UDPProtocol, UDPAgent, Agen
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
Consumer<String> messageConsumer = ProtocolUtil.createGenericAttributeMessageConsumer(assetId, attribute, agentLink, timerService::getCurrentTimeMillis, this::updateLinkedAttribute);
@@ -74,7 +74,7 @@ public class UDPProtocol extends AbstractUDPProtocol<UDPProtocol, UDPAgent, Agen
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
protocolMessageConsumers.removeIf(attributeRefConsumerPair -> attributeRefConsumerPair.key.equals(attributeRef));
}
@@ -91,7 +91,7 @@ public class UDPProtocol extends AbstractUDPProtocol<UDPProtocol, UDPAgent, Agen
}
@Override
- protected String createWriteMessage(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected String createWriteMessage(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
return Values.convert(processedValue, String.class);
}
}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
index 636466d27..5a0b4a008 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/AbstractVelbusProtocol.java
@@ -52,7 +52,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
import static org.openremote.model.util.TextUtil.isNullOrEmpty;
import static org.openremote.model.value.MetaItemType.AGENT_LINK;
-public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,T>, T extends VelbusAgent<T, S>> extends AbstractProtocol<T, VelbusAgent.VelbusAgentLink> implements
+public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,T>, T extends VelbusAgent<T, S>> extends AbstractProtocol<T, VelbusAgentLink> implements
ProtocolAssetImport {
public static final int DEFAULT_TIME_INJECTION_INTERVAL_SECONDS = 3600 * 6;
@@ -99,7 +99,7 @@ public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, VelbusAgent.VelbusAgentLink agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, VelbusAgentLink agentLink) {
// Get the device that this attribute is linked to
int deviceAddress = getOrThrowAgentLinkProperty(agentLink.getDeviceAddress(), "device address");
@@ -118,7 +118,7 @@ public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, VelbusAgent.VelbusAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, VelbusAgentLink agentLink) {
// Get the device that this attribute is linked to
int deviceAddress = getOrThrowAgentLinkProperty(agentLink.getDeviceAddress(), "device address");
@@ -132,7 +132,7 @@ public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, VelbusAgent.VelbusAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, VelbusAgentLink agentLink, AttributeEvent event, Object processedValue) {
// Get the device that this attribute is linked to
int deviceAddress = getOrThrowAgentLinkProperty(agentLink.getDeviceAddress(), "device address");
@@ -215,7 +215,7 @@ public abstract class AbstractVelbusProtocol<S extends AbstractVelbusProtocol<S,
Arrays.stream(processors).flatMap(processor ->
processor.getPropertyDescriptors(type).stream().map(descriptor -> {
- VelbusAgent.VelbusAgentLink agentLink = new VelbusAgent.VelbusAgentLink(agent.getId(), baseAddress, descriptor.getLinkName());
+ VelbusAgentLink agentLink = new VelbusAgentLink(agent.getId(), baseAddress, descriptor.getLinkName());
Attribute<?> attribute = new Attribute<>(descriptor.getName(), descriptor.getAttributeValueDescriptor())
.addMeta(
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgent.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgent.java
index edb6bee0c..7bf76a4ce 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgent.java
@@ -19,59 +19,13 @@
*/
package org.openremote.agent.protocol.velbus;
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.asset.agent.Agent;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
-import javax.validation.constraints.Max;
-import javax.validation.constraints.Min;
-import javax.validation.constraints.NotBlank;
-import javax.validation.constraints.NotNull;
import java.util.Optional;
-public abstract class VelbusAgent<T extends VelbusAgent<T, U>, U extends AbstractVelbusProtocol<U, T>> extends Agent<T, U, VelbusAgent.VelbusAgentLink> {
-
- public static class VelbusAgentLink extends AgentLink<VelbusAgentLink> {
-
- @NotBlank
- protected String deviceValueLink;
-
- @Min(1)
- @Max(255)
- @NotNull
- protected Integer deviceAddress;
-
- // For Hydrators
- protected VelbusAgentLink() {}
-
- @JsonCreator
- public VelbusAgentLink(@JsonProperty("id") String id, @JsonProperty("deviceAddress") Integer deviceAddress, @JsonProperty("deviceValueLink") String deviceValueLink) {
- super(id);
- this.deviceValueLink = deviceValueLink;
- this.deviceAddress = deviceAddress;
- }
-
- public Optional<String> getDeviceValueLink() {
- return Optional.ofNullable(deviceValueLink);
- }
-
- public VelbusAgentLink setDeviceValueLink(String deviceValueLink) {
- this.deviceValueLink = deviceValueLink;
- return this;
- }
-
- public Optional<Integer> getDeviceAddress() {
- return Optional.ofNullable(deviceAddress);
- }
-
- public VelbusAgentLink setDeviceAddress(Integer deviceAddress) {
- this.deviceAddress = deviceAddress;
- return this;
- }
- }
+public abstract class VelbusAgent<T extends VelbusAgent<T, U>, U extends AbstractVelbusProtocol<U, T>> extends Agent<T, U, VelbusAgentLink> {
public static final AttributeDescriptor<Integer> TIME_INJECTION_INTERVAL_SECONDS = new AttributeDescriptor<>("timeInjectionInterval", ValueType.POSITIVE_INTEGER);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgentLink.java
new file mode 100644
index 000000000..31f1f8efb
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/velbus/VelbusAgentLink.java
@@ -0,0 +1,70 @@
+/*
+ * 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.agent.protocol.velbus;
+
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import org.openremote.model.asset.agent.AgentLink;
+
+import javax.validation.constraints.Max;
+import javax.validation.constraints.Min;
+import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
+import java.util.Optional;
+
+public class VelbusAgentLink extends AgentLink<VelbusAgentLink> {
+
+ @NotBlank
+ protected String deviceValueLink;
+
+ @Min(1)
+ @Max(255)
+ @NotNull
+ protected Integer deviceAddress;
+
+ // For Hydrators
+ protected VelbusAgentLink() {
+ }
+
+ @JsonCreator
+ public VelbusAgentLink(@JsonProperty("id") String id, @JsonProperty("deviceAddress") Integer deviceAddress, @JsonProperty("deviceValueLink") String deviceValueLink) {
+ super(id);
+ this.deviceValueLink = deviceValueLink;
+ this.deviceAddress = deviceAddress;
+ }
+
+ public Optional<String> getDeviceValueLink() {
+ return Optional.ofNullable(deviceValueLink);
+ }
+
+ public VelbusAgentLink setDeviceValueLink(String deviceValueLink) {
+ this.deviceValueLink = deviceValueLink;
+ return this;
+ }
+
+ public Optional<Integer> getDeviceAddress() {
+ return Optional.ofNullable(deviceAddress);
+ }
+
+ public VelbusAgentLink setDeviceAddress(Integer deviceAddress) {
+ this.deviceAddress = deviceAddress;
+ return this;
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgent.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgent.java
index ca11ebbe4..b437c01c2 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgent.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgent.java
@@ -19,10 +19,8 @@
*/
package org.openremote.agent.protocol.websocket;
-import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import org.openremote.agent.protocol.io.IOAgent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueDescriptor;
import org.openremote.model.value.ValueType;
@@ -31,29 +29,7 @@ import javax.persistence.Entity;
import java.util.Optional;
@Entity
-public class WebsocketAgent extends IOAgent<WebsocketAgent, WebsocketAgentProtocol, WebsocketAgent.WebsocketAgentLink> {
-
- public static class WebsocketAgentLink extends AgentLink<WebsocketAgentLink> {
-
- protected WebsocketSubscription[] websocketSubscriptions;
-
- // For Hydrators
- protected WebsocketAgentLink() {}
-
- public WebsocketAgentLink(String id) {
- super(id);
- }
-
- @JsonPropertyDescription("Array of WebsocketSubscriptions that should be executed when the linked attribute is linked; the subscriptions are executed in the order specified in the array.")
- public Optional<WebsocketSubscription[]> getWebsocketSubscriptions() {
- return Optional.ofNullable(websocketSubscriptions);
- }
-
- public WebsocketAgentLink setWebsocketSubscriptions(WebsocketSubscription[] websocketSubscriptions) {
- this.websocketSubscriptions = websocketSubscriptions;
- return this;
- }
- }
+public class WebsocketAgent extends IOAgent<WebsocketAgent, WebsocketAgentProtocol, WebsocketAgentLink> {
public static final ValueDescriptor<WebsocketSubscription> WEBSOCKET_SUBSCRIPTION_VALUE_DESCRIPTOR = new ValueDescriptor<>("websocketSubscription", WebsocketSubscription.class);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentLink.java
new file mode 100644
index 000000000..dbda928bc
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketAgentLink.java
@@ -0,0 +1,48 @@
+/*
+ * 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.agent.protocol.websocket;
+
+import com.fasterxml.jackson.annotation.JsonPropertyDescription;
+import org.openremote.model.asset.agent.AgentLink;
+
+import java.util.Optional;
+
+public class WebsocketAgentLink extends AgentLink<WebsocketAgentLink> {
+
+ protected WebsocketSubscription[] websocketSubscriptions;
+
+ // For Hydrators
+ protected WebsocketAgentLink() {
+ }
+
+ public WebsocketAgentLink(String id) {
+ super(id);
+ }
+
+ @JsonPropertyDescription("Array of WebsocketSubscriptions that should be executed when the linked attribute is linked; the subscriptions are executed in the order specified in the array.")
+ public Optional<WebsocketSubscription[]> getWebsocketSubscriptions() {
+ return Optional.ofNullable(websocketSubscriptions);
+ }
+
+ public WebsocketAgentLink setWebsocketSubscriptions(WebsocketSubscription[] websocketSubscriptions) {
+ this.websocketSubscriptions = websocketSubscriptions;
+ return this;
+ }
+}
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 24010b0ec..8be7c73dc 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
@@ -65,10 +65,10 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;
* <h2>Protocol Specifics</h2>
* When the websocket connection is established it is possible to subscribe to events by specifying the
* {@link WebsocketAgent#CONNECT_SUBSCRIPTIONS} on the {@link WebsocketAgent} or
- * {@link WebsocketAgent.WebsocketAgentLink#getConnectSubscriptions()} on linked {@link Attribute}s; a
+ * {@link WebsocketAgentLink#getConnectSubscriptions()} on linked {@link Attribute}s; a
* subscription can be a message sent over the websocket or a HTTP REST API call.
*/
-public class WebsocketAgentProtocol extends AbstractIOClientProtocol<WebsocketAgentProtocol, WebsocketAgent, String, WebsocketIOClient<String>, WebsocketAgent.WebsocketAgentLink> {
+public class WebsocketAgentProtocol extends AbstractIOClientProtocol<WebsocketAgentProtocol, WebsocketAgent, String, WebsocketIOClient<String>, WebsocketAgentLink> {
public static final String PROTOCOL_DISPLAY_NAME = "Websocket Client";
private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, WebsocketAgentProtocol.class);
@@ -117,7 +117,7 @@ public class WebsocketAgentProtocol extends AbstractIOClientProtocol<WebsocketAg
}
@Override
- protected String createWriteMessage(Attribute<?> attribute, WebsocketAgent.WebsocketAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected String createWriteMessage(Attribute<?> attribute, WebsocketAgentLink agentLink, AttributeEvent event, Object processedValue) {
if (attribute.getType().equals(ValueType.EXECUTION_STATUS)) {
boolean isRequestStart = event.getValue()
@@ -181,7 +181,7 @@ public class WebsocketAgentProtocol extends AbstractIOClientProtocol<WebsocketAg
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, WebsocketAgent.WebsocketAgentLink agentLink) {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, WebsocketAgentLink agentLink) {
Optional<WebsocketSubscription[]> subscriptions = agentLink.getWebsocketSubscriptions();
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
@@ -201,7 +201,7 @@ public class WebsocketAgentProtocol extends AbstractIOClientProtocol<WebsocketAg
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, WebsocketAgent.WebsocketAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, WebsocketAgentLink agentLink) {
AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());
protocolMessageConsumers.removeIf((attrRefConsumer) -> attrRefConsumer.key.equals(attributeRef));
attributeConnectedTasks.remove(attributeRef);
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 b1030e143..5cf713fa9 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
@@ -21,43 +21,12 @@ package org.openremote.agent.protocol.zwave;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import javax.persistence.Entity;
-import java.util.Optional;
@Entity
-public class ZWaveAgent extends Agent<ZWaveAgent, ZWaveProtocol, ZWaveAgent.ZWaveAgentLink> {
-
- public static class ZWaveAgentLink extends AgentLink<ZWaveAgentLink> {
-
- protected Integer deviceNodeId;
- protected Integer deviceEndpoint;
- protected String deviceValue;
-
- // For Hydrators
- protected ZWaveAgentLink() {}
-
- public ZWaveAgentLink(String id, Integer deviceNodeId, Integer deviceEndpoint, String deviceValue) {
- super(id);
- this.deviceNodeId = deviceNodeId;
- this.deviceEndpoint = deviceEndpoint;
- this.deviceValue = deviceValue;
- }
-
- public Optional<Integer> getDeviceNodeId() {
- return Optional.ofNullable(deviceNodeId);
- }
-
- public Optional<Integer> getDeviceEndpoint() {
- return Optional.ofNullable(deviceEndpoint);
- }
-
- public Optional<String> getDeviceValue() {
- return Optional.ofNullable(deviceValue);
- }
- }
+public class ZWaveAgent extends Agent<ZWaveAgent, ZWaveProtocol, ZWaveAgentLink> {
public static final AttributeDescriptor<String> ZWAVE_SERIAL_PORT = SERIAL_PORT.withOptional(false);
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgentLink.java
new file mode 100644
index 000000000..11e29ae7f
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveAgentLink.java
@@ -0,0 +1,54 @@
+/*
+ * 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.agent.protocol.zwave;
+
+import org.openremote.model.asset.agent.AgentLink;
+
+import java.util.Optional;
+
+public class ZWaveAgentLink extends AgentLink<ZWaveAgentLink> {
+
+ protected Integer deviceNodeId;
+ protected Integer deviceEndpoint;
+ protected String deviceValue;
+
+ // For Hydrators
+ protected ZWaveAgentLink() {
+ }
+
+ public ZWaveAgentLink(String id, Integer deviceNodeId, Integer deviceEndpoint, String deviceValue) {
+ super(id);
+ this.deviceNodeId = deviceNodeId;
+ this.deviceEndpoint = deviceEndpoint;
+ this.deviceValue = deviceValue;
+ }
+
+ public Optional<Integer> getDeviceNodeId() {
+ return Optional.ofNullable(deviceNodeId);
+ }
+
+ public Optional<Integer> getDeviceEndpoint() {
+ return Optional.ofNullable(deviceEndpoint);
+ }
+
+ public Optional<String> getDeviceValue() {
+ return Optional.ofNullable(deviceValue);
+ }
+}
diff --git a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveNetwork.java b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveNetwork.java
index eb051112d..7a2794b55 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveNetwork.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/zwave/ZWaveNetwork.java
@@ -231,7 +231,7 @@ public class ZWaveNetwork {
int endpoint = channel.getCommandClass() != null ? channel.getCommandClass().getContext().getDestEndPoint() : 0;
String linkValue = channel.getLinkName();
- ZWaveAgent.ZWaveAgentLink agentLink = new ZWaveAgent.ZWaveAgentLink(agentId, nodeId, endpoint, linkValue);
+ ZWaveAgentLink agentLink = new ZWaveAgentLink(agentId, nodeId, endpoint, linkValue);
attribute.addOrReplaceMeta(
new MetaItem<>(AGENT_LINK, agentLink),
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 37f68e84a..03697cfb4 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
@@ -44,7 +44,7 @@ import java.util.logging.Logger;
import static org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty;
-public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgent.ZWaveAgentLink> implements ProtocolAssetDiscovery {
+public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgentLink> implements ProtocolAssetDiscovery {
// Constants ------------------------------------------------------------------------------------
@@ -95,7 +95,7 @@ public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgent.ZWave
}
@Override
- protected synchronized void doLinkAttribute(String assetId, Attribute<?> attribute, ZWaveAgent.ZWaveAgentLink agentLink) {
+ protected synchronized void doLinkAttribute(String assetId, Attribute<?> attribute, ZWaveAgentLink agentLink) {
if (network == null) {
return;
}
@@ -113,7 +113,7 @@ public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgent.ZWave
}
@Override
- protected synchronized void doUnlinkAttribute(String assetId, Attribute<?> attribute, ZWaveAgent.ZWaveAgentLink agentLink) {
+ protected synchronized void doUnlinkAttribute(String assetId, Attribute<?> attribute, ZWaveAgentLink agentLink) {
if (network == null) {
return;
}
@@ -123,7 +123,7 @@ public class ZWaveProtocol extends AbstractProtocol<ZWaveAgent, ZWaveAgent.ZWave
}
@Override
- protected synchronized void doLinkedAttributeWrite(Attribute<?> attribute, ZWaveAgent.ZWaveAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected synchronized void doLinkedAttributeWrite(Attribute<?> attribute, ZWaveAgentLink agentLink, AttributeEvent event, Object processedValue) {
if (network == null) {
return;
}
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 c62e22988..452ed45ce 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceService.java
@@ -44,7 +44,7 @@ import org.openremote.model.rules.TenantRuleset;
import org.openremote.model.security.Tenant;
import org.openremote.model.security.User;
import org.openremote.model.syslog.SyslogEvent;
-import org.openremote.model.util.AssetModelUtil;
+import org.openremote.model.value.Values;
import javax.persistence.*;
import javax.persistence.spi.ClassTransformer;
@@ -288,7 +288,7 @@ public class PersistenceService implements ContainerService {
entityClasses.add("org.openremote.container.util");
// Get asset sub type entities from asset model
- Arrays.stream(AssetModelUtil.getAssetDescriptors(null))
+ Arrays.stream(Values.getAssetDescriptors(null))
.map(AssetDescriptor::getType)
.filter(assetClass -> assetClass.getAnnotation(Entity.class) != null)
.map(Class::getName)
diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentResourceImpl.java b/manager/src/main/java/org/openremote/manager/agent/AgentResourceImpl.java
index 8622682e7..bfbe20a4a 100644
--- a/manager/src/main/java/org/openremote/manager/agent/AgentResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/agent/AgentResourceImpl.java
@@ -31,8 +31,8 @@ import org.openremote.model.asset.agent.AgentDescriptor;
import org.openremote.model.asset.agent.AgentResource;
import org.openremote.model.file.FileInfo;
import org.openremote.model.http.RequestParams;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TextUtil;
+import org.openremote.model.value.Values;
import javax.ws.rs.*;
import java.nio.charset.StandardCharsets;
@@ -85,7 +85,7 @@ public class AgentResourceImpl extends ManagerWebResource implements AgentResour
}
}
- Optional<AgentDescriptor<?, ?, ?>> agentDescriptor = AssetModelUtil.getAgentDescriptor(agentType);
+ Optional<AgentDescriptor<?, ?, ?>> agentDescriptor = Values.getAgentDescriptor(agentType);
if (!agentDescriptor.isPresent()) {
throw new IllegalArgumentException("Agent descriptor not found: agent type =" + agentType);
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 2fa9ef954..35d6dac51 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetModelService.java
@@ -30,10 +30,10 @@ 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.util.AssetModelUtil;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
+import org.openremote.model.value.Values;
// TODO: Implement model client event support
/**
@@ -101,7 +101,7 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return new AssetTypeInfo[0];
}
- return AssetModelUtil.getAssetInfos(parentType);
+ return Values.getAssetInfos(parentType);
}
public AssetTypeInfo getAssetInfo(String parentId, String assetType) {
@@ -111,7 +111,7 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return null;
}
- return AssetModelUtil.getAssetInfo(assetType).orElse(null);
+ return Values.getAssetInfo(assetType).orElse(null);
}
public AssetDescriptor<?>[] getAssetDescriptors(String parentId, String parentType) {
@@ -121,7 +121,7 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return new AssetDescriptor[0];
}
- return AssetModelUtil.getAssetDescriptors(parentType);
+ return Values.getAssetDescriptors(parentType);
}
public ValueDescriptor<?>[] getValueDescriptors(String parentId) {
@@ -131,7 +131,7 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return new ValueDescriptor<?>[0];
}
- return AssetModelUtil.getValueDescriptors();
+ return Values.getValueDescriptors();
}
public MetaItemDescriptor<?>[] getMetaItemDescriptors(String parentId) {
@@ -141,6 +141,6 @@ public class AssetModelService extends RouteBuilder implements ContainerService
return new MetaItemDescriptor<?>[0];
}
- return AssetModelUtil.getMetaItemDescriptors();
+ return Values.getMetaItemDescriptors();
}
}
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 99d678ccb..81b363e4c 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -53,7 +53,6 @@ import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.filter.*;
import org.openremote.model.security.ClientRole;
import org.openremote.model.security.User;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.Pair;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.Values;
@@ -591,7 +590,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
T existingAsset = TextUtil.isNullOrEmpty(asset.getId()) ? null : (T)em.find(Asset.class, asset.getId());
// Do standard JSR-380 validation on the asset (includes custom validation)
- Set<ConstraintViolation<Asset<?>>> validationFailures = AssetModelUtil.validate(asset, Asset.AssetSave.class);
+ Set<ConstraintViolation<Asset<?>>> validationFailures = Values.validate(asset, Asset.AssetSave.class);
if (validationFailures.size() > 0) {
String msg = "Asset merge failed as asset has failed constraint validation: asset=" + asset;
@@ -1591,7 +1590,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected static String[] getResolvedAssetTypes(Class<? extends Asset<?>>[] assetClasses) {
return Arrays.stream(assetClasses)
.flatMap(assetClass ->
- Arrays.stream(AssetModelUtil.getAssetClasses(null)).filter(assetClass::isAssignableFrom))
+ Arrays.stream(Values.getAssetClasses(null)).filter(assetClass::isAssignableFrom))
.map(Class::getSimpleName)
.distinct()
.toArray(String[]::new);
diff --git a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java
index 6e8272a49..ab6fca06f 100644
--- a/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/console/ConsoleResourceImpl.java
@@ -40,16 +40,11 @@ import org.openremote.model.query.filter.ParentPredicate;
import org.openremote.model.query.filter.StringPredicate;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TextUtil;
-import javax.validation.ConstraintViolation;
-import javax.validation.ConstraintViolationException;
import javax.ws.rs.BadRequestException;
-import javax.ws.rs.core.Response;
import java.util.HashMap;
import java.util.Map;
-import java.util.Set;
import static org.openremote.container.concurrent.GlobalLock.withLockReturning;
import static org.openremote.model.value.MetaItemType.*;
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 163ddc0e4..21ce21e09 100644
--- a/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java
+++ b/manager/src/main/java/org/openremote/manager/energy/EnergyOptimisationService.java
@@ -32,7 +32,6 @@ import org.openremote.model.Container;
import org.openremote.model.ContainerService;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetFilter;
import org.openremote.model.asset.impl.*;
import org.openremote.model.attribute.Attribute;
@@ -45,9 +44,9 @@ import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.filter.AttributePredicate;
import org.openremote.model.query.filter.BooleanPredicate;
import org.openremote.model.query.filter.StringPredicate;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.Pair;
import org.openremote.model.value.MetaItemType;
+import org.openremote.model.value.Values;
import java.time.*;
import java.time.format.DateTimeFormatter;
@@ -590,7 +589,7 @@ public class EnergyOptimisationService extends RouteBuilder implements Container
return false;
}
- Class<?> assetClass = AssetModelUtil
+ Class<?> assetClass = Values
.getAssetDescriptor(((GroupAsset)asset).getChildAssetType().orElse(null))
.map(AssetDescriptor::getType)
.orElse(null);
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 7f704f6f4..38932da90 100644
--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java
@@ -28,7 +28,6 @@ import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.LogicGroup;
import org.openremote.model.query.filter.*;
import org.openremote.model.rules.AssetState;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.value.MetaHolder;
import org.openremote.model.value.NameValueHolder;
import org.openremote.model.value.Values;
@@ -86,7 +85,7 @@ public class AssetQueryPredicate implements Predicate<AssetState<?>> {
if (query.types != null && query.types.length > 0) {
if (Arrays.stream(query.types).noneMatch(type ->
type.isAssignableFrom(
- AssetModelUtil.getAssetDescriptor(assetState.getAssetType())
+ Values.getAssetDescriptor(assetState.getAssetType())
.orElse(ThingAsset.DESCRIPTOR).getType()))
) {
return false;
diff --git a/model/build.gradle b/model/build.gradle
index 152cb6a77..f1defe128 100644
--- a/model/build.gradle
+++ b/model/build.gradle
@@ -32,6 +32,7 @@ dependencies {
compile "com.github.victools:jsonschema-generator:$jsonSchemaVersion"
compile "com.github.victools:jsonschema-module-jackson:$jsonSchemaVersion"
+ compile "com.github.victools:jsonschema-module-swagger-2:$jsonSchemaVersion"
compile "com.github.victools:jsonschema-module-javax-validation:$jsonSchemaVersion"
}
diff --git a/model/src/main/java/org/openremote/model/AssetModelProvider.java b/model/src/main/java/org/openremote/model/AssetModelProvider.java
index 3f742761f..5889b9c18 100644
--- a/model/src/main/java/org/openremote/model/AssetModelProvider.java
+++ b/model/src/main/java/org/openremote/model/AssetModelProvider.java
@@ -21,20 +21,20 @@ package org.openremote.model;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemDescriptor;
import org.openremote.model.value.ValueDescriptor;
+import org.openremote.model.value.Values;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
/**
- * Provides model descriptors that are processed by {@link AssetModelUtil}; implementations can be discovered using the
+ * Provides model descriptors that are processed by {@link Values}; implementations can be discovered using the
* standard {@link ServiceLoader} mechanism or can be manually registered by adding an instance to the {@link
- * AssetModelUtil#getModelProviders}.
+ * Values#getModelProviders}.
* <p>
* If {@link #useAutoScan} is true then the {@link org.reflections.Reflections} library is used to find all classes that
* extend {@link Asset} in the same JAR as the {@link AssetModelProvider}, these are then searched for all types of
@@ -62,14 +62,14 @@ public interface AssetModelProvider {
/**
* 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 AssetModelUtil} initialisation.
+ * duplicate conflicts will generate an {@link IllegalStateException} during {@link Values} initialisation.
*/
Map<Class<? extends Asset<?>>, List<AttributeDescriptor<?>>> getAttributeDescriptors();
/**
* Get {@link MetaItemDescriptor}s that should be associated with the specified {@link Asset} type; these are
* combined with any {@link MetaItemDescriptor}s already associated with the given {@link Asset} type. Any duplicate
- * conflicts will generate an {@link IllegalStateException} during {@link AssetModelUtil} initialisation.
+ * conflicts will generate an {@link IllegalStateException} during {@link Values} initialisation.
* <p>
* If {@link #useAutoScan} is true and this is also defined then the results will be combined with those returned by
* scanning.
@@ -79,7 +79,7 @@ public interface AssetModelProvider {
/**
* 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 AssetModelUtil} initialisation. Shouldn't contain
+ * will generate an {@link IllegalStateException} during {@link Values} 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>
diff --git a/model/src/main/java/org/openremote/model/ModelDescriptor.java b/model/src/main/java/org/openremote/model/ModelDescriptor.java
index 539fb2691..d0f38304d 100644
--- a/model/src/main/java/org/openremote/model/ModelDescriptor.java
+++ b/model/src/main/java/org/openremote/model/ModelDescriptor.java
@@ -20,11 +20,6 @@
package org.openremote.model;
import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.util.AssetModelUtil;
-import org.openremote.model.value.AttributeDescriptor;
-import org.openremote.model.value.MetaItemDescriptor;
-import org.openremote.model.value.ValueDescriptor;
import java.lang.annotation.*;
diff --git a/model/src/main/java/org/openremote/model/StandardModelProvider.java b/model/src/main/java/org/openremote/model/StandardModelProvider.java
index f0329cb2c..6daec5f76 100644
--- a/model/src/main/java/org/openremote/model/StandardModelProvider.java
+++ b/model/src/main/java/org/openremote/model/StandardModelProvider.java
@@ -21,9 +21,7 @@ package org.openremote.model;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.asset.impl.GroupAsset;
import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.*;
@@ -72,7 +70,7 @@ public class StandardModelProvider implements AssetModelProvider {
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(AssetModelUtil.getAssetClasses(null)).map(Class::getSimpleName).toArray()));
+ constraints.add(new ValueConstraint.AllowedValues(Arrays.stream(Values.getAssetClasses(null)).map(Class::getSimpleName).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 e553cce4a..cb471dc4b 100644
--- a/model/src/main/java/org/openremote/model/asset/Asset.java
+++ b/model/src/main/java/org/openremote/model/asset/Asset.java
@@ -33,7 +33,6 @@ import org.openremote.model.attribute.AttributeMap;
import org.openremote.model.attribute.MetaMap;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.jackson.AssetTypeIdResolver;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.validation.AssetValid;
import org.openremote.model.value.AttributeDescriptor;
@@ -325,7 +324,7 @@ public abstract class Asset<T extends Asset<?>> implements IdentifiableEntity<T>
setName(name);
// Initialise required attributes
- AssetModelUtil.initialiseAssetAttributes(this);
+ Values.initialiseAssetAttributes(this);
}
public String getId() {
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 19449b0d5..cbef7f825 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetDescriptor.java
@@ -25,15 +25,14 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
-import com.fasterxml.jackson.core.JsonToken;
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 org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.NameHolder;
+import org.openremote.model.value.Values;
import java.io.IOException;
@@ -71,7 +70,7 @@ public class AssetDescriptor<T extends Asset<?>> implements NameHolder {
} else if (node.isObject()) {
name = node.get("name").asText();
}
- return AssetModelUtil.getAssetDescriptor(name).orElse(null);
+ return Values.getAssetDescriptor(name).orElse(null);
}
}
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 6b80a212d..4f5158b4d 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
@@ -25,10 +25,10 @@ import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.auth.OAuthGrant;
import org.openremote.model.auth.UsernamePassword;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.MetaItemType;
import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
import java.util.Arrays;
import java.util.Optional;
@@ -261,12 +261,12 @@ public abstract class Agent<T extends Agent<T, U, V>, U extends Protocol<T>, V e
// This is an event for an agent so is it for an attribute that has a descriptor which is defined in an agent class
// and it's not the status attribute (or we'll end up in a loop)
return !attributeName.equals(Agent.STATUS.getName())
- && AssetModelUtil.getAssetInfo(getType())
+ && Values.getAssetInfo(getType())
.map(info ->
Arrays.stream(info.getAttributeDescriptors())
.anyMatch(ad -> ad.getName().equals(attributeName)))
.orElse(false)
- && AssetModelUtil.getAssetInfo(UnknownAsset.class)
+ && Values.getAssetInfo(UnknownAsset.class)
.map(typeInfo -> Arrays.stream(typeInfo.getAttributeDescriptors()).noneMatch(ad -> ad.getName().equals(attributeName)))
.orElse(false);
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/AgentDescriptor.java b/model/src/main/java/org/openremote/model/asset/agent/AgentDescriptor.java
index f02ebbbda..00417de4e 100644
--- a/model/src/main/java/org/openremote/model/asset/agent/AgentDescriptor.java
+++ b/model/src/main/java/org/openremote/model/asset/agent/AgentDescriptor.java
@@ -30,7 +30,7 @@ import org.openremote.model.asset.AssetDescriptor;
import org.openremote.model.protocol.ProtocolAssetDiscovery;
import org.openremote.model.protocol.ProtocolAssetImport;
import org.openremote.model.protocol.ProtocolInstanceDiscovery;
-import org.openremote.model.util.AssetModelUtil;
+import org.openremote.model.value.Values;
/**
* Special type of {@link AssetDescriptor} that describes an agent {@link Asset}.
@@ -85,8 +85,8 @@ public class AgentDescriptor<T extends Agent<T, U, V>, U extends Protocol<T>, V
}
@JsonProperty
- public JsonNode getAgentLinkSchema() {
- return AssetModelUtil.getSchema(agentLinkClass);
+ public String getAgentLinkType() {
+ return agentLinkClass.getSimpleName();
}
public Class<U> getProtocolClass() {
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 b8f4b3747..7ea7197d8 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
@@ -21,19 +21,14 @@ package org.openremote.model.asset.agent;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.fasterxml.jackson.annotation.JsonTypeName;
-import com.fasterxml.jackson.databind.DatabindContext;
-import com.fasterxml.jackson.databind.JavaType;
-import com.fasterxml.jackson.databind.annotation.JsonTypeIdResolver;
-import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
+import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.node.ObjectNode;
+import io.swagger.v3.oas.annotations.media.Schema;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.query.filter.ValuePredicate;
-import org.openremote.model.util.AssetModelUtil;
-import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.ValueFilter;
+import org.openremote.model.value.Values;
-import java.io.IOException;
import java.io.Serializable;
import java.util.Optional;
@@ -42,57 +37,10 @@ import java.util.Optional;
* own concrete implementation of this class with fields describing each configuration item and standard JSR-380
* annotations should be used to provide validation logic.
*/
-@JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.CUSTOM, defaultImpl = AgentLink.Default.class)
-@JsonTypeIdResolver(AgentLink.AgentLinkTypeIdResolver.class)
+@JsonTypeInfo(property = "type", use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, defaultImpl = DefaultAgentLink.class)
public abstract class AgentLink<T extends AgentLink<?>> implements Serializable {
- /**
- * Resolves agent link type as agent type strings using {@link org.openremote.model.util.AssetModelUtil}
- */
- @TsIgnore
- public static class AgentLinkTypeIdResolver extends TypeIdResolverBase {
- @Override
- public String idFromValue(Object value) {
- if (value == null) {
- return null;
- }
- if (!(value instanceof AgentLink)) {
- throw new IllegalArgumentException("Type must be an agent link type");
- }
- return value.getClass().getSimpleName().replaceAll("\\$", ".");
- }
-
- @Override
- public String idFromValueAndType(Object value, Class<?> suggestedType) {
- return idFromValue(value);
- }
-
- @Override
- public JsonTypeInfo.Id getMechanism() {
- return JsonTypeInfo.Id.CUSTOM;
- }
-
- @Override
- public JavaType typeFromId(DatabindContext context, String id) throws IOException {
- Class<? extends AgentLink<?>> agentLinkClass = AssetModelUtil.getAgentLinkClass(id)
- .orElse(AgentLink.Default.class);
- return context.constructType(agentLinkClass);
- }
- }
-
- /**
- * Does nothing other than hide the generic type parameter which causes problems with inference from class references
- */
- @JsonTypeName("Default") // Needed for typescript generator - doesn't seem to use type id resolver
- public static class Default extends AgentLink<Default> {
-
- protected Default() {}
-
- public Default(String id) {
- super(id);
- }
- }
-
+ @Schema(format = "or-agent-id")
protected String id;
protected ValueFilter[] valueFilters;
protected ObjectNode valueConverter;
@@ -101,6 +49,11 @@ public abstract class AgentLink<T extends AgentLink<?>> implements Serializable
protected ValuePredicate messageMatchPredicate;
protected ValueFilter[] messageMatchFilters;
+ @JsonSerialize
+ protected String getType() {
+ return getClass().getSimpleName();
+ }
+
// For Hydrators
protected AgentLink() {}
@@ -189,7 +142,7 @@ public abstract class AgentLink<T extends AgentLink<?>> implements Serializable
public static <T> T getOrThrowAgentLinkProperty(Optional<T> value, String name) {
return value.orElseThrow(() -> {
String msg = "Required agent link property is undefined: " + name;
- AssetModelUtil.LOG.warning(msg);
+ Values.LOG.warning(msg);
return new IllegalStateException("msg");
});
}
diff --git a/model/src/main/java/org/openremote/model/asset/agent/DefaultAgentLink.java b/model/src/main/java/org/openremote/model/asset/agent/DefaultAgentLink.java
new file mode 100644
index 000000000..6e0b78408
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/asset/agent/DefaultAgentLink.java
@@ -0,0 +1,36 @@
+/*
+ * 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.asset.agent;
+
+import org.openremote.model.util.TsIgnore;
+
+/**
+ * Does nothing other than hide the generic type parameter which causes problems with inference from class references
+ */
+@TsIgnore
+public class DefaultAgentLink extends AgentLink<DefaultAgentLink> {
+
+ protected DefaultAgentLink() {
+ }
+
+ public DefaultAgentLink(String id) {
+ super(id);
+ }
+}
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 05d486c57..063884dc3 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -31,7 +31,6 @@ import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.util.TokenBuffer;
import org.openremote.model.asset.Asset;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.value.*;
import javax.validation.Valid;
@@ -91,7 +90,7 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
}
// Get inner attribute type or fallback to primitive/JSON type
- Optional<ValueDescriptor<?>> valueDescriptor = AssetModelUtil.getValueDescriptor(attributeValueType);
+ Optional<ValueDescriptor<?>> valueDescriptor = Values.getValueDescriptor(attributeValueType);
Attribute attribute = new Attribute<>();
while (jp3.nextToken() != JsonToken.END_OBJECT) {
@@ -127,7 +126,7 @@ public class Attribute<T> extends AbstractNameValueHolder<T> implements MetaHold
return ValueDescriptor.UNKNOWN;
}
Object value = attribute.value;
- return AssetModelUtil.getValueDescriptorForValue(value);
+ return Values.getValueDescriptorForValue(value);
});
return (Attribute<?>) attribute;
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValidationFailure.java b/model/src/main/java/org/openremote/model/attribute/AttributeValidationFailure.java
deleted file mode 100644
index 2f7234741..000000000
--- a/model/src/main/java/org/openremote/model/attribute/AttributeValidationFailure.java
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.attribute;
-
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.fasterxml.jackson.annotation.JsonTypeName;
-import org.openremote.model.util.TsIgnore;
-
-import java.util.Optional;
-
-/**
- * Encapsulates a validation failure for a specific {@link Attribute}; constants should be used for {@link ReasonString}
- * values to allow human readable strings to be mapped for I18N. The parameter can be used to convey more specific
- * failure information (is dependent on I18N implementation),
- */
-@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
-@JsonTypeName("attribute")
-@Deprecated
-// TODO: Replace with JSR-380 constraint violations
-public class AttributeValidationFailure {
-
- public interface ReasonString {
- @JsonProperty
- String name();
- }
-
- public enum Reason implements ReasonString {
- ATTRIBUTE_MISSING,
- ATTRIBUTE_VALUE_MISSING,
- ATTRIBUTE_VALUE_TYPE_MISMATCH
- }
-
- protected String parameter;
- protected ReasonString reason;
- protected String attribute;
-
- public AttributeValidationFailure(String attribute, ReasonString reason) {
- this(attribute, reason, null);
- }
-
- public AttributeValidationFailure(String attribute, ReasonString reason, String parameter) {
- this.attribute = attribute;
- this.reason = reason;
- this.parameter = parameter;
- }
-
- public String getAttribute() {
- return attribute;
- }
-
- public ReasonString getReason() {
- return reason;
- }
-
- public Optional<String> getParameter() {
- return Optional.ofNullable(parameter);
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "attributeName=" + attribute +
- ", reason=" + reason +
- ", param='" + parameter + '\'' +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java b/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java
deleted file mode 100644
index 7ddbf9146..000000000
--- a/model/src/main/java/org/openremote/model/attribute/AttributeValidationResult.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.model.attribute;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.*;
-
-/**
- * Represents the validation result of an attribute.
- * <p>
- * {@link #getAttributeFailures} returns any attribute validation failures along with an optional failure message
- * parameter for each failure.
- * <p>
- * {@link #getMetaFailures()} returns a map of meta item validation failures along with optional failure message
- * parameter for each failure; the key represents the meta item index that has failed.
- */
-@Deprecated
-public class AttributeValidationResult {
-
- @JsonProperty
- protected String attributeName;
- @JsonProperty
- protected List<AttributeValidationFailure> attributeFailures;
- @JsonProperty
- protected Map<Integer, List<AttributeValidationFailure>> metaFailures;
-
- public AttributeValidationResult(String attributeName) {
- this.attributeName = attributeName;
- }
-
- @JsonCreator
- public AttributeValidationResult(@JsonProperty("attributeName") String attributeName,
- @JsonProperty("attributeFailures") List<AttributeValidationFailure> attributeFailures,
- @JsonProperty("metaFailures") Map<Integer, List<AttributeValidationFailure>> metaFailures) {
- this.attributeName = attributeName;
- this.attributeFailures = attributeFailures;
- this.metaFailures = metaFailures;
- }
-
- public void addAttributeFailure(AttributeValidationFailure attributeFailure) {
- if (attributeFailures == null) {
- attributeFailures = new ArrayList<>();
- }
-
- attributeFailures.add(attributeFailure);
- }
-
- public void addMetaFailure(AttributeValidationFailure failure) {
- addMetaFailure(-1, failure);
- }
-
- public void addMetaFailure(int metaItemindex, AttributeValidationFailure failure) {
- if (metaFailures == null) {
- metaFailures = new HashMap<>();
- }
- if (!metaFailures.containsKey(metaItemindex)) {
- metaFailures.put(metaItemindex, new ArrayList<>());
- }
- metaFailures.get(metaItemindex).add(failure);
- }
-
- public String getAttributeName() {
- return attributeName;
- }
-
- public List<AttributeValidationFailure> getAttributeFailures() {
- return attributeFailures;
- }
-
- public Map<Integer, List<AttributeValidationFailure>> getMetaFailures() {
- return metaFailures;
- }
-
- public boolean hasAttributeFailures() {
- return attributeFailures != null && !attributeFailures.isEmpty();
- }
-
- public boolean hasMetaFailures() {
- return metaFailures != null && !metaFailures.isEmpty();
- }
-
- public boolean isValid() {
- return !hasAttributeFailures() && !hasMetaFailures();
- }
-}
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 63fdfe16b..e74ddf398 100644
--- a/model/src/main/java/org/openremote/model/attribute/MetaMap.java
+++ b/model/src/main/java/org/openremote/model/attribute/MetaMap.java
@@ -25,7 +25,6 @@ import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.value.*;
import java.io.IOException;
@@ -62,7 +61,7 @@ public class MetaMap extends NamedMap<MetaItem<?>> {
// 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 = AssetModelUtil.getMetaItemDescriptor(metaItemName)
+ Optional<ValueDescriptor<?>> valueDescriptor = Values.getMetaItemDescriptor(metaItemName)
.map(MetaItemDescriptor::getType);
Class valueType = valueDescriptor.map(ValueDescriptor::getType).orElseGet(() -> (Class) Object.class);
@@ -74,7 +73,7 @@ public class MetaMap extends NamedMap<MetaItem<?>> {
return ValueDescriptor.UNKNOWN;
}
Object value = metaItem.getValue().orElse(null);
- return AssetModelUtil.getValueDescriptorForValue(value);
+ return Values.getValueDescriptorForValue(value);
}));
list.add(metaItem);
diff --git a/model/src/main/java/org/openremote/model/attribute/MetaValidationFailure.java b/model/src/main/java/org/openremote/model/attribute/MetaValidationFailure.java
deleted file mode 100644
index 97889d969..000000000
--- a/model/src/main/java/org/openremote/model/attribute/MetaValidationFailure.java
+++ /dev/null
@@ -1,56 +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.model.attribute;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import com.fasterxml.jackson.annotation.JsonTypeName;
-import org.openremote.model.util.TsIgnore;
-
-@Deprecated
-public class MetaValidationFailure extends AttributeValidationFailure {
-
- protected String metaItem;
-
- public MetaValidationFailure(String attributeName, String metaItem, ReasonString reason) {
- super(attributeName, reason);
- this.metaItem = metaItem;
- }
-
- @JsonCreator
- public MetaValidationFailure(@JsonProperty("attribute") String attribute, @JsonProperty("metaItem") String metaItem, @JsonProperty("reason") ReasonString reason, @JsonProperty("parameter") String parameter) {
- super(attribute, reason, parameter);
- this.metaItem = metaItem;
- }
-
- public String getMetaItem() {
- return metaItem;
- }
-
- @Override
- public String toString() {
- return MetaValidationFailure.class.getSimpleName() + "{" +
- "metaItem='" + metaItem + '\'' +
- ", parameter='" + parameter + '\'' +
- ", reason=" + reason +
- ", attribute='" + attribute + '\'' +
- '}';
- }
-}
diff --git a/model/src/main/java/org/openremote/model/calendar/CalendarEvent.java b/model/src/main/java/org/openremote/model/calendar/CalendarEvent.java
index 48a817ad2..3517b7d40 100644
--- a/model/src/main/java/org/openremote/model/calendar/CalendarEvent.java
+++ b/model/src/main/java/org/openremote/model/calendar/CalendarEvent.java
@@ -20,22 +20,17 @@
package org.openremote.model.calendar;
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 com.fasterxml.jackson.databind.util.StdConverter;
import net.fortuna.ical4j.model.DateList;
import net.fortuna.ical4j.model.Recur;
import org.openremote.model.asset.Asset;
-import org.openremote.model.util.AssetModelUtil;
import org.openremote.model.util.Pair;
import java.io.Serializable;
-import java.text.ParseException;
import java.time.temporal.ChronoUnit;
import java.util.Date;
-import java.util.logging.Level;
/**
* Represents an event that occurs at a point in time with a {@link #start}, {#link #end} and optional
diff --git a/model/src/main/java/org/openremote/model/jackson/AssetTypeIdResolver.java b/model/src/main/java/org/openremote/model/jackson/AssetTypeIdResolver.java
index fa5b3bc92..0e466764a 100644
--- a/model/src/main/java/org/openremote/model/jackson/AssetTypeIdResolver.java
+++ b/model/src/main/java/org/openremote/model/jackson/AssetTypeIdResolver.java
@@ -25,9 +25,8 @@ import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.jsontype.impl.TypeIdResolverBase;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.asset.impl.ThingAsset;
import org.openremote.model.asset.impl.UnknownAsset;
-import org.openremote.model.util.AssetModelUtil;
+import org.openremote.model.value.Values;
import java.io.IOException;
@@ -60,7 +59,7 @@ public class AssetTypeIdResolver extends TypeIdResolverBase {
@Override
public JavaType typeFromId(DatabindContext context, String id) throws IOException {
- AssetDescriptor<?> descriptor = AssetModelUtil.getAssetDescriptor(id).orElse(UnknownAsset.DESCRIPTOR);
+ AssetDescriptor<?> descriptor = Values.getAssetDescriptor(id).orElse(UnknownAsset.DESCRIPTOR);
return context.constructType(descriptor.getType());
}
}
diff --git a/model/src/main/java/org/openremote/model/query/AssetQuery.java b/model/src/main/java/org/openremote/model/query/AssetQuery.java
index a7948a155..6261574d9 100644
--- a/model/src/main/java/org/openremote/model/query/AssetQuery.java
+++ b/model/src/main/java/org/openremote/model/query/AssetQuery.java
@@ -24,8 +24,9 @@ import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.util.StdConverter;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.AssetDescriptor;
+import org.openremote.model.asset.agent.Agent;
import org.openremote.model.query.filter.*;
-import org.openremote.model.util.AssetModelUtil;
+import org.openremote.model.value.Values;
import java.util.Arrays;
import java.util.Comparator;
@@ -237,9 +238,17 @@ public class AssetQuery {
public static class StringToAssetClassConverter extends StdConverter<String, Class<? extends Asset<?>>> {
+ @SuppressWarnings("unchecked")
@Override
public Class<? extends Asset<?>> convert(String value) {
- return AssetModelUtil.getAssetDescriptor(value).map(AssetDescriptor::getType).orElse(null);
+ if (Agent.class.getSimpleName().equals(value)) {
+ return (Class<? extends Asset<?>>)(Class<?>) Agent.class;
+ }
+ if (Asset.class.getSimpleName().equals(value)) {
+ return (Class<? extends Asset<?>>)(Class<?>) Asset.class;
+ }
+
+ return Values.getAssetDescriptor(value).map(AssetDescriptor::getType).orElse(null);
}
}
diff --git a/model/src/main/java/org/openremote/model/util/AssetModelUtil.java b/model/src/main/java/org/openremote/model/util/AssetModelUtil.java
deleted file mode 100644
index 031a7a2fd..000000000
--- a/model/src/main/java/org/openremote/model/util/AssetModelUtil.java
+++ /dev/null
@@ -1,664 +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.model.util;
-
-import com.fasterxml.jackson.databind.JsonNode;
-import com.github.victools.jsonschema.generator.*;
-import com.github.victools.jsonschema.module.jackson.JacksonModule;
-import com.github.victools.jsonschema.module.jackson.JacksonOption;
-import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule;
-import org.openremote.model.AssetModelProvider;
-import org.openremote.model.ModelDescriptor;
-import org.openremote.model.ModelDescriptors;
-import org.openremote.model.StandardModelProvider;
-import org.openremote.model.asset.Asset;
-import org.openremote.model.asset.AssetDescriptor;
-import org.openremote.model.asset.AssetTypeInfo;
-import org.openremote.model.asset.agent.Agent;
-import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
-import org.openremote.model.attribute.Attribute;
-import org.openremote.model.syslog.SyslogCategory;
-import org.openremote.model.value.*;
-import org.reflections.Reflections;
-import org.reflections.scanners.SubTypesScanner;
-import org.reflections.util.ClasspathHelper;
-import org.reflections.util.ConfigurationBuilder;
-
-import javax.persistence.Entity;
-import javax.validation.ConstraintViolation;
-import javax.validation.Validation;
-import javax.validation.Validator;
-import javax.validation.constraints.NotNull;
-import java.io.Serializable;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-import java.util.stream.Collectors;
-
-import static java.lang.reflect.Modifier.isPublic;
-import static java.lang.reflect.Modifier.isStatic;
-import static org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES;
-
-/**
- * Utility class for retrieving asset model descriptors
- * <p>
- * Custom descriptors can be added by simply adding new {@link Asset}/{@link Agent} sub types and following the discovery
- * rules described in {@link StandardModelProvider}; alternatively a custom {@link AssetModelProvider} implementation
- * can be created and discovered with the {@link ServiceLoader} or manually added to this class via
- * {@link #getModelProviders()} collection.
- */
-@SuppressWarnings("unchecked")
-@TsIgnore
-public final class AssetModelUtil {
-
- /**
- * Copied from: https://puredanger.github.io/tech.puredanger.com/2006/11/29/writing-a-class-hierarchy-comparator/
- */
- protected static class ClassHierarchyComparator implements Comparator<Class<?>> {
-
- public int compare(Class<?> c1, Class<?> c2) {
- if(c1 == null) {
- if(c2 == null) {
- return 0;
- } else {
- // Sort nulls first
- return 1;
- }
- } else if(c2 == null) {
- // Sort nulls first
- return -1;
- }
-
- // At this point, we know that c1 and c2 are not null
- if(c1.equals(c2)) {
- return 0;
- }
-
- // At this point, c1 and c2 are not null and not equal, here we
- // compare them to see which is "higher" in the class hierarchy
- boolean c1Lower = c2.isAssignableFrom(c1);
- boolean c2Lower = c1.isAssignableFrom(c2);
-
- if(c1Lower && !c2Lower) {
- return 1;
- } else if(c2Lower && !c1Lower) {
- return -1;
- }
-
- // Doesn't matter, sort consistently on classname
- return c1.getName().compareTo(c2.getName());
- }
- }
-
- public static Logger LOG = SyslogCategory.getLogger(MODEL_AND_VALUES, AssetModelUtil.class);
- // Preload the Standard model provider so it takes priority over others
- protected static final 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;
- protected static Validator validator;
- protected static SchemaGenerator generator;
-
- static {
- // Find all service loader registered asset model providers
- ServiceLoader.load(AssetModelProvider.class).forEach(assetModelProviders::add);
- }
-
- private AssetModelUtil() {
- }
-
- public static AssetTypeInfo[] getAssetInfos(String parentType) {
- if (assetTypeMap == null) {
- initialise();
- }
- return assetInfoMap.values().toArray(new AssetTypeInfo[0]);
- }
-
- public static Class<? extends Asset<?>>[] getAssetClasses(String parentType) {
- if (assetTypeMap == null) {
- initialise();
- }
- return assetTypeMap.values().toArray(new Class[0]);
- }
-
- public static Optional<AssetTypeInfo> getAssetInfo(Class<? extends Asset<?>> assetType) {
- if (assetTypeMap == null) {
- initialise();
- }
- return Optional.ofNullable(assetInfoMap.get(assetType));
- }
-
- public static Optional<AssetTypeInfo> getAssetInfo(String assetType) {
- if (assetTypeMap == null) {
- initialise();
- }
- Class<? extends Asset<?>> assetClass = assetTypeMap.get(assetType);
- return Optional.ofNullable(assetClass != null ? assetInfoMap.get(assetClass) : null);
- }
-
- // TODO: Implement ability to restrict which asset types are allowed to be added to a given parent type
- public static AssetDescriptor<?>[] getAssetDescriptors(String parentType) {
- if (assetTypeMap == null) {
- initialise();
- }
- return Arrays.stream(getAssetInfos(parentType)).map(AssetTypeInfo::getAssetDescriptor).toArray(AssetDescriptor[]::new);
- }
-
- public static <T extends Asset<?>> Optional<AssetDescriptor<T>> getAssetDescriptor(Class<T> assetType) {
- if (assetTypeMap == null) {
- initialise();
- }
-
- return getAssetInfo(assetType).map(assetInfo -> (AssetDescriptor<T>)assetInfo.getAssetDescriptor());
- }
-
- public static Optional<AssetDescriptor<?>> getAssetDescriptor(String assetType) {
- if (assetTypeMap == null) {
- initialise();
- }
-
- return getAssetInfo(assetType).map(AssetTypeInfo::getAssetDescriptor);
- }
-
- public static <T extends Agent<T, ?, ?>> Optional<AgentDescriptor<T, ?, ?>> getAgentDescriptor(Class<T> agentType) {
- return getAssetDescriptor(agentType)
- .map(assetDescriptor -> assetDescriptor instanceof AgentDescriptor ? (AgentDescriptor<T, ?, ?>)assetDescriptor : null);
- }
-
- public static Optional<AgentDescriptor<?, ?, ?>> getAgentDescriptor(String agentType) {
- return getAssetDescriptor(agentType)
- .map(assetDescriptor -> assetDescriptor instanceof AgentDescriptor ? (AgentDescriptor<?, ?, ?>)assetDescriptor : null);
- }
-
- /**
- * Get {@link AgentLink} class by its' simple class name
- */
- public static Optional<Class <? extends AgentLink<?>>> getAgentLinkClass(String agentLinkType) {
- if (assetTypeMap == null) {
- initialise();
- }
-
- return Optional.ofNullable(agentLinkMap.get(agentLinkType));
- }
-
- public static MetaItemDescriptor<?>[] getMetaItemDescriptors() {
- if (assetTypeMap == null) {
- initialise();
- }
- return metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]);
- }
-
- public static Optional<MetaItemDescriptor<?>[]> getMetaItemDescriptors(Class<? extends Asset<?>> assetType) {
- return getAssetInfo(assetType).map(AssetTypeInfo::getMetaItemDescriptors);
- }
-
- public static Optional<MetaItemDescriptor<?>[]> getMetaItemDescriptors(String assetType) {
- return getAssetInfo(assetType).map(AssetTypeInfo::getMetaItemDescriptors);
- }
-
- public static Optional<MetaItemDescriptor<?>> getMetaItemDescriptor(String name) {
- if (TextUtil.isNullOrEmpty(name)) return Optional.empty();
- if (assetTypeMap == null) {
- initialise();
- }
- return metaItemDescriptors.stream().filter(mid -> mid.getName().equals(name)).findFirst();
- }
-
- public static ValueDescriptor<?>[] getValueDescriptors() {
- if (assetTypeMap == null) {
- initialise();
- }
- return valueDescriptors.toArray(new ValueDescriptor<?>[0]);
- }
-
- public static Optional<ValueDescriptor<?>[]> getValueDescriptors(Class<? extends Asset<?>> assetType) {
- return getAssetInfo(assetType).map(AssetTypeInfo::getValueDescriptors);
- }
-
- public static Optional<ValueDescriptor<?>[]> getValueDescriptors(String assetType) {
- return getAssetInfo(assetType).map(AssetTypeInfo::getValueDescriptors);
- }
-
- public static Optional<ValueDescriptor<?>> getValueDescriptor(String name) {
- if (TextUtil.isNullOrEmpty(name)) return Optional.empty();
- if (assetTypeMap == null) {
- initialise();
- }
-
- int arrayDimensions = 0;
-
- while(name.endsWith("[]")) {
- name = name.substring(0, name.length() - 2);
- arrayDimensions++;
- }
-
- String finalName = name;
- int finalArrayDimensions = arrayDimensions;
- return valueDescriptors.stream().filter(vd -> vd.getName().equals(finalName)).findFirst().map(vd -> {
- int dims = finalArrayDimensions;
- while(dims > 0) {
- vd = vd.asArray();
- dims--;
- }
- return vd;
- });
- }
-
- public static ValueDescriptor<?> getValueDescriptorForValue(Object value) {
- if (value == null) {
- return ValueDescriptor.UNKNOWN;
- }
-
- Class<?> valueClass = value.getClass();
- boolean isArray = valueClass.isArray();
- valueClass = isArray ? valueClass.getComponentType() : valueClass;
- ValueDescriptor<?> valueDescriptor = ValueDescriptor.UNKNOWN;
-
- if (valueClass == Boolean.class) valueDescriptor = ValueType.BOOLEAN;
- else if (valueClass == String.class) valueDescriptor = ValueType.TEXT;
- else if (valueClass == Integer.class) valueDescriptor = ValueType.INTEGER;
- else if (valueClass == Long.class) valueDescriptor = ValueType.LONG;
- else if (valueClass == Double.class || valueClass == Float.class) valueDescriptor = ValueType.NUMBER;
- 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)) {
- Object firstElem = Values.findFirstNonNullEntry((Map<?,?>)value);
-
- if (firstElem == null) valueDescriptor = ValueType.JSON_OBJECT;
- else {
- boolean elemIsArray = firstElem.getClass().isArray();
- Class<?> elemClass = elemIsArray ? firstElem.getClass() : firstElem.getClass().getComponentType();
- if (elemIsArray) {
- valueDescriptor = elemClass == String.class ? ValueType.MULTIVALUED_TEXT_MAP : ValueType.JSON_OBJECT;
- } else {
- if (elemClass == String.class)
- valueDescriptor = ValueType.TEXT_MAP;
- else if (elemClass == Double.class || elemClass == Float.class)
- valueDescriptor = ValueType.NUMBER_MAP;
- else if (elemClass == Integer.class)
- valueDescriptor = ValueType.TEXT_MAP;
- else if (elemClass == Boolean.class)
- valueDescriptor = ValueType.BOOLEAN_MAP;
- }
- }
- }
-
- return isArray ? valueDescriptor.asArray() : valueDescriptor;
- }
-
- public static void refresh() {
- assetInfoMap = null;
- assetTypeMap = null;
- agentLinkMap = null;
- metaItemDescriptors = null;
- valueDescriptors = null;
- }
-
- public static List<AssetModelProvider> getModelProviders() {
- return assetModelProviders;
- }
-
- protected static void initialise() {
- try {
- initialiseOrThrow();
- } catch (IllegalStateException e) {
- LOG.log(Level.SEVERE, "Failed to initialise the asset model", e);
- throw e;
- }
- }
-
- /**
- * 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 {@link AssetModelUtil} is un-usable
- */
- public static void initialiseOrThrow() throws IllegalStateException {
-
- assetInfoMap = new HashMap<>();
- assetTypeMap = new HashMap<>();
- agentLinkMap = new HashMap<>();
- metaItemDescriptors = new ArrayList<>();
- valueDescriptors = new ArrayList<>();
-
- LOG.info("Initialising asset model...");
- Map<Class<? extends Asset<?>>, List<NameHolder>> assetDescriptorProviders = new TreeMap<>(new ClassHierarchyComparator());
- //noinspection RedundantCast
- assetDescriptorProviders.put((Class<? extends Asset<?>>)(Class)Asset.class, new ArrayList<>(getDescriptorFields(Asset.class)));
-
- getModelProviders().forEach(assetModelProvider -> {
- LOG.fine("Processing asset model provider: " + assetModelProvider.getClass().getSimpleName());
- LOG.fine("Auto scan = " + assetModelProvider.useAutoScan());
-
- if (assetModelProvider.useAutoScan()) {
-
- Set<Class<? extends Asset<?>>> assetClasses = getAssetClasses(assetModelProvider);
- LOG.fine("Found " + assetClasses.size() + " asset class(es)");
-
- assetClasses.forEach(assetClass ->
- assetDescriptorProviders.computeIfAbsent(assetClass, aClass ->
- new ArrayList<>(getDescriptorFields(aClass))));
-
- 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) -> {
- if (list == null) {
- list = new ArrayList<>();
- }
-
- list.addAll(getDescriptorFields(modelDescriptor.provider()));
- return list;
- });
- }
- }
- }
-
- if (assetModelProvider.getAssetDescriptors() != null) {
- for (AssetDescriptor<?> assetDescriptor : assetModelProvider.getAssetDescriptors()) {
- Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
-
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
- if (list == null) {
- list = new ArrayList<>();
- }
-
- list.add(assetDescriptor);
- return list;
- });
- }
- }
-
- if (assetModelProvider.getAttributeDescriptors() != null) {
- assetModelProvider.getAttributeDescriptors().forEach((assetClass, attributeDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
- if (list == null) {
- list = new ArrayList<>();
- }
-
- list.addAll(attributeDescriptors);
- return list;
- }));
- }
-
- if (assetModelProvider.getMetaItemDescriptors() != null) {
- assetModelProvider.getMetaItemDescriptors().forEach((assetClass, metaDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
- if (list == null) {
- list = new ArrayList<>();
- }
-
- list.addAll(metaDescriptors);
- return list;
- }));
- }
-
- if (assetModelProvider.getValueDescriptors() != null) {
- assetModelProvider.getValueDescriptors().forEach((assetClass, valueDescriptors) ->
- assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
- if (list == null) {
- list = new ArrayList<>();
- }
-
- list.addAll(valueDescriptors);
- 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) -> {
-
- // 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);
- assetInfoMap.put(assetClass, assetInfo);
- assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
-
- if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor) {
- AgentDescriptor<?,?,?> agentDescriptor = (AgentDescriptor<?,?,?>)assetInfo.getAssetDescriptor();
- agentLinkMap.put(agentDescriptor.getAgentLinkClass().getSimpleName().replaceAll("\\$", "."), 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);
- }
-
- // Call on finished on each provider
- assetModelProviders.forEach(AssetModelProvider::onAssetModelFinished);
- }
-
- /**
- * Validates the supplied object using standard JSR-380 bean validation; therefore any type passed in here must
- * follow the JSR-380 annotation requirements.
- */
- // TODO: Implement validation using javax bean validation JSR-380
- public static <T> Set<ConstraintViolation<T>> validate(@NotNull T obj, Class<?>... groups) {
-
- Validator validator = getValidator();
- return validator.validate(obj, groups);
- }
-
- public static Validator getValidator() {
- if (validator == null) {
- validator = Validation
- .buildDefaultValidatorFactory()
- .getValidator();
- }
-
- return validator;
- }
-
- /**
- * Returns the schema for the specified type
- */
- public static JsonNode getSchema(Class<?> clazz) {
- if (generator == null) {
- JacksonModule module = new JacksonModule(
- JacksonOption.FLATTENED_ENUMS_FROM_JSONVALUE
- );
- JavaxValidationModule validationModule = new JavaxValidationModule();
- SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(Values.JSON, SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON);
- configBuilder.with(module);
-// .with(validationModule);
- SchemaGeneratorConfig config = configBuilder.build();
-
-
- generator = new SchemaGenerator(config);
- }
- return generator.generateSchema(clazz);
- }
-
- public static void initialiseAssetAttributes(Asset<?> asset) throws IllegalStateException {
- AssetTypeInfo assetInfo = AssetModelUtil.getAssetInfo(asset.getType()).orElseThrow(() -> new IllegalStateException("Cannot get asset model info for requested asset type: " + asset.getType()));
- asset.getAttributes().addOrReplace(
- Arrays.stream(assetInfo.getAttributeDescriptors())
- .filter(attributeDescriptor -> !attributeDescriptor.isOptional())
- .map(Attribute::new)
- .collect(Collectors.toList())
- );
- }
-
- protected static boolean isGetter(Method method) {
- if (Modifier.isPublic(method.getModifiers()) &&
- method.getParameterTypes().length == 0) {
- if (method.getName().matches("^get[A-Z].*") &&
- !method.getReturnType().equals(void.class))
- return true;
- if (method.getName().matches("^is[A-Z].*") &&
- method.getReturnType().equals(boolean.class))
- return true;
- }
- return false;
- }
-
- protected static Set<Class<? extends Asset<?>>> getAssetClasses(AssetModelProvider assetModelProvider) {
-
- Set<Class<? extends Asset<?>>> assetClasses;
-
- // Search for concrete asset classes in the same JAR as the provided AssetModelProvider
- Reflections reflections = new Reflections(new ConfigurationBuilder()
- .setUrls(ClasspathHelper.forClass(assetModelProvider.getClass()))
- .setScanners(
- new SubTypesScanner(true)
- ));
-
- LOG.fine("Scanning for Asset classes");
-
- assetClasses = reflections.getSubTypesOf(Asset.class).stream()
- .map(assetClass -> (Class<? extends Asset<?>>)assetClass)
- .filter(assetClass -> assetClass.getAnnotation(ModelIgnore.class) == null)
- .collect(Collectors.toSet());
-
- LOG.fine("Found asset class count = " + assetClasses.size());
-
- return assetClasses;
- }
-
- /**
- * Extract public static field values that are of type {@link AssetDescriptor}, {@link AttributeDescriptor}, {@link MetaItemDescriptor} or {@link ValueDescriptor}.
- */
- protected static List<NameHolder> getDescriptorFields(Class<?> type) {
- return Arrays.stream(type.getDeclaredFields())
- .filter(field ->
- isStatic(field.getModifiers())
- && isPublic(field.getModifiers())
- && (AssetDescriptor.class.isAssignableFrom(field.getType())
- || AttributeDescriptor.class.isAssignableFrom(field.getType())
- || MetaItemDescriptor.class.isAssignableFrom(field.getType())
- || ValueDescriptor.class.isAssignableFrom(field.getType())))
- .map(field -> {
- try {
- return (NameHolder)field.get(null);
- } catch (IllegalAccessException e) {
- String msg = "Failed to extract descriptor fields from class: " + type.getName();
- LOG.log(Level.SEVERE, msg, e);
- throw new IllegalStateException(msg);
- }
- })
- .collect(Collectors.toList());
- }
-
- protected static AssetTypeInfo buildAssetInfo(Class<? extends Asset<?>> assetClass, Map<Class<? extends Asset<?>>, List<NameHolder>> classDescriptorMap) throws IllegalStateException {
-
- Class<?> currentClass = assetClass;
- List<Class<?>> classTree = new ArrayList<>();
-
- while (Asset.class.isAssignableFrom(currentClass)) {
- classTree.add(currentClass);
- currentClass = currentClass.getSuperclass();
- }
-
- // Check asset class has JPA entity annotation for JPA polymorphism
- if (assetClass.getAnnotation(Entity.class) == null) {
- throw new IllegalStateException("Asset class must have @Entity JPA annotation for polymorphic JPA support: " + assetClass);
- }
-
- if (Arrays.stream(assetClass.getDeclaredConstructors()).noneMatch(ctor -> ctor.getParameterCount() == 0)) {
- throw new IllegalStateException("Asset class must have a no args constructor for JPA support: " + assetClass);
- }
-
- // Order from Asset class downwards
- Collections.reverse(classTree);
-
- AtomicReference<AssetDescriptor<?>> assetDescriptor = new AtomicReference<>();
- Set<AttributeDescriptor<?>> attributeDescriptors = new HashSet<>(10);
- List<MetaItemDescriptor<?>> metaItemDescriptors = new ArrayList<>(50);
- List<ValueDescriptor<?>> valueDescriptors = new ArrayList<>(50);
-
- classTree.forEach(aClass -> {
- List<NameHolder> descriptors = classDescriptorMap.get(aClass);
- if (descriptors != null) {
- descriptors.forEach(descriptor -> {
- if (aClass == assetClass && descriptor instanceof AssetDescriptor) {
- if (assetDescriptor.get() != null) {
- throw new IllegalStateException("Duplicate asset descriptor found: asset type=" + assetClass +", descriptor=" + assetDescriptor.get() + ", duplicate descriptor=" + descriptor);
- }
- assetDescriptor.set((AssetDescriptor<?>) descriptor);
- } 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=" + assetClass + ", descriptor=" + existingDescriptor + ", duplicate descriptor=" + descriptor);
- }
- attributeDescriptors.remove(existingDescriptor);
- });
- attributeDescriptors.add((AttributeDescriptor<?>) descriptor);
- } else if (descriptor instanceof MetaItemDescriptor) {
- int index = AssetModelUtil.metaItemDescriptors.indexOf(descriptor);
- if (index >= 0 && AssetModelUtil.metaItemDescriptors.get(index) != descriptor) {
- throw new IllegalStateException("Duplicate meta item descriptor found: asset type=" + assetClass +", descriptor=" + metaItemDescriptors.get(index) + ", duplicate descriptor=" + descriptor);
- }
- metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
- if (!AssetModelUtil.metaItemDescriptors.contains(descriptor)) {
- AssetModelUtil.metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
- }
- } else if (descriptor instanceof ValueDescriptor) {
- ValueDescriptor<?> valueDescriptor = (ValueDescriptor<?>)descriptor;
- // 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 = AssetModelUtil.valueDescriptors.indexOf(descriptor);
- if (index >= 0 && AssetModelUtil.valueDescriptors.get(index).getType() != valueDescriptor.getType()) {
- throw new IllegalStateException("Duplicate value descriptor found: asset type=" + assetClass +", descriptor=" + valueDescriptors.get(index) + ", duplicate descriptor=" + descriptor);
- }
- valueDescriptors.add(valueDescriptor);
- if (!AssetModelUtil.valueDescriptors.contains(descriptor)) {
- AssetModelUtil.valueDescriptors.add((ValueDescriptor<?>) descriptor);
- }
- }
- });
- }
- });
-
- if (assetDescriptor.get() == null || assetDescriptor.get().getType() != assetClass) {
- throw new IllegalStateException("Asset descriptor not found or is not for this asset type: asset type=" + assetClass +", descriptor=" + assetDescriptor.get());
- }
-
- return new AssetTypeInfo(
- assetDescriptor.get(),
- attributeDescriptors.toArray(new AttributeDescriptor<?>[0]),
- metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]),
- valueDescriptors.toArray(new ValueDescriptor<?>[0]));
- }
-}
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 de05a6233..8eda1d349 100644
--- a/model/src/main/java/org/openremote/model/validation/AssetValid.java
+++ b/model/src/main/java/org/openremote/model/validation/AssetValid.java
@@ -22,9 +22,9 @@ 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.AssetModelUtil;
import org.openremote.model.util.TsIgnore;
import org.openremote.model.value.AttributeDescriptor;
+import org.openremote.model.value.Values;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
@@ -78,7 +78,7 @@ public @interface AssetValid {
public boolean isValid(Asset<?> value, ConstraintValidatorContext context) {
String type = value.getType();
- AssetTypeInfo assetModelInfo = AssetModelUtil.getAssetInfo(type).orElse(null);
+ AssetTypeInfo assetModelInfo = Values.getAssetInfo(type).orElse(null);
if (assetModelInfo == null || value.getClass() != assetModelInfo.getAssetDescriptor().getType()) {
context.buildConstraintViolationWithTemplate(ASSET_TYPE_INVALID).addConstraintViolation();
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 4aa17de8a..d406a636c 100644
--- a/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java
+++ b/model/src/main/java/org/openremote/model/value/MetaItemDescriptor.java
@@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.util.StdConverter;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.util.AssetModelUtil;
/**
* Describes a {@link MetaItem} that can be added to an {@link Attribute}; the {@link #getName()} must match the {@link
@@ -54,7 +53,7 @@ public class MetaItemDescriptor<T> extends AbstractNameValueDescriptorHolder<T>
@Override
public MetaItemDescriptor<?> convert(String value) {
- return AssetModelUtil.getMetaItemDescriptor(value).orElse(MetaItemDescriptor.UNKNOWN);
+ return Values.getMetaItemDescriptor(value).orElse(MetaItemDescriptor.UNKNOWN);
}
}
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 0499bf14d..a8f91d66a 100644
--- a/model/src/main/java/org/openremote/model/value/ValueDescriptor.java
+++ b/model/src/main/java/org/openremote/model/value/ValueDescriptor.java
@@ -25,7 +25,6 @@ import com.fasterxml.jackson.databind.util.StdConverter;
import org.openremote.model.asset.Asset;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
-import org.openremote.model.util.AssetModelUtil;
import java.io.Serializable;
import java.math.BigInteger;
@@ -66,7 +65,7 @@ public class ValueDescriptor<T> implements NameHolder, Serializable {
@Override
public ValueDescriptor<?> convert(String value) {
- return AssetModelUtil.getValueDescriptor(value).orElse(ValueDescriptor.UNKNOWN);
+ return Values.getValueDescriptor(value).orElse(ValueDescriptor.UNKNOWN);
}
}
diff --git a/model/src/main/java/org/openremote/model/value/Values.java b/model/src/main/java/org/openremote/model/value/Values.java
index c62c0cfdb..04fee6511 100644
--- a/model/src/main/java/org/openremote/model/value/Values.java
+++ b/model/src/main/java/org/openremote/model/value/Values.java
@@ -22,43 +22,131 @@ import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
+import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.node.*;
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.github.victools.jsonschema.generator.*;
+import com.github.victools.jsonschema.module.jackson.JacksonModule;
+import com.github.victools.jsonschema.module.jackson.JacksonOption;
+import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule;
+import com.github.victools.jsonschema.module.swagger2.Swagger2Module;
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.openremote.model.asset.Asset;
+import org.openremote.model.asset.AssetDescriptor;
+import org.openremote.model.asset.AssetTypeInfo;
+import org.openremote.model.asset.agent.Agent;
+import org.openremote.model.asset.agent.AgentDescriptor;
+import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.attribute.Attribute;
+import org.openremote.model.syslog.SyslogCategory;
+import org.openremote.model.util.ModelIgnore;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.TsIgnore;
-
+import org.reflections.Reflections;
+import org.reflections.scanners.SubTypesScanner;
+import org.reflections.util.ClasspathHelper;
+import org.reflections.util.ConfigurationBuilder;
+
+import javax.persistence.Entity;
+import javax.validation.ConstraintViolation;
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import java.util.stream.IntStream;
+import static java.lang.reflect.Modifier.isPublic;
+import static java.lang.reflect.Modifier.isStatic;
+import static org.openremote.model.syslog.SyslogCategory.MODEL_AND_VALUES;
+
/**
- * Utilities for working with values and JSON
+ * Utilities for working with values/JSON and asset model
+ * <p>
+ * Custom descriptors can be added by simply adding new {@link Asset}/{@link Agent} sub types and following the discovery
+ * rules described in {@link StandardModelProvider}; alternatively a custom {@link AssetModelProvider} implementation
+ * can be created and discovered with the {@link ServiceLoader} or manually added to this class via
+ * {@link Values#getModelProviders()} collection.
*/
@SuppressWarnings({"unchecked", "deprecation"})
@TsIgnore
public class Values {
- private static final Logger LOG = Logger.getLogger(Values.class.getName());
- public static final ObjectMapper JSON;
+ /**
+ * Copied from: https://puredanger.github.io/tech.puredanger.com/2006/11/29/writing-a-class-hierarchy-comparator/
+ */
+ protected static class ClassHierarchyComparator implements Comparator<Class<?>> {
+
+ public int compare(Class<?> c1, Class<?> c2) {
+ if(c1 == null) {
+ if(c2 == null) {
+ return 0;
+ } else {
+ // Sort nulls first
+ return 1;
+ }
+ } else if(c2 == null) {
+ // Sort nulls first
+ return -1;
+ }
+
+ // At this point, we know that c1 and c2 are not null
+ if(c1.equals(c2)) {
+ return 0;
+ }
+
+ // At this point, c1 and c2 are not null and not equal, here we
+ // compare them to see which is "higher" in the class hierarchy
+ boolean c1Lower = c2.isAssignableFrom(c1);
+ boolean c2Lower = c1.isAssignableFrom(c2);
+
+ if(c1Lower && !c2Lower) {
+ return 1;
+ } else if(c2Lower && !c1Lower) {
+ return -1;
+ }
+
+ // Doesn't matter, sort consistently on classname
+ return c1.getName().compareTo(c2.getName());
+ }
+ }
+
+ // Preload the Standard model provider so it takes priority over others
+ public static Logger LOG = SyslogCategory.getLogger(MODEL_AND_VALUES, Values.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;
+ protected static Validator validator;
+ protected static SchemaGenerator generator;
static {
- JSON = configureObjectMapper(new ObjectMapper());
+ // Find all service loader registered asset model providers
+ ServiceLoader.load(AssetModelProvider.class).forEach(Values.assetModelProviders::add);
+ initialise();
}
public static ObjectMapper configureObjectMapper(ObjectMapper objectMapper) {
@@ -72,7 +160,6 @@ public class Values {
.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
.setVisibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.ANY)
- //.registerModule(new ORModelModule())
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.registerModule(new ParameterNamesModule(JsonCreator.Mode.PROPERTIES));
@@ -302,139 +389,15 @@ public class Values {
return getValue(value, ArrayNode.class);
}
- public static <T> T[] reverseArray(T[] array, Class<T> clazz) {
- if (array == null) {
- return null;
- }
-
- List<T> list = Arrays.asList(array);
- Collections.reverse(list);
- return list.toArray(createArray(0, clazz));
- }
-
- public static <T> T[] createArray(int size, Class<T> clazz) {
- return (T[]) Array.newInstance(clazz, size);
- }
-
public static ObjectNode createJsonObject() {
return Values.JSON.createObjectNode();
}
- public static List<Object> createObjectList() {
- return new ArrayList<>();
- }
-
- /**
- * @param o A timestamp string as 'HH:mm:ss' or 'HH:mm'.
- * @return Epoch time or 0 if there is a problem parsing the timestamp string.
- */
- public static long parseTimestamp(Object o) {
- String timestamp = "";
- try {
- timestamp = o.toString();
- } catch (Exception e) {
- return (0L);
- }
- SimpleDateFormat sdf;
- if (timestamp.length() == 8) {
- sdf = new SimpleDateFormat("HH:mm:ss");
- } else if (timestamp.length() == 5) {
- sdf = new SimpleDateFormat("HH:mm");
- } else {
- return (0L);
- }
- try {
- return (sdf.parse(timestamp).getTime());
- } catch (ParseException e) {
- return (0L);
- }
- }
-
- /**
- * @param timestamp Epoch time
- * @return The timestamp formatted as 'HH:mm' or <code>null</code> if the timestamp is <= 0.
- */
- public static String formatTimestamp(long timestamp) {
- if (timestamp <= 0)
- return null;
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
- return (sdf.format(new Date(timestamp)));
- }
-
- /**
- * @param timestamp Epoch time
- * @return The timestamp formatted as 'HH:mm:ss' or <code>null</code> if the timestamp is <= 0.
- */
- public static String formatTimestampWithSeconds(long timestamp) {
- if (timestamp <= 0)
- return null;
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
- return (sdf.format(new Date(timestamp)));
- }
-
- /**
- * @param timestamp Epoch time
- * @return The timestamp formatted as 'EEE' or <code>null</code> if the timestamp is <= 0.
- */
- public static String formatDayOfWeek(long timestamp) {
- if (timestamp <= 0)
- return null;
- SimpleDateFormat sdf = new SimpleDateFormat("EEE");
- return (sdf.format(new Date(timestamp)));
- }
-
- /**
- * @param o A timestamp string as 'HH:mm' or '-'.
- * @param minutes The minutes to increment/decrement from timestamp.
- * @return Timestamp string as 'HH:mm', modified with the given minutes or the current time + 60 minutes if the
- * given timestamp was '-' or the given timestamp couldn't be parsed.
- */
- public static String shiftTime(Object o, int minutes) {
- String timestamp = o.toString();
- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
- Date date;
- if (timestamp != null && timestamp.length() >= 1 && timestamp.startsWith("-")) {
- date = new Date();
- date.setTime(date.getTime() + 60 * 60000);
- } else {
- try {
- date = sdf.parse(timestamp);
- date.setTime(date.getTime() + minutes * 60000);
- } catch (ParseException ex) {
- date = new Date();
- date.setTime(date.getTime() + 60 * 60000);
- }
- }
- return (sdf.format(date));
- }
-
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
- @SafeVarargs
- public static <T> List<T> joinCollections(Collection<T>... collections) {
- if (collections == null || collections.length == 0) {
- return Collections.emptyList();
- }
-
- List<T> newCollection = null;
-
- for (Collection<T> collection : collections) {
- if (collection == null) {
- continue;
- }
-
- if (newCollection == null) {
- newCollection = new ArrayList<>(collection);
- } else {
- newCollection.addAll(collection);
- }
- }
- return newCollection;
- }
-
public static <T> T convert(Object object, Class<T> targetType) {
if (object == null) {
return null;
@@ -467,7 +430,6 @@ public class Values {
return String.class.isAssignableFrom(clazz) || TextNode.class.isAssignableFrom(clazz) || BinaryNode.class.isAssignableFrom(clazz);
}
-
public static boolean isObject(Class<?> clazz) {
return !isArray(clazz) && !isBoolean(clazz) && !isNumber(clazz) && !isString(clazz);
}
@@ -571,4 +533,524 @@ public class Values {
}
return null;
}
+
+ public static AssetTypeInfo[] getAssetInfos(String parentType) {
+ return assetInfoMap.values().toArray(new AssetTypeInfo[0]);
+ }
+
+ public static Class<? extends Asset<?>>[] getAssetClasses(String parentType) {
+ return assetTypeMap.values().toArray(new Class[0]);
+ }
+
+ public static Optional<AssetTypeInfo> getAssetInfo(Class<? extends Asset<?>> assetType) {
+ return Optional.ofNullable(assetInfoMap.get(assetType));
+ }
+
+ public static Optional<AssetTypeInfo> getAssetInfo(String assetType) {
+ Class<? extends Asset<?>> assetClass = assetTypeMap.get(assetType);
+ return Optional.ofNullable(assetClass != null ? assetInfoMap.get(assetClass) : null);
+ }
+
+ // TODO: Implement ability to restrict which asset types are allowed to be added to a given parent type
+ public static AssetDescriptor<?>[] getAssetDescriptors(String parentType) {
+ return Arrays.stream(getAssetInfos(parentType)).map(AssetTypeInfo::getAssetDescriptor).toArray(AssetDescriptor[]::new);
+ }
+
+ public static <T extends Asset<?>> Optional<AssetDescriptor<T>> getAssetDescriptor(Class<T> assetType) {
+ return getAssetInfo(assetType).map(assetInfo -> (AssetDescriptor<T>)assetInfo.getAssetDescriptor());
+ }
+
+ public static Optional<AssetDescriptor<?>> getAssetDescriptor(String assetType) {
+ return getAssetInfo(assetType).map(AssetTypeInfo::getAssetDescriptor);
+ }
+
+ public static <T extends Agent<T, ?, ?>> Optional<AgentDescriptor<T, ?, ?>> getAgentDescriptor(Class<T> agentType) {
+ return getAssetDescriptor(agentType)
+ .map(assetDescriptor -> assetDescriptor instanceof AgentDescriptor ? (AgentDescriptor<T, ?, ?>)assetDescriptor : null);
+ }
+
+ public static Optional<AgentDescriptor<?, ?, ?>> getAgentDescriptor(String agentType) {
+ return getAssetDescriptor(agentType)
+ .map(assetDescriptor -> assetDescriptor instanceof AgentDescriptor ? (AgentDescriptor<?, ?, ?>)assetDescriptor : null);
+ }
+
+ public static MetaItemDescriptor<?>[] getMetaItemDescriptors() {
+ return metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]);
+ }
+
+ public static Optional<MetaItemDescriptor<?>[]> getMetaItemDescriptors(Class<? extends Asset<?>> assetType) {
+ return getAssetInfo(assetType).map(AssetTypeInfo::getMetaItemDescriptors);
+ }
+
+ public static Optional<MetaItemDescriptor<?>[]> getMetaItemDescriptors(String assetType) {
+ return getAssetInfo(assetType).map(AssetTypeInfo::getMetaItemDescriptors);
+ }
+
+ public static Optional<MetaItemDescriptor<?>> getMetaItemDescriptor(String name) {
+ if (TextUtil.isNullOrEmpty(name)) return Optional.empty();
+ return metaItemDescriptors.stream().filter(mid -> mid.getName().equals(name)).findFirst();
+ }
+
+ public static ValueDescriptor<?>[] getValueDescriptors() {
+ return valueDescriptors.toArray(new ValueDescriptor<?>[0]);
+ }
+
+ public static Optional<ValueDescriptor<?>[]> getValueDescriptors(Class<? extends Asset<?>> assetType) {
+ return getAssetInfo(assetType).map(AssetTypeInfo::getValueDescriptors);
+ }
+
+ public static Optional<ValueDescriptor<?>[]> getValueDescriptors(String assetType) {
+ return getAssetInfo(assetType).map(AssetTypeInfo::getValueDescriptors);
+ }
+
+ public static Optional<ValueDescriptor<?>> getValueDescriptor(String name) {
+ if (TextUtil.isNullOrEmpty(name)) return Optional.empty();
+
+ int arrayDimensions = 0;
+
+ while(name.endsWith("[]")) {
+ name = name.substring(0, name.length() - 2);
+ arrayDimensions++;
+ }
+
+ String finalName = name;
+ int finalArrayDimensions = arrayDimensions;
+ return valueDescriptors.stream().filter(vd -> vd.getName().equals(finalName)).findFirst().map(vd -> {
+ int dims = finalArrayDimensions;
+ while(dims > 0) {
+ vd = vd.asArray();
+ dims--;
+ }
+ return vd;
+ });
+ }
+
+ public static ValueDescriptor<?> getValueDescriptorForValue(Object value) {
+ if (value == null) {
+ return ValueDescriptor.UNKNOWN;
+ }
+
+ Class<?> valueClass = value.getClass();
+ boolean isArray = valueClass.isArray();
+ valueClass = isArray ? valueClass.getComponentType() : valueClass;
+ ValueDescriptor<?> valueDescriptor = ValueDescriptor.UNKNOWN;
+
+ if (valueClass == Boolean.class) valueDescriptor = ValueType.BOOLEAN;
+ else if (valueClass == String.class) valueDescriptor = ValueType.TEXT;
+ else if (valueClass == Integer.class) valueDescriptor = ValueType.INTEGER;
+ else if (valueClass == Long.class) valueDescriptor = ValueType.LONG;
+ else if (valueClass == Double.class || valueClass == Float.class) valueDescriptor = ValueType.NUMBER;
+ 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)) {
+ Object firstElem = findFirstNonNullEntry((Map<?,?>)value);
+
+ if (firstElem == null) valueDescriptor = ValueType.JSON_OBJECT;
+ else {
+ boolean elemIsArray = firstElem.getClass().isArray();
+ Class<?> elemClass = elemIsArray ? firstElem.getClass() : firstElem.getClass().getComponentType();
+ if (elemIsArray) {
+ valueDescriptor = elemClass == String.class ? ValueType.MULTIVALUED_TEXT_MAP : ValueType.JSON_OBJECT;
+ } else {
+ if (elemClass == String.class)
+ valueDescriptor = ValueType.TEXT_MAP;
+ else if (elemClass == Double.class || elemClass == Float.class)
+ valueDescriptor = ValueType.NUMBER_MAP;
+ else if (elemClass == Integer.class)
+ valueDescriptor = ValueType.TEXT_MAP;
+ else if (elemClass == Boolean.class)
+ valueDescriptor = ValueType.BOOLEAN_MAP;
+ }
+ }
+ }
+
+ return isArray ? valueDescriptor.asArray() : valueDescriptor;
+ }
+
+ public static List<AssetModelProvider> getModelProviders() {
+ return assetModelProviders;
+ }
+
+ public static void initialise() throws IllegalStateException {
+ try {
+ doInitialise();
+ } catch (IllegalStateException e) {
+ LOG.log(Level.SEVERE, "Failed to initialise the asset model", e);
+ throw e;
+ }
+ }
+
+ /**
+ * 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<>();
+ generator = null;
+
+ // Provide basic Object Mapper and enhance once asset model is initialised
+ JSON = configureObjectMapper(new ObjectMapper());
+
+ LOG.info("Initialising asset model...");
+ Map<Class<? extends Asset<?>>, List<NameHolder>> assetDescriptorProviders = new TreeMap<>(new ClassHierarchyComparator());
+ //noinspection RedundantCast
+ assetDescriptorProviders.put((Class<? extends Asset<?>>)(Class<?>)Asset.class, new ArrayList<>(getDescriptorFields(Asset.class)));
+
+ getModelProviders().forEach(assetModelProvider -> {
+ LOG.fine("Processing asset model provider: " + assetModelProvider.getClass().getSimpleName());
+ LOG.fine("Auto scan = " + assetModelProvider.useAutoScan());
+
+ if (assetModelProvider.useAutoScan()) {
+
+ Set<Class<? extends Asset<?>>> assetClasses = getAssetClasses(assetModelProvider);
+ LOG.fine("Found " + assetClasses.size() + " asset class(es)");
+
+ assetClasses.forEach(assetClass ->
+ assetDescriptorProviders.computeIfAbsent(assetClass, aClass ->
+ new ArrayList<>(getDescriptorFields(aClass))));
+
+ 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) -> {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+
+ list.addAll(getDescriptorFields(modelDescriptor.provider()));
+ return list;
+ });
+ }
+ }
+ }
+
+ if (assetModelProvider.getAssetDescriptors() != null) {
+ for (AssetDescriptor<?> assetDescriptor : assetModelProvider.getAssetDescriptors()) {
+ Class<? extends Asset<?>> assetClass = assetDescriptor.getType();
+
+ assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+
+ list.add(assetDescriptor);
+ return list;
+ });
+ }
+ }
+
+ if (assetModelProvider.getAttributeDescriptors() != null) {
+ assetModelProvider.getAttributeDescriptors().forEach((assetClass, attributeDescriptors) ->
+ assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+
+ list.addAll(attributeDescriptors);
+ return list;
+ }));
+ }
+
+ if (assetModelProvider.getMetaItemDescriptors() != null) {
+ assetModelProvider.getMetaItemDescriptors().forEach((assetClass, metaDescriptors) ->
+ assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+
+ list.addAll(metaDescriptors);
+ return list;
+ }));
+ }
+
+ if (assetModelProvider.getValueDescriptors() != null) {
+ assetModelProvider.getValueDescriptors().forEach((assetClass, valueDescriptors) ->
+ assetDescriptorProviders.compute(assetClass, (aClass, list) -> {
+ if (list == null) {
+ list = new ArrayList<>();
+ }
+
+ list.addAll(valueDescriptors);
+ 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) -> {
+
+ // 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);
+ assetInfoMap.put(assetClass, assetInfo);
+ assetTypeMap.put(assetInfo.getAssetDescriptor().getName(), assetClass);
+
+ if (assetInfo.getAssetDescriptor() instanceof AgentDescriptor) {
+ AgentDescriptor<?,?,?> agentDescriptor = (AgentDescriptor<?,?,?>)assetInfo.getAssetDescriptor();
+ 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());
+ }
+ 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);
+ }
+
+ // Call on finished on each provider
+ assetModelProviders.forEach(AssetModelProvider::onAssetModelFinished);
+
+ // Add agent link sub types to object mapper (need to avoid circular dependency)
+ NamedType[] agentLinkSubTypes = Arrays.stream(getAgentLinkClasses())
+ .map(agentLinkClass -> new NamedType(
+ agentLinkClass,
+ agentLinkClass.getSimpleName()
+ )).toArray(NamedType[]::new);
+ JSON.registerSubtypes(agentLinkSubTypes);
+
+ doSchemaInit();
+ }
+
+ protected static void doSchemaInit() {
+ SchemaGeneratorConfigBuilder configBuilder = new SchemaGeneratorConfigBuilder(JSON, SchemaVersion.DRAFT_7, OptionPreset.PLAIN_JSON)
+ .with(
+ new JacksonModule(
+ JacksonOption.FLATTENED_ENUMS_FROM_JSONVALUE
+ )
+ )
+ .with(
+ new Swagger2Module()
+ );
+// .with(new JavaxValidationModule());
+
+ configBuilder.forTypesInGeneral()
+ .withSubtypeResolver((declaredType, generationContext) -> {
+ if (declaredType.getErasedType() == AgentLink.class) {
+ TypeContext typeContext = generationContext.getTypeContext();
+ return Arrays.stream(getAgentLinkClasses())
+ .map(agentLinkClass -> typeContext.resolveSubtype(declaredType, agentLinkClass))
+ .collect(Collectors.toList());
+ }
+ return null;
+ });
+
+ SchemaGeneratorConfig config = configBuilder.build();
+ generator = new SchemaGenerator(config);
+ }
+
+ protected static Class<?>[] getAgentLinkClasses() {
+ return Arrays.stream(getAssetDescriptors(null))
+ .filter(descriptor -> descriptor instanceof AgentDescriptor)
+ .map(descriptor ->
+ ((AgentDescriptor<?, ?, ?>) descriptor).getAgentLinkClass()
+ )
+ .distinct()
+ .toArray(Class<?>[]::new);
+ }
+
+ /**
+ * Validates the supplied object using standard JSR-380 bean validation; therefore any type passed in here must
+ * follow the JSR-380 annotation requirements.
+ */
+ // TODO: Implement validation using javax bean validation JSR-380
+ public static <T> Set<ConstraintViolation<T>> validate(@NotNull T obj, Class<?>... groups) {
+
+ Validator validator = getValidator();
+ return validator.validate(obj, groups);
+ }
+
+ public static Validator getValidator() {
+ if (validator == null) {
+ validator = Validation
+ .buildDefaultValidatorFactory()
+ .getValidator();
+ }
+
+ return validator;
+ }
+
+ /**
+ * Returns the schema for the specified type
+ */
+ public static JsonNode getSchema(Class<?> clazz) {
+ if (generator == null) {
+ return JSON.createObjectNode();
+ }
+ return generator.generateSchema(clazz);
+ }
+
+ 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())
+ .filter(attributeDescriptor -> !attributeDescriptor.isOptional())
+ .map(Attribute::new)
+ .collect(Collectors.toList())
+ );
+ }
+
+ protected static boolean isGetter(Method method) {
+ if (Modifier.isPublic(method.getModifiers()) &&
+ method.getParameterTypes().length == 0) {
+ if (method.getName().matches("^get[A-Z].*") &&
+ !method.getReturnType().equals(void.class))
+ return true;
+ if (method.getName().matches("^is[A-Z].*") &&
+ method.getReturnType().equals(boolean.class))
+ return true;
+ }
+ return false;
+ }
+
+ protected static Set<Class<? extends Asset<?>>> getAssetClasses(AssetModelProvider assetModelProvider) {
+
+ Set<Class<? extends Asset<?>>> assetClasses;
+
+ // Search for concrete asset classes in the same JAR as the provided AssetModelProvider
+ Reflections reflections = new Reflections(new ConfigurationBuilder()
+ .setUrls(ClasspathHelper.forClass(assetModelProvider.getClass()))
+ .setScanners(
+ new SubTypesScanner(true)
+ ));
+
+ LOG.fine("Scanning for Asset classes");
+
+ assetClasses = reflections.getSubTypesOf(Asset.class).stream()
+ .map(assetClass -> (Class<? extends Asset<?>>)assetClass)
+ .filter(assetClass -> assetClass.getAnnotation(ModelIgnore.class) == null)
+ .collect(Collectors.toSet());
+
+ LOG.fine("Found asset class count = " + assetClasses.size());
+
+ return assetClasses;
+ }
+
+ /**
+ * Extract public static field values that are of type {@link AssetDescriptor}, {@link AttributeDescriptor}, {@link MetaItemDescriptor} or {@link ValueDescriptor}.
+ */
+ protected static List<NameHolder> getDescriptorFields(Class<?> type) {
+ return Arrays.stream(type.getDeclaredFields())
+ .filter(field ->
+ isStatic(field.getModifiers())
+ && isPublic(field.getModifiers())
+ && (AssetDescriptor.class.isAssignableFrom(field.getType())
+ || AttributeDescriptor.class.isAssignableFrom(field.getType())
+ || MetaItemDescriptor.class.isAssignableFrom(field.getType())
+ || ValueDescriptor.class.isAssignableFrom(field.getType())))
+ .map(field -> {
+ try {
+ return (NameHolder)field.get(null);
+ } catch (IllegalAccessException e) {
+ String msg = "Failed to extract descriptor fields from class: " + type.getName();
+ LOG.log(Level.SEVERE, msg, e);
+ throw new IllegalStateException(msg);
+ }
+ })
+ .collect(Collectors.toList());
+ }
+
+ protected static AssetTypeInfo buildAssetInfo(Class<? extends Asset<?>> assetClass, Map<Class<? extends Asset<?>>, List<NameHolder>> classDescriptorMap) throws IllegalStateException {
+
+ Class<?> currentClass = assetClass;
+ List<Class<?>> classTree = new ArrayList<>();
+
+ while (Asset.class.isAssignableFrom(currentClass)) {
+ classTree.add(currentClass);
+ currentClass = currentClass.getSuperclass();
+ }
+
+ // Check asset class has JPA entity annotation for JPA polymorphism
+ if (assetClass.getAnnotation(Entity.class) == null) {
+ throw new IllegalStateException("Asset class must have @Entity JPA annotation for polymorphic JPA support: " + assetClass);
+ }
+
+ if (Arrays.stream(assetClass.getDeclaredConstructors()).noneMatch(ctor -> ctor.getParameterCount() == 0)) {
+ throw new IllegalStateException("Asset class must have a no args constructor for JPA support: " + assetClass);
+ }
+
+ // Order from Asset class downwards
+ Collections.reverse(classTree);
+
+ AtomicReference<AssetDescriptor<?>> assetDescriptor = new AtomicReference<>();
+ Set<AttributeDescriptor<?>> attributeDescriptors = new HashSet<>(10);
+ List<MetaItemDescriptor<?>> metaItemDescriptors = new ArrayList<>(50);
+ List<ValueDescriptor<?>> valueDescriptors = new ArrayList<>(50);
+
+ classTree.forEach(aClass -> {
+ List<NameHolder> descriptors = classDescriptorMap.get(aClass);
+ if (descriptors != null) {
+ descriptors.forEach(descriptor -> {
+ if (aClass == assetClass && descriptor instanceof AssetDescriptor) {
+ if (assetDescriptor.get() != null) {
+ throw new IllegalStateException("Duplicate asset descriptor found: asset type=" + assetClass +", descriptor=" + assetDescriptor.get() + ", duplicate descriptor=" + descriptor);
+ }
+ assetDescriptor.set((AssetDescriptor<?>) descriptor);
+ } 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=" + assetClass + ", descriptor=" + existingDescriptor + ", duplicate descriptor=" + descriptor);
+ }
+ attributeDescriptors.remove(existingDescriptor);
+ });
+ attributeDescriptors.add((AttributeDescriptor<?>) descriptor);
+ } else if (descriptor instanceof MetaItemDescriptor) {
+ int index = Values.metaItemDescriptors.indexOf(descriptor);
+ if (index >= 0 && Values.metaItemDescriptors.get(index) != descriptor) {
+ throw new IllegalStateException("Duplicate meta item descriptor found: asset type=" + assetClass +", descriptor=" + metaItemDescriptors.get(index) + ", duplicate descriptor=" + descriptor);
+ }
+ metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
+ if (!Values.metaItemDescriptors.contains(descriptor)) {
+ Values.metaItemDescriptors.add((MetaItemDescriptor<?>) descriptor);
+ }
+ } else if (descriptor instanceof ValueDescriptor) {
+ ValueDescriptor<?> valueDescriptor = (ValueDescriptor<?>)descriptor;
+ // 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);
+ }
+ valueDescriptors.add(valueDescriptor);
+ if (!Values.valueDescriptors.contains(descriptor)) {
+ Values.valueDescriptors.add((ValueDescriptor<?>) descriptor);
+ }
+ }
+ });
+ }
+ });
+
+ if (assetDescriptor.get() == null || assetDescriptor.get().getType() != assetClass) {
+ throw new IllegalStateException("Asset descriptor not found or is not for this asset type: asset type=" + assetClass +", descriptor=" + assetDescriptor.get());
+ }
+
+ return new AssetTypeInfo(
+ assetDescriptor.get(),
+ attributeDescriptors.toArray(new AttributeDescriptor<?>[0]),
+ metaItemDescriptors.toArray(new MetaItemDescriptor<?>[0]),
+ valueDescriptors.toArray(new ValueDescriptor<?>[0]));
+ }
}
diff --git a/test/src/main/java/org/openremote/test/protocol/MockAgent.java b/test/src/main/java/org/openremote/test/protocol/MockAgent.java
index 7a1076b47..b6810ad95 100644
--- a/test/src/main/java/org/openremote/test/protocol/MockAgent.java
+++ b/test/src/main/java/org/openremote/test/protocol/MockAgent.java
@@ -21,7 +21,6 @@ package org.openremote.test.protocol;
import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
import org.openremote.model.value.AttributeDescriptor;
import org.openremote.model.value.ValueType;
@@ -29,28 +28,7 @@ import javax.persistence.Entity;
import java.util.Optional;
@Entity
-public class MockAgent extends Agent<MockAgent, MockProtocol, MockAgent.MockAgentLink> {
-
- public static class MockAgentLink extends AgentLink<MockAgentLink> {
-
- protected String requiredValue;
-
- // For Hydrators
- protected MockAgentLink() {}
-
- protected MockAgentLink(String id) {
- super(id);
- }
-
- public Optional<String> getRequiredValue() {
- return Optional.ofNullable(requiredValue);
- }
-
- public MockAgentLink setRequiredValue(String requiredValue) {
- this.requiredValue = requiredValue;
- return this;
- }
- }
+public class MockAgent extends Agent<MockAgent, MockProtocol, MockAgentLink> {
public static final AttributeDescriptor<Boolean> REQUIRED = new AttributeDescriptor<>("requiredTest", ValueType.BOOLEAN);
diff --git a/test/src/main/java/org/openremote/test/protocol/MockAgentLink.java b/test/src/main/java/org/openremote/test/protocol/MockAgentLink.java
new file mode 100644
index 000000000..196ac4a6f
--- /dev/null
+++ b/test/src/main/java/org/openremote/test/protocol/MockAgentLink.java
@@ -0,0 +1,46 @@
+/*
+ * 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.test.protocol;
+
+import org.openremote.model.asset.agent.AgentLink;
+
+import java.util.Optional;
+
+public class MockAgentLink extends AgentLink<MockAgentLink> {
+
+ protected String requiredValue;
+
+ // For Hydrators
+ protected MockAgentLink() {
+ }
+
+ protected MockAgentLink(String id) {
+ super(id);
+ }
+
+ public Optional<String> getRequiredValue() {
+ return Optional.ofNullable(requiredValue);
+ }
+
+ public MockAgentLink setRequiredValue(String requiredValue) {
+ this.requiredValue = requiredValue;
+ return this;
+ }
+}
diff --git a/test/src/main/java/org/openremote/test/protocol/MockProtocol.java b/test/src/main/java/org/openremote/test/protocol/MockProtocol.java
index fb14a2564..e03b35021 100644
--- a/test/src/main/java/org/openremote/test/protocol/MockProtocol.java
+++ b/test/src/main/java/org/openremote/test/protocol/MockProtocol.java
@@ -38,7 +38,7 @@ import java.util.function.Consumer;
/**
* A mock protocol for testing purposes that records the various method calls and supports protocol discovery
*/
-public class MockProtocol extends AbstractProtocol<MockAgent, MockAgent.MockAgentLink> implements ProtocolAssetDiscovery {
+public class MockProtocol extends AbstractProtocol<MockAgent, MockAgentLink> implements ProtocolAssetDiscovery {
public static final String PROTOCOl_NAME = "Mock protocol";
public List<AttributeEvent> protocolWriteAttributeEvents = new ArrayList<>();
@@ -68,7 +68,7 @@ public class MockProtocol extends AbstractProtocol<MockAgent, MockAgent.MockAgen
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, MockAgent.MockAgentLink agentLink) throws RuntimeException {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, MockAgentLink agentLink) throws RuntimeException {
protocolMethodCalls.add("LINK_ATTRIBUTE:" + assetId + ":" + attribute.getName());
if (!agentLink.getRequiredValue().isPresent()) {
@@ -78,12 +78,12 @@ public class MockProtocol extends AbstractProtocol<MockAgent, MockAgent.MockAgen
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, MockAgent.MockAgentLink agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, MockAgentLink agentLink) {
protocolMethodCalls.add("UNLINK_ATTRIBUTE:" + assetId + ":" + attribute.getName());
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, MockAgent.MockAgentLink agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, MockAgentLink agentLink, AttributeEvent event, Object processedValue) {
protocolMethodCalls.add("WRITE_ATTRIBUTE:" + event.getAssetId() + ":" + attribute.getName());
protocolWriteAttributeEvents.add(event);
if (updateSensor) {
diff --git a/test/src/main/java/org/openremote/test/protocol/http/HTTPServerTestAgent.java b/test/src/main/java/org/openremote/test/protocol/http/HTTPServerTestAgent.java
index 28b637939..5ddf1b76f 100644
--- a/test/src/main/java/org/openremote/test/protocol/http/HTTPServerTestAgent.java
+++ b/test/src/main/java/org/openremote/test/protocol/http/HTTPServerTestAgent.java
@@ -21,15 +21,15 @@ package org.openremote.test.protocol.http;
import org.openremote.agent.protocol.http.AbstractHTTPServerAgent;
import org.openremote.model.asset.agent.AgentDescriptor;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import javax.persistence.Entity;
@Entity
-public class HTTPServerTestAgent extends AbstractHTTPServerAgent<HTTPServerTestAgent, TestHTTPServerProtocol, AgentLink.Default> {
+public class HTTPServerTestAgent extends AbstractHTTPServerAgent<HTTPServerTestAgent, TestHTTPServerProtocol, DefaultAgentLink> {
- public static final AgentDescriptor<HTTPServerTestAgent, TestHTTPServerProtocol, AgentLink.Default> DESCRIPTOR = new AgentDescriptor<>(
- HTTPServerTestAgent.class, TestHTTPServerProtocol.class, AgentLink.Default.class
+ public static final AgentDescriptor<HTTPServerTestAgent, TestHTTPServerProtocol, DefaultAgentLink> DESCRIPTOR = new AgentDescriptor<>(
+ HTTPServerTestAgent.class, TestHTTPServerProtocol.class, DefaultAgentLink.class
);
protected HTTPServerTestAgent() {}
diff --git a/test/src/main/java/org/openremote/test/protocol/http/TestHTTPServerProtocol.java b/test/src/main/java/org/openremote/test/protocol/http/TestHTTPServerProtocol.java
index 104da5a67..f3415c10d 100644
--- a/test/src/main/java/org/openremote/test/protocol/http/TestHTTPServerProtocol.java
+++ b/test/src/main/java/org/openremote/test/protocol/http/TestHTTPServerProtocol.java
@@ -20,7 +20,7 @@
package org.openremote.test.protocol.http;
import org.openremote.agent.protocol.http.AbstractHTTPServerProtocol;
-import org.openremote.model.asset.agent.AgentLink;
+import org.openremote.model.asset.agent.DefaultAgentLink;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.AttributeEvent;
@@ -28,7 +28,7 @@ import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
-public class TestHTTPServerProtocol extends AbstractHTTPServerProtocol<TestHTTPServerProtocol, HTTPServerTestAgent, AgentLink.Default> {
+public class TestHTTPServerProtocol extends AbstractHTTPServerProtocol<TestHTTPServerProtocol, HTTPServerTestAgent, DefaultAgentLink> {
public static final String PROTOCOL_DISPLAY_NAME = "HTTP Server Test Protocol";
public TestResourceImpl resource1 = new TestResourceImpl();
@@ -43,17 +43,17 @@ public class TestHTTPServerProtocol extends AbstractHTTPServerProtocol<TestHTTPS
}
@Override
- protected void doLinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) throws RuntimeException {
+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) throws RuntimeException {
}
@Override
- protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, AgentLink.Default agentLink) {
+ protected void doUnlinkAttribute(String assetId, Attribute<?> attribute, DefaultAgentLink agentLink) {
}
@Override
- protected void doLinkedAttributeWrite(Attribute<?> attribute, AgentLink.Default agentLink, AttributeEvent event, Object processedValue) {
+ protected void doLinkedAttributeWrite(Attribute<?> attribute, DefaultAgentLink agentLink, AttributeEvent event, Object processedValue) {
}
diff --git a/test/src/main/java/org/openremote/test/protocol/velbus/MockVelbusAgent.java b/test/src/main/java/org/openremote/test/protocol/velbus/MockVelbusAgent.java
index 5b316eb21..c869236b1 100644
--- a/test/src/main/java/org/openremote/test/protocol/velbus/MockVelbusAgent.java
+++ b/test/src/main/java/org/openremote/test/protocol/velbus/MockVelbusAgent.java
@@ -20,6 +20,7 @@
package org.openremote.test.protocol.velbus;
import org.openremote.agent.protocol.velbus.VelbusAgent;
+import org.openremote.agent.protocol.velbus.VelbusAgentLink;
import org.openremote.model.asset.agent.AgentDescriptor;
import javax.persistence.Entity;
diff --git a/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java b/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
index a8c9fb712..f3cf12676 100644
--- a/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
+++ b/test/src/main/java/org/openremote/test/setup/ManagerTestSetup.java
@@ -21,6 +21,7 @@ package org.openremote.test.setup;
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;
import org.openremote.manager.security.UserConfiguration;
import org.openremote.manager.setup.ManagerSetup;
@@ -28,21 +29,16 @@ import org.openremote.model.Constants;
import org.openremote.model.Container;
import org.openremote.model.asset.Asset;
import org.openremote.model.asset.UserAsset;
-import org.openremote.model.asset.agent.Agent;
import org.openremote.model.asset.impl.*;
import org.openremote.model.attribute.Attribute;
import org.openremote.model.attribute.MetaItem;
import org.openremote.model.geo.GeoJSONPoint;
import org.openremote.model.security.Tenant;
-import org.openremote.model.value.MetaItemType;
import org.openremote.model.value.ValueConstraint;
import org.openremote.model.value.ValueType;
import org.openremote.model.value.Values;
import org.openremote.model.value.impl.ColourRGB;
-import java.util.List;
-import java.util.stream.Collectors;
-
import static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS_MAX_AGE_DAYS_DEFAULT;
import static org.openremote.model.Constants.*;
import static org.openremote.model.value.MetaItemType.*;
@@ -172,12 +168,12 @@ public class ManagerTestSetup extends ManagerSetup {
),
new MetaItem<>(
AGENT_LINK,
- new SimulatorAgent.SimulatorAgentLink(agent.getId()))
+ new SimulatorAgentLink(agent.getId()))
),
new Attribute<>("light1Dimmer", POSITIVE_INTEGER)
.addOrReplaceMeta(
new MetaItem<>(LABEL, "Light 1 Dimmer"),
- new MetaItem<>(AGENT_LINK, new SimulatorAgent.SimulatorAgentLink(agent.getId())),
+ new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(agent.getId())),
new MetaItem<>(UNITS, Constants.units(UNITS_PERCENTAGE)),
new MetaItem<>(CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Min(0), new ValueConstraint.Max(100)))
),
@@ -188,14 +184,14 @@ public class ManagerTestSetup extends ManagerSetup {
"Light 1 Color"),
new MetaItem<>(
AGENT_LINK,
- new SimulatorAgent.SimulatorAgentLink(agent.getId()))
+ new SimulatorAgentLink(agent.getId()))
),
new Attribute<>("light1PowerConsumption", POSITIVE_NUMBER, 12.345)
.addOrReplaceMeta(
new MetaItem<>(LABEL, "Light 1 Usage"),
new MetaItem<>(READ_ONLY, true),
new MetaItem<>(UNITS, Constants.units(UNITS_KILO, UNITS_WATT, UNITS_HOUR)),
- new MetaItem<>(AGENT_LINK, new SimulatorAgent.SimulatorAgentLink(agent.getId()))
+ new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(agent.getId()))
)
);
thing = assetStorageService.merge(thing);
@@ -305,19 +301,19 @@ public class ManagerTestSetup extends ManagerSetup {
)
);
addDemoApartmentRoomMotionSensor(apartment1Livingroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
addDemoApartmentRoomCO2Sensor(apartment1Livingroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
addDemoApartmentRoomHumiditySensor(apartment1Livingroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
addDemoApartmentRoomThermometer(apartment1Livingroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
addDemoApartmentTemperatureControl(apartment1Livingroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
apartment1Livingroom.setId(apartment1LivingroomId);
@@ -332,7 +328,7 @@ public class ManagerTestSetup extends ManagerSetup {
.addMeta(new MetaItem<>(ACCESS_RESTRICTED_WRITE, true))
);
addDemoApartmentRoomMotionSensor(apartment1Kitchen, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
for (String switchName : new String[]{"A", "B", "C"}) {
@@ -342,7 +338,7 @@ public class ManagerTestSetup extends ManagerSetup {
case 3:
case 4:
return new MetaItem[]{
- new MetaItem<>(AGENT_LINK, new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId))
+ new MetaItem<>(AGENT_LINK, new SimulatorAgentLink(apartment1ServiceAgentId))
};
}
return null;
@@ -360,7 +356,7 @@ public class ManagerTestSetup extends ManagerSetup {
.addMeta(new MetaItem<>(ACCESS_RESTRICTED_WRITE, true))
);
addDemoApartmentRoomMotionSensor(apartment1Hallway, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId)
+ new SimulatorAgentLink(apartment1ServiceAgentId)
);
apartment1Hallway = assetStorageService.merge(apartment1Hallway);
@@ -374,13 +370,13 @@ public class ManagerTestSetup extends ManagerSetup {
.addMeta(new MetaItem<>(ACCESS_RESTRICTED_WRITE, true))
);
addDemoApartmentRoomCO2Sensor(apartment1Bedroom1, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
addDemoApartmentRoomHumiditySensor(apartment1Bedroom1, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
addDemoApartmentRoomThermometer(apartment1Bedroom1, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
addDemoApartmentTemperatureControl(apartment1Bedroom1, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
apartment1Bedroom1 = assetStorageService.merge(apartment1Bedroom1);
apartment1Bedroom1Id = apartment1Bedroom1.getId();
@@ -397,15 +393,15 @@ public class ManagerTestSetup extends ManagerSetup {
)
);
addDemoApartmentRoomThermometer(apartment1Bathroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
addDemoApartmentTemperatureControl(apartment1Bathroom, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
apartment1Bathroom = assetStorageService.merge(apartment1Bathroom);
apartment1BathroomId = apartment1Bathroom.getId();
addDemoApartmentVentilation(apartment1, true, () ->
- new SimulatorAgent.SimulatorAgentLink(apartment1ServiceAgentId));
+ new SimulatorAgentLink(apartment1ServiceAgentId));
apartment1 = assetStorageService.merge(apartment1);
apartment1Id = apartment1.getId();
@@ -612,16 +608,16 @@ public class ManagerTestSetup extends ManagerSetup {
area1Id = assetArea1.getId();
PeopleCounterAsset peopleCounter1Asset = createDemoPeopleCounterAsset("PeopleCounter 1", assetArea1, new GeoJSONPoint(5.477126, 51.439137), () ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
peopleCounter1Asset = assetStorageService.merge(peopleCounter1Asset);
Asset<?> microphone1Asset = createDemoMicrophoneAsset("Microphone 1", assetArea1, new GeoJSONPoint(5.478092, 51.438655), () ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
microphone1Asset = assetStorageService.merge(microphone1Asset);
microphone1Id = microphone1Asset.getId();
Asset<?> enviroment1Asset = createDemoEnvironmentAsset("Environment 1", assetArea1, new GeoJSONPoint(5.478907, 51.438943),() ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
enviroment1Asset = assetStorageService.merge(enviroment1Asset);
Asset<?> light1Asset = createDemoLightAsset("Light 1", assetArea1, new GeoJSONPoint(5.476111, 51.438492));
@@ -640,11 +636,11 @@ public class ManagerTestSetup extends ManagerSetup {
assetArea2 = assetStorageService.merge(assetArea2);
Asset<?> peopleCounter2Asset = createDemoPeopleCounterAsset("PeopleCounter 2", assetArea2, new GeoJSONPoint(5.473686, 51.438603), () ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
peopleCounter2Asset = assetStorageService.merge(peopleCounter2Asset);
Asset<?> environment2Asset = createDemoEnvironmentAsset("Environment 2", assetArea2, new GeoJSONPoint(5.473552, 51.438412), () ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
environment2Asset = assetStorageService.merge(environment2Asset);
@@ -658,7 +654,7 @@ public class ManagerTestSetup extends ManagerSetup {
assetArea3 = assetStorageService.merge(assetArea3);
Asset<?> peopleCounter3Asset = createDemoPeopleCounterAsset("PeopleCounter 3", assetArea3, new GeoJSONPoint(5.487234, 51.447065), () ->
- new SimulatorAgent.SimulatorAgentLink(smartCityServiceAgentId));
+ new SimulatorAgentLink(smartCityServiceAgentId));
peopleCounter3Asset = assetStorageService.merge(peopleCounter3Asset);
peopleCounter3AssetId = peopleCounter3Asset.getId();
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
index 9ba9793dd..1f8fad519 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
@@ -5,9 +5,10 @@ import org.openremote.manager.asset.*
import org.openremote.manager.datapoint.AssetDatapointService
import org.openremote.manager.rules.RulesService
import org.openremote.manager.setup.SetupService
+import org.openremote.model.asset.agent.DefaultAgentLink
+import org.openremote.test.protocol.MockAgentLink
import org.openremote.test.setup.KeycloakTestSetup
import org.openremote.model.asset.Asset
-import org.openremote.model.asset.agent.AgentLink
import org.openremote.model.asset.agent.ConnectionStatus
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.*
@@ -110,7 +111,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent.id)
+ new MockAgentLink(mockAgent.id)
.setRequiredValue("true")
)
),
@@ -118,7 +119,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new AgentLink.Default("INVALID AGENT ID")
+ new DefaultAgentLink("INVALID AGENT ID")
)
),
new Attribute<>("plainAttribute", TEXT, "demo")
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 19598e336..c626ed0fb 100644
--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy
@@ -4,6 +4,7 @@ import com.google.common.collect.Lists
import io.netty.channel.ChannelHandler
import org.apache.http.client.utils.URIBuilder
import org.openremote.agent.protocol.http.HTTPAgent
+import org.openremote.agent.protocol.http.HTTPAgentLink
import org.openremote.agent.protocol.io.AbstractNettyIOClient
import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.agent.protocol.websocket.WebsocketIOClient
@@ -195,12 +196,12 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
new MetaItem<>(ACCESS_PUBLIC_READ)
),
new Attribute<>("temp", NUMBER).addOrReplaceMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[i-1])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[i-1])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
),
new Attribute<>("tempSetpoint", NUMBER).addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[i-1])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[i-1])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
)
@@ -386,12 +387,12 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
new MetaItem<>(ACCESS_PUBLIC_READ)
),
new Attribute<>("temp", NUMBER).addOrReplaceMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[0])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[0])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
),
new Attribute<>("tempSetpoint", NUMBER).addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[0])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[0])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
)
@@ -418,7 +419,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
new Attribute<>("co2Level", POSITIVE_INTEGER, 500)
.addMeta(
new MetaItem<>(UNITS, units(UNITS_PART_PER_MILLION)),
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[0]).setPath(""))
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[0]).setPath(""))
)
)
gatewayClient.sendMessage(SharedEvent.MESSAGE_PREFIX + Values.asJSON(new AssetEvent(AssetEvent.Cause.UPDATE, building1Room5Asset, (String[]) ["name", "attributes"].toArray(new String[0]))).get())
@@ -648,12 +649,12 @@ class GatewayTest extends Specification implements ManagerContainerTrait {
new MetaItem<>(ACCESS_PUBLIC_READ)
),
new Attribute<>("temp", NUMBER).addOrReplaceMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[1])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[1])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
),
new Attribute<>("tempSetpoint", NUMBER).addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agentAssetIds[1])
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agentAssetIds[1])
.setPath("")),
new MetaItem<>(UNITS, units(UNITS_CELSIUS))
)
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 dd17d2d3c..851f9af28 100644
--- a/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/model/AssetModelTest.groovy
@@ -1,13 +1,17 @@
package org.openremote.test.model
import com.fasterxml.jackson.databind.node.ObjectNode
-import org.openremote.agent.protocol.http.HTTPAgent
+import org.openremote.agent.protocol.http.HTTPAgentLink
import org.openremote.agent.protocol.simulator.SimulatorAgent
+import org.openremote.agent.protocol.simulator.SimulatorAgentLink
import org.openremote.agent.protocol.velbus.VelbusTCPAgent
import org.openremote.manager.asset.AssetModelService
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetModelResource
+import org.openremote.model.asset.agent.Agent
+import org.openremote.model.asset.agent.AgentDescriptor
import org.openremote.model.asset.agent.AgentLink
+import org.openremote.model.asset.agent.DefaultAgentLink
import org.openremote.model.asset.impl.GroupAsset
import org.openremote.model.asset.impl.LightAsset
import org.openremote.model.asset.impl.ThingAsset
@@ -15,7 +19,6 @@ import org.openremote.model.attribute.Attribute
import org.openremote.model.attribute.MetaItem
import org.openremote.model.rules.AssetState
import org.openremote.model.asset.AssetTypeInfo
-import org.openremote.model.util.AssetModelUtil
import org.openremote.model.value.MetaItemType
import org.openremote.model.value.SubStringValueFilter
import org.openremote.model.value.ValueConstraint
@@ -46,7 +49,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
def "Retrieving all asset model info"() {
when: "an asset info is serialised"
- def thingAssetInfo = AssetModelUtil.getAssetInfo(ThingAsset.class).orElse(null)
+ def thingAssetInfo = Values.getAssetInfo(ThingAsset.class).orElse(null)
def thingAssetInfoStr = Values.asJSON(thingAssetInfo)
then: "it should contain the right information"
@@ -63,13 +66,13 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
thingAssetInfo2.get().attributeDescriptors.find { (it == Asset.LOCATION) }.type == ValueType.GEO_JSON_POINT
when: "the asset type value descriptor is retrieved"
- def assetValueType = AssetModelUtil.getValueDescriptor(ValueType.ASSET_TYPE.getName())
+ def assetValueType = Values.getValueDescriptor(ValueType.ASSET_TYPE.getName())
then: "it should contain an allowed values constraint with all asset types listed"
assetValueType.isPresent()
assetValueType.get().constraints != null
assetValueType.get().constraints.find {it instanceof ValueConstraint.AllowedValues} as ValueConstraint.AllowedValues != null
- (assetValueType.get().constraints.find {it instanceof ValueConstraint.AllowedValues} as ValueConstraint.AllowedValues).allowedValues.length == AssetModelUtil.getAssetInfos().length
+ (assetValueType.get().constraints.find {it instanceof ValueConstraint.AllowedValues} as ValueConstraint.AllowedValues).allowedValues.length == Values.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"
@@ -77,7 +80,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
then: "the asset model infos should be available"
assetInfos.size() > 0
- assetInfos.size() == AssetModelUtil.assetTypeMap.size()
+ assetInfos.size() == Values.assetTypeMap.size()
def velbusTcpAgent = assetInfos.find {it.assetDescriptor.type == VelbusTCPAgent.class}
velbusTcpAgent != null
velbusTcpAgent.attributeDescriptors.any {it == VelbusTCPAgent.VELBUS_HOST && !it.optional}
@@ -96,18 +99,20 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
thingAssetInfo.valueDescriptors != null
thingAssetInfo.attributeDescriptors.contains(Asset.LOCATION)
thingAssetInfo.metaItemDescriptors.contains(MetaItemType.AGENT_LINK)
- AssetModelUtil.getAssetDescriptor(ThingAsset.class) != null
- AssetModelUtil.getAgentDescriptor(SimulatorAgent.class) != null
+ Values.getAssetDescriptor(ThingAsset.class) != null
+ Values.getAgentDescriptor(SimulatorAgent.class) != null
when: "the http test server agent descriptor is retrieved (the test asset model provider should have registered test agents and assets)"
- def testAgentDescriptor = AssetModelUtil.getAgentDescriptor(HTTPServerTestAgent.DESCRIPTOR.name).orElse(null)
+ def testAgentDescriptor = Values.getAgentDescriptor(HTTPServerTestAgent.DESCRIPTOR.name).orElse(null)
then: "the descriptor should have been found"
assert testAgentDescriptor != null
and: "the descriptor should contain an agent link schema"
- def schema = testAgentDescriptor.getAgentLinkSchema()
+ def schema = Values.getSchema(AgentLink.class)
assert schema != null
+ assert schema.get("anyOf") != null
+ assert schema.get("anyOf").size() == Values.getAssetDescriptors(null).findAll {it instanceof AgentDescriptor}.collect {(it as AgentDescriptor).getAgentLinkClass()}.unique {it.getSimpleName()}.size()
}
def "Serialize/Deserialize asset model"() {
@@ -119,7 +124,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
.addAttributes(
new Attribute<>("testAttribute", BIG_NUMBER, 100.5, System.currentTimeMillis())
.addOrReplaceMeta(
- new MetaItem<>(MetaItemType.AGENT_LINK, new HTTPAgent.HTTPAgentLink("http_agent_id")
+ new MetaItem<>(MetaItemType.AGENT_LINK, new HTTPAgentLink("http_agent_id")
.setPath("test_path")
.setPagingMode(true))
)
@@ -127,7 +132,7 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
asset.getAttribute(LightAsset.COLOUR_RGB).ifPresent({
it.addOrReplaceMeta(
- new MetaItem<>(MetaItemType.AGENT_LINK, new AgentLink.Default("agent_id")
+ new MetaItem<>(MetaItemType.AGENT_LINK, new DefaultAgentLink("agent_id")
.setValueFilters(
[new SubStringValueFilter(0,10)] as ValueFilter[]
)
@@ -150,11 +155,11 @@ class AssetModelTest extends Specification implements ManagerContainerTrait {
assetObjectNode.get("attributes").get("colourRGB").get("timestamp") == null
assetObjectNode.get("attributes").get("colourRGB").get("meta").get(MetaItemType.AGENT_LINK.name).isObject()
assetObjectNode.get("attributes").get("colourRGB").get("meta").get(MetaItemType.AGENT_LINK.name).get("id").asText() == "agent_id"
- assetObjectNode.get("attributes").get("colourRGB").get("meta").get(MetaItemType.AGENT_LINK.name).get("type").asText() == AgentLink.Default.class.getSimpleName()
+ assetObjectNode.get("attributes").get("colourRGB").get("meta").get(MetaItemType.AGENT_LINK.name).get("type").asText() == DefaultAgentLink.class.getSimpleName()
assetObjectNode.get("attributes").get("testAttribute").get("meta").get(MetaItemType.AGENT_LINK.name).isObject()
assetObjectNode.get("attributes").get("testAttribute").get("value").decimalValue() == 100.5
assetObjectNode.get("attributes").get("testAttribute").get("meta").get(MetaItemType.AGENT_LINK.name).get("id").asText() == "http_agent_id"
- assetObjectNode.get("attributes").get("testAttribute").get("meta").get(MetaItemType.AGENT_LINK.name).get("type").asText() == HTTPAgent.HTTPAgentLink.class.getSimpleName()
+ assetObjectNode.get("attributes").get("testAttribute").get("meta").get(MetaItemType.AGENT_LINK.name).get("type").asText() == HTTPAgentLink.class.getSimpleName()
when: "the asset is deserialized"
def asset2 = Values.parse(assetStr, LightAsset.class).orElse(null)
@@ -166,9 +171,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 HTTPAgent.HTTPAgentLink
- asset2.getAttribute("testAttribute", BIG_NUMBER.type).flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgent.HTTPAgentLink)it}.flatMap{it.path}.orElse("") == "test_path"
- asset2.getAttribute("testAttribute", BIG_NUMBER.type).flatMap{it.getMetaValue(MetaItemType.AGENT_LINK)}.map{(HTTPAgent.HTTPAgentLink)it}.flatMap{it.pagingMode}.orElse(false)
+ 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)
when: "an attribute is cloned"
def attribute = asset2.getAttribute(LightAsset.COLOUR_RGB).get()
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 bba400254..078bfd384 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy
@@ -100,7 +100,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
.setRequiredValue("true")
)
),
@@ -108,7 +108,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
.setRequiredValue("true")
)
),
@@ -116,14 +116,14 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
)
),
new Attribute<>("lightToggle2", BOOLEAN)
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent2.id)
+ new MockAgentLink(mockAgent2.id)
.setRequiredValue("true")
)
),
@@ -131,7 +131,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent2.id)
+ new MockAgentLink(mockAgent2.id)
.setRequiredValue("true")
)
),
@@ -139,7 +139,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent3.id)
+ new MockAgentLink(mockAgent3.id)
.setRequiredValue("true")
)
),
@@ -147,7 +147,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent3.id)
+ new MockAgentLink(mockAgent3.id)
.setRequiredValue("true")
)
),
@@ -155,7 +155,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink("invalid id")
+ new MockAgentLink("invalid id")
.setRequiredValue("true")
)
),
@@ -167,7 +167,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
.setRequiredValue("true")
.setValueFilters(
[
@@ -180,7 +180,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
.setRequiredValue("true")
.setValueFilters(
[
@@ -193,7 +193,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait {
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new MockAgent.MockAgentLink(mockAgent1.id)
+ new MockAgentLink(mockAgent1.id)
.setRequiredValue("true")
.setValueFilters(
[
diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
index 578b2c67b..cfacbdb64 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy
@@ -21,6 +21,7 @@ package org.openremote.test.protocol
import org.apache.commons.lang3.SystemUtils
import org.openremote.agent.protocol.knx.KNXAgent
+import org.openremote.agent.protocol.knx.KNXAgentLink
import org.openremote.agent.protocol.knx.KNXProtocol
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
@@ -117,7 +118,7 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {
new Attribute<>("light1ToggleOnOff", BOOLEAN)
.addOrReplaceMeta(
new MetaItem<>(LABEL, "Light 1 Toggle On/Off"),
- new MetaItem<>(AGENT_LINK, new KNXAgent.KNXAgentLink(knxAgent1.id, "1.001", "1/0/17", "0/4/14"))
+ new MetaItem<>(AGENT_LINK, new KNXAgentLink(knxAgent1.id, "1.001", "1/0/17", "0/4/14"))
)
)
knxThing = assetStorageService.merge(knxThing)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy
index 50b0558bd..a48243633 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy
@@ -22,6 +22,7 @@ package org.openremote.test.protocol.controller
import org.jboss.resteasy.spi.ResteasyUriInfo
import org.jboss.resteasy.util.BasicAuthHelper
import org.openremote.agent.protocol.controller.ControllerAgent
+import org.openremote.agent.protocol.controller.ControllerAgentLink
import org.openremote.agent.protocol.controller.ControllerProtocol
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
@@ -203,13 +204,13 @@ class ControllerProtocolTest extends Specification implements ManagerContainerTr
// attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
new Attribute<>("sensor", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new ControllerAgent.ControllerAgentLink(agent1.id, "MyDevice")
+ new MetaItem<>(AGENT_LINK, new ControllerAgentLink(agent1.id, "MyDevice")
.setSensorName("my_sensor1a")),
new MetaItem<>(READ_ONLY)
),
new Attribute<>("command", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new ControllerAgent.ControllerAgentLink(agent1.id, "MyDevice")
+ new MetaItem<>(AGENT_LINK, new ControllerAgentLink(agent1.id, "MyDevice")
.setCommandName("my_command"))
)
)
@@ -279,7 +280,7 @@ class ControllerProtocolTest extends Specification implements ManagerContainerTr
// attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
new Attribute<>("command", TEXT, "command1")
.addMeta(
- new MetaItem<>(AGENT_LINK, new ControllerAgent.ControllerAgentLink(agent3.id, "DeviceName2")
+ new MetaItem<>(AGENT_LINK, new ControllerAgentLink(agent3.id, "DeviceName2")
.setCommandsMap(new HashMap<String, List<String>>([
("command1") : ["my_command"],
("command2") : ["wrong"]
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 6adf10431..ae69b4330 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
@@ -23,6 +23,7 @@ import com.fasterxml.jackson.databind.node.ObjectNode
import org.jboss.resteasy.spi.ResteasyUriInfo
import org.jboss.resteasy.util.BasicAuthHelper
import org.openremote.agent.protocol.http.HTTPAgent
+import org.openremote.agent.protocol.http.HTTPAgentLink
import org.openremote.agent.protocol.http.HTTPMethod
import org.openremote.agent.protocol.http.HTTPProtocol
import org.openremote.container.web.OAuthServerResponse
@@ -286,7 +287,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
// attribute that sends requests to the server using PUT with dynamic body and custom header to override parent
new Attribute<>("putRequestWithHeaders", JSON_OBJECT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath("put_request_with_headers")
.setMethod(HTTPMethod.PUT)
.setWriteValue('{"prop1": {$value}, "prop2": "prop2Value"}')
@@ -307,7 +308,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
// attribute that sends requests to the server using GET with dynamic path
new Attribute<>("getRequestWithDynamicPath", BOOLEAN)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath('value/{$value}/set')
.setWriteValueConverter((ObjectNode)Values.parse("{\n" +
" \"TRUE\": \"on\",\n" +
@@ -318,7 +319,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
// attribute that polls the server using GET and uses regex filter on response
new Attribute<>("getPollSlow", INTEGER)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath("get_poll_slow")
.setPollingMillis(50)
.setValueFilters(
@@ -331,7 +332,7 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
// attribute that polls the server using GET and uses regex filter on response
new Attribute<>("getPollFast", INTEGER)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent.id)
.setPath("get_poll_fast")
.setPollingMillis(40)
.setValueFilters(
@@ -430,38 +431,38 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTr
.addOrReplaceAttributes(
new Attribute<>("getSuccess", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent2.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent2.id)
.setPath("get_success_200")
)
),
new Attribute<>("getFailure", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent2.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent2.id)
.setPath("get_failure_401")
)
),
new Attribute<>("pollFailure", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent3.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent3.id)
.setPath("get_failure_401")
.setPollingMillis(50)
)
),
new Attribute<>("getSuccess2", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent4.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent4.id)
.setPath("get_success_200")
)
),
new Attribute<>("getFailure2", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent4.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent4.id)
.setPath("get_failure_401")
)
),
new Attribute<>("getRedirect", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new HTTPAgent.HTTPAgentLink(agent4.id)
+ new MetaItem<>(AGENT_LINK, new HTTPAgentLink(agent4.id)
.setPath("redirect")
)
)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy
index 8aecb95eb..6b9e49bad 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy
@@ -27,7 +27,6 @@ import io.netty.handler.codec.MessageToMessageEncoder
import io.netty.handler.codec.bytes.ByteArrayDecoder
import org.openremote.agent.protocol.udp.UDPAgent
import org.openremote.model.asset.agent.Agent
-import org.openremote.model.asset.agent.AgentLink
import org.openremote.agent.protocol.udp.AbstractUDPServer
import org.openremote.agent.protocol.udp.UDPProtocol
import org.openremote.agent.protocol.udp.UDPStringServer
@@ -36,6 +35,7 @@ import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
import org.openremote.model.Constants
import org.openremote.model.asset.agent.ConnectionStatus
+import org.openremote.model.asset.agent.DefaultAgentLink
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.*
import org.openremote.model.query.AssetQuery
@@ -118,29 +118,29 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTra
.addOrReplaceAttributes(
new Attribute<>("startHello", EXECUTION_STATUS)
.addMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.id)
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.id)
.setWriteValue("abcdef"))
),
new Attribute<>("echoHello", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.id)
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.id)
.setWriteValue('Hello {$value};'))
),
new Attribute<>("echoWorld", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.id)
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.id)
.setWriteValue("World;"))
),
new Attribute<>("responseHello", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.id)
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.id)
.setMessageMatchPredicate(
new StringPredicate(AssetQuery.Match.BEGIN, true, "Hello"))
)
),
new Attribute<>("responseWorld", TEXT)
.addMeta(
- new MetaItem<>(AGENT_LINK, new AgentLink.Default(agent.id)
+ new MetaItem<>(AGENT_LINK, new DefaultAgentLink(agent.id)
.setMessageMatchPredicate(
new StringPredicate(AssetQuery.Match.BEGIN, true, "Hello"))
)
diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
index 5315942a2..8eac55758 100644
--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy
@@ -1,7 +1,7 @@
package org.openremote.test.protocol.velbus
import org.apache.commons.io.IOUtils
-import org.openremote.agent.protocol.velbus.VelbusAgent
+import org.openremote.agent.protocol.velbus.VelbusAgentLink
import org.openremote.manager.agent.AgentService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -84,7 +84,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
.addOrReplaceMeta(
new MetaItem<>(
AGENT_LINK,
- new VelbusAgent.VelbusAgentLink(agent.id, 48, "CH1")
+ new VelbusAgentLink(agent.id, 48, "CH1")
)
)
)
@@ -163,7 +163,7 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
!it.asset.getAttributes().isEmpty() &&
it.asset.getAttributes().values().every {attr ->
attr.getMetaValue(AGENT_LINK).map{
- Values.getValue(it, VelbusAgent.VelbusAgentLink.class)
+ Values.getValue(it, VelbusAgentLink.class)
.map({agentLink -> agentLink.id == agent.id && agentLink.deviceAddress.isPresent() && agentLink.deviceValueLink.isPresent()})
.orElse(false)
}.orElse(true)
@@ -174,9 +174,9 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTrait
def asset = assets.find {it.asset.name == "VMBGPOD"}
assert asset != null
assert asset.asset.getAttributes().size() == 305
- def memoTextAttribute = asset.asset.getAttributes().values().find {it.getMetaValue(AGENT_LINK).map{(it as VelbusAgent.VelbusAgentLink).deviceValueLink.orElse(null) == "MEMO_TEXT"}.orElse(false)}
+ def memoTextAttribute = asset.asset.getAttributes().values().find {it.getMetaValue(AGENT_LINK).map{(it as VelbusAgentLink).deviceValueLink.orElse(null) == "MEMO_TEXT"}.orElse(false)}
assert memoTextAttribute != null
- assert memoTextAttribute.getMetaValue(AGENT_LINK).flatMap(){(it as VelbusAgent.VelbusAgentLink).deviceAddress}.orElse(null) == 24
+ assert memoTextAttribute.getMetaValue(AGENT_LINK).flatMap(){(it as VelbusAgentLink).deviceAddress}.orElse(null) == 24
and: "all imported assets should be fully linked"
conditions.eventually {
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 ca3b9bf8d..facd0871d 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
@@ -21,6 +21,7 @@ package org.openremote.test.protocol.websocket
import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.agent.protocol.websocket.WebsocketAgent
+import org.openremote.agent.protocol.websocket.WebsocketAgentLink
import org.openremote.agent.protocol.websocket.WebsocketAgentProtocol
import org.openremote.agent.protocol.websocket.WebsocketHTTPSubscription
import org.openremote.agent.protocol.websocket.WebsocketSubscription
@@ -192,7 +193,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
// write attribute value
new Attribute<>("readWriteTargetTemp", NUMBER)
.addMeta(
- new MetaItem<>(AGENT_LINK, new WebsocketAgent.WebsocketAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new WebsocketAgentLink(agent.id)
.setWriteValue(SharedEvent.MESSAGE_PREFIX +
Values.asJSON(new AttributeEvent(
managerTestSetup.apartment1LivingroomId,
@@ -230,7 +231,7 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContai
),
new Attribute<>("readCo2Level", NUMBER)
.addMeta(
- new MetaItem<>(AGENT_LINK, new WebsocketAgent.WebsocketAgentLink(agent.id)
+ new MetaItem<>(AGENT_LINK, new WebsocketAgentLink(agent.id)
.setMessageMatchFilters(
[
new SubStringValueFilter(TriggeredEventSubscription.MESSAGE_PREFIX.length()),
diff --git a/ui/component/core/src/index.ts b/ui/component/core/src/index.ts
index 46d4555a4..a364e347b 100644
--- a/ui/component/core/src/index.ts
+++ b/ui/component/core/src/index.ts
@@ -473,7 +473,7 @@ export class AssetModelUtil {
}
}
-export type EventCallback = (event: OREvent) => any;
+export type EventCallback = (event: OREvent) => void;
export class Manager implements EventProviderFactory {
diff --git a/ui/component/model/src/main/java/AssetModelInfoExtension.java b/ui/component/model/src/main/java/AssetModelInfoExtension.java
index 3e2edb3d3..d182e3b34 100644
--- a/ui/component/model/src/main/java/AssetModelInfoExtension.java
+++ b/ui/component/model/src/main/java/AssetModelInfoExtension.java
@@ -20,16 +20,13 @@
import cz.habarta.typescript.generator.Extension;
import cz.habarta.typescript.generator.Settings;
-import cz.habarta.typescript.generator.compiler.ModelCompiler;
-import cz.habarta.typescript.generator.compiler.TsModelTransformer;
import cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures;
-import cz.habarta.typescript.generator.emitter.TsBeanModel;
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.AssetModelUtil;
import org.openremote.model.value.MetaItemDescriptor;
+import org.openremote.model.value.Values;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
@@ -42,9 +39,9 @@ public class AssetModelInfoExtension extends Extension {
public AssetModelInfoExtension() {
// Service loader doesn't seem to work so manually load the agent model provider
- AssetModelUtil.getModelProviders().add(new AgentModelProvider());
+ Values.getModelProviders().add(new AgentModelProvider());
// Ensure the asset model is initialised
- AssetModelUtil.initialiseOrThrow();
+ Values.initialise();
}
@Override
@@ -61,7 +58,7 @@ public class AssetModelInfoExtension extends Extension {
Map<String, String> assetMap = new HashMap<>();
Map<String, String> otherMap = new HashMap<>();
- Arrays.stream(AssetModelUtil.getAssetInfos(null)).forEach(assetModelInfo -> {
+ Arrays.stream(Values.getAssetInfos(null)).forEach(assetModelInfo -> {
String assetDescriptorName = assetModelInfo.getAssetDescriptor().getName();
assetMap.put(assetDescriptorName.toUpperCase(Locale.ROOT), assetDescriptorName);
@@ -78,7 +75,7 @@ public class AssetModelInfoExtension extends Extension {
emitEnum(writer, "WellknownAttributes", otherMap);
otherMap.clear();
- Arrays.stream(AssetModelUtil.getMetaItemDescriptors()).forEach(metaItemDescriptor -> {
+ Arrays.stream(Values.getMetaItemDescriptors()).forEach(metaItemDescriptor -> {
String metaName = metaItemDescriptor.getName();
otherMap.put(metaName.toUpperCase(Locale.ROOT), metaName);
});
@@ -86,7 +83,7 @@ public class AssetModelInfoExtension extends Extension {
emitEnum(writer, "WellknownMetaItems", otherMap);
otherMap.clear();
- Arrays.stream(AssetModelUtil.getValueDescriptors()).forEach(valueDescriptor -> {
+ Arrays.stream(Values.getValueDescriptors()).forEach(valueDescriptor -> {
String valueTypeName = valueDescriptor.getName();
otherMap.put(valueTypeName.toUpperCase(Locale.ROOT).replaceAll("[^A-Z0-9]", ""), valueTypeName);
});
diff --git a/ui/component/model/src/main/java/CustomExtension.java b/ui/component/model/src/main/java/CustomExtension.java
index 4af27105b..c4cc19701 100644
--- a/ui/component/model/src/main/java/CustomExtension.java
+++ b/ui/component/model/src/main/java/CustomExtension.java
@@ -19,20 +19,16 @@
*/
import cz.habarta.typescript.generator.Extension;
-import cz.habarta.typescript.generator.Settings;
import cz.habarta.typescript.generator.TsType;
import cz.habarta.typescript.generator.compiler.ModelCompiler;
import cz.habarta.typescript.generator.compiler.TsModelTransformer;
import cz.habarta.typescript.generator.emitter.EmitterExtensionFeatures;
import cz.habarta.typescript.generator.emitter.TsBeanModel;
-import cz.habarta.typescript.generator.emitter.TsModel;
import cz.habarta.typescript.generator.emitter.TsPropertyModel;
-import org.openremote.agent.protocol.AgentModelProvider;
import org.openremote.model.asset.AssetTypeInfo;
-import org.openremote.model.util.AssetModelUtil;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
+import java.util.Arrays;
+import java.util.List;
/**
* Does some custom processing for our specific model:
diff --git a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
index ee119556e..d1f3f2c64 100644
--- a/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
+++ b/ui/component/or-asset-viewer/src/or-edit-asset-panel.ts
@@ -1,4 +1,5 @@
import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";
+import {until} from "lit/directives/until";
import {customElement, property} from "lit/decorators.js";
import {InputType, OrMwcInput, OrInputChangedEvent, getValueHolderInputTemplateProvider, ValueInputProviderOptions, OrInputChangedEventDetail} from "@openremote/or-mwc-components/or-mwc-input";
import i18next from "i18next";
@@ -15,7 +16,7 @@ import {
} from "./or-add-attribute-panel";
import {panelStyles} from "./style";
import { OrAssetTree, UiAssetTreeNode } from "@openremote/or-asset-tree";
-import { OrAttributeInputChangedEvent } from "@openremote/or-attribute-input";
+import {jsonFormsInputTemplateProvider, OrAttributeInputChangedEvent } from "@openremote/or-attribute-input";
// TODO: Add webpack/rollup to build so consumers aren't forced to use the same tooling
const tableStyle = require("@material/data-table/dist/mdc.data-table.css");
@@ -280,9 +281,9 @@ export class OrEditAssetPanel extends LitElement {
this._onModified();
}
- protected _onMetaItemModified(attribute: Attribute<any>, metaItem: NameValueHolder<any>, detail: OrInputChangedEventDetail) {
- metaItem.value = detail.value;
- attribute.meta![metaItem.name!] = detail.value;
+ protected _onMetaItemModified(attribute: Attribute<any>, metaItem: NameValueHolder<any>, detail: OrInputChangedEventDetail | undefined) {
+ metaItem.value = detail ? detail.value : undefined;
+ attribute.meta![metaItem.name!] = metaItem.value;
this._onModified();
}
@@ -294,7 +295,7 @@ export class OrEditAssetPanel extends LitElement {
};
const descriptor = AssetModelUtil.getMetaItemDescriptor(metaItem.name);
- let valueDescriptor = descriptor ? AssetModelUtil.getValueDescriptor(descriptor.type) : undefined;
+ const valueDescriptor = descriptor ? AssetModelUtil.getValueDescriptor(descriptor.type) : undefined;
let content: TemplateResult = html``;
if (!valueDescriptor) {
@@ -304,10 +305,16 @@ export class OrEditAssetPanel extends LitElement {
label: Util.getMetaLabel(metaItem, descriptor!, this.asset.type!, true),
resizeVertical: true
};
- const provider = getValueHolderInputTemplateProvider(this.asset.type!, metaItem, descriptor, valueDescriptor, (detail: OrInputChangedEventDetail) => this._onMetaItemModified(attribute, metaItem, detail), options);
+
+ const standardInputProvider = getValueHolderInputTemplateProvider(this.asset.type!, metaItem, descriptor, valueDescriptor, (detail) => this._onMetaItemModified(attribute, metaItem, detail), options);
+ let provider = jsonFormsInputTemplateProvider(this.asset.type!, metaItem, descriptor, valueDescriptor, (detail) => this._onMetaItemModified(attribute, metaItem, detail), options, standardInputProvider);
+
+ if (!provider) {
+ provider = standardInputProvider;
+ }
if (provider.templateFunction) {
- content = provider.templateFunction(metaItem.value, false, false, false, false, undefined);
+ content = html`${until(provider.templateFunction(metaItem.value, false, false, false, false, undefined), ``)}`;
}
}
diff --git a/ui/component/or-attribute-input/package.json b/ui/component/or-attribute-input/package.json
index 7f880cb02..9ec2d2e42 100644
--- a/ui/component/or-attribute-input/package.json
+++ b/ui/component/or-attribute-input/package.json
@@ -16,6 +16,7 @@
"@openremote/or-mwc-components": "^1.0.3",
"@openremote/or-map": "^1.0.4",
"@openremote/or-translate": "^1.0.3",
+ "@openremote/or-json-forms": "^1.0.3",
"lit": "^2.0.0-rc.2"
},
"devDependencies": {
diff --git a/ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts b/ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts
new file mode 100644
index 000000000..d348c4d71
--- /dev/null
+++ b/ui/component/or-attribute-input/src/agent-link-json-forms-renderer.ts
@@ -0,0 +1,36 @@
+import {
+ RankedTester,
+ rankWith,
+ isStringControl,
+ or,
+ ControlProps,
+ mapStateToControlProps,
+ mapDispatchToControlProps
+} from "@jsonforms/core";
+import { JsonFormsStateContext, getTemplateWrapper, JsonFormsRendererRegistryEntry } from "@openremote/or-json-forms";
+import { html } from "lit";
+
+const agentIdTester: RankedTester = rankWith(
+ 6,
+ or(
+ isStringControl,
+ (uischema, schema) => {
+ return schema.format === "or-agent-id";
+ }
+ )
+);
+const agentIdRenderer = (state: JsonFormsStateContext, props: ControlProps) => {
+ props = {
+ ...props,
+ ...mapStateToControlProps({jsonforms: {...state}}, props),
+ ...mapDispatchToControlProps(state.dispatch)
+ };
+
+ const template = html`<div>AGENT PICKER</div>`;
+ return getTemplateWrapper(template, state, props);
+};
+
+export const agentIdRendererRegistryEntry: JsonFormsRendererRegistryEntry = {
+ tester: agentIdTester,
+ renderer: agentIdRenderer
+};
diff --git a/ui/component/or-attribute-input/src/index.ts b/ui/component/or-attribute-input/src/index.ts
index ea41e24e2..d25fafd91 100644
--- a/ui/component/or-attribute-input/src/index.ts
+++ b/ui/component/or-attribute-input/src/index.ts
@@ -8,6 +8,8 @@ import {
} from "lit";
import {customElement, property, query} from "lit/decorators.js";
import {ifDefined} from "lit/directives/if-defined";
+import {until} from "lit/directives/until";
+import {createRef, Ref, ref} from 'lit/directives/ref.js';
import {i18next, translate} from "@openremote/or-translate";
import {
Attribute,
@@ -17,13 +19,26 @@ import {
WellknownMetaItems,
SharedEvent,
ValueDescriptor,
- WellknownValueTypes
+ WellknownValueTypes,
+ AgentLink,
+ Agent,
+ AgentDescriptor,
+ AssetDescriptor,
+ NameHolder,
+ ValueHolder,
+ ValueDescriptorHolder
} from "@openremote/model";
import manager, {AssetModelUtil, DefaultColor4, subscribe, Util} from "@openremote/core";
import "@openremote/or-mwc-components/or-mwc-input";
-import {InputType, OrMwcInput, OrInputChangedEvent, ValueInputProviderOptions, ValueInputProviderGenerator, getValueHolderInputTemplateProvider, ValueInputProvider, OrInputChangedEventDetail} from "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrMwcInput, OrInputChangedEvent, ValueInputProviderOptions, ValueInputProviderGenerator, getValueHolderInputTemplateProvider, ValueInputProvider, OrInputChangedEventDetail, ValueInputTemplateFunction} from "@openremote/or-mwc-components/or-mwc-input";
import "@openremote/or-map";
import { geoJsonPointInputTemplateProvider } from "@openremote/or-map";
+import "@openremote/or-json-forms";
+import {OrJSONForms, StandardRenderers} from "@openremote/or-json-forms";
+import "./or-agent-picker";
+import {OrAgentPickerChangedEvent, OrAgentPickerLoadedEvent} from "./or-agent-picker";
+import { ErrorObject } from "@openremote/or-json-forms";
+import {agentIdRendererRegistryEntry} from "./agent-link-json-forms-renderer";
export class OrAttributeInputChangedEvent extends CustomEvent<OrAttributeInputChangedEventDetail> {
@@ -100,6 +115,133 @@ export function getHelperText(sending: boolean, error: boolean, timestamp: numbe
return i18next.t("updatedWithDate", { date: new Date(timestamp) });
}
+const jsonFormsAttributeRenderers = [...StandardRenderers, agentIdRendererRegistryEntry];
+
+export const jsonFormsInputTemplateProvider: (assetDescriptor: AssetDescriptor | string, valueHolder: NameHolder & ValueHolder<any> | undefined, valueHolderDescriptor: ValueDescriptorHolder | undefined, valueDescriptor: ValueDescriptor, valueChangeNotifier: (value: OrInputChangedEventDetail | undefined) => void, options: ValueInputProviderOptions, fallback: ValueInputProvider) => ValueInputProvider = (assetDescriptor, valueHolder, valueHolderDescriptor, valueDescriptor, valueChangeNotifier, options, fallback) => {
+
+ const disabled = !!(options && options.disabled);
+ const readonly = !!(options && options.readonly);
+ const label = options.label;
+
+ // Agent link needs some special handling as we need an agent picker no matter what
+ if (valueDescriptor.name === WellknownValueTypes.AGENTLINK) {
+
+ const templateFunction: ValueInputTemplateFunction = (value, focused, loading, sending, error, helperText) => {
+ const jsonForms: Ref<OrJSONForms> = createRef();
+ const editorDiv: Ref<HTMLDivElement> = createRef();
+ const errorDiv: Ref<HTMLDivElement> = createRef();
+ const agentLink = value as AgentLink;
+ const agentPickerLoadedDeferred: Util.Deferred<{agent: Agent, error: boolean}> = new Util.Deferred();
+ const schemaEditorPromise: PromiseLike<TemplateResult> = agentPickerLoadedDeferred.promise.then((agentAndError) => {
+
+ const onAgentLinkChanged = (dataAndErrors: {errors: ErrorObject[] | undefined, data: any}) => {
+ valueChangeNotifier({
+ value: dataAndErrors.data
+ });
+ };
+
+ const schema = JSON.parse("{\"$schema\":\"http://json-schema.org/draft-07/schema#\",\"definitions\":{\"ArrayPredicate-1\":{\"type\":\"object\",\"properties\":{\"index\":{\"type\":\"integer\"},\"lengthEquals\":{\"type\":\"integer\"},\"lengthGreaterThan\":{\"type\":\"integer\"},\"lengthLessThan\":{\"type\":\"integer\"},\"negated\":{\"type\":\"boolean\"},\"value\":{}}},\"ArrayPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/ArrayPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"ArrayPredicate\"}}}]},\"BooleanPredicate-1\":{\"type\":\"object\",\"properties\":{\"value\":{\"type\":\"boolean\"}}},\"BooleanPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/BooleanPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"BooleanPredicate\"}}}]},\"CalendarEventPredicate-1\":{\"type\":\"object\",\"properties\":{\"timestamp\":{\"type\":\"string\"}}},\"CalendarEventPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/CalendarEventPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"CalendarEventPredicate\"}}}]},\"DateTimePredicate-1\":{\"type\":\"object\",\"properties\":{\"negate\":{\"type\":\"boolean\"},\"operator\":{\"$ref\":\"#/definitions/Operator\"},\"rangeValue\":{\"type\":\"string\"},\"value\":{\"type\":\"string\"}}},\"DateTimePredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/DateTimePredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"DateTimePredicate\"}}}]},\"JsonPathFilter-1\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"},\"returnFirst\":{\"type\":\"boolean\"},\"returnLast\":{\"type\":\"boolean\"}}},\"JsonPathFilter-2\":{\"allOf\":[{\"$ref\":\"#/definitions/JsonPathFilter-1\"},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"jsonPath\"}}}]},\"Map(String,List(String))\":{\"type\":\"object\"},\"NumberPredicate-1\":{\"type\":\"object\",\"properties\":{\"negate\":{\"type\":\"boolean\"},\"operator\":{\"$ref\":\"#/definitions/Operator\"},\"rangeValue\":{\"type\":\"number\"},\"value\":{\"type\":\"number\"}}},\"NumberPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/NumberPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"NumberPredicate\"}}}]},\"ObjectNode\":{\"type\":\"object\"},\"Operator\":{\"type\":\"string\",\"enum\":[\"EQUALS\",\"GREATER_THAN\",\"GREATER_EQUALS\",\"LESS_THAN\",\"LESS_EQUALS\",\"BETWEEN\"]},\"RadialGeofencePredicate-1\":{\"type\":\"object\",\"properties\":{\"lat\":{\"type\":\"number\"},\"lng\":{\"type\":\"number\"},\"negated\":{\"type\":\"boolean\"},\"radius\":{\"type\":\"integer\"}}},\"RadialGeofencePredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/RadialGeofencePredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"RadialGeofencePredicate\"}}}]},\"RectangularGeofencePredicate-1\":{\"type\":\"object\",\"properties\":{\"latMax\":{\"type\":\"number\"},\"latMin\":{\"type\":\"number\"},\"lngMax\":{\"type\":\"number\"},\"lngMin\":{\"type\":\"number\"},\"negated\":{\"type\":\"boolean\"}}},\"RectangularGeofencePredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/RectangularGeofencePredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"RectangularGeofencePredicate\"}}}]},\"RegexValueFilter-1\":{\"type\":\"object\",\"properties\":{\"matchGroup\":{\"type\":\"integer\"},\"matchIndex\":{\"type\":\"integer\"},\"pattern\":{\"type\":\"object\",\"properties\":{\"flags\":{\"type\":\"integer\"},\"pattern\":{\"type\":\"string\"}}}}},\"RegexValueFilter-2\":{\"allOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-1\"},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"regex\"}}}]},\"StringPredicate-1\":{\"type\":\"object\",\"properties\":{\"caseSensitive\":{\"type\":\"boolean\"},\"match\":{\"type\":\"string\",\"enum\":[\"EXACT\",\"BEGIN\",\"END\",\"CONTAINS\"]},\"negate\":{\"type\":\"boolean\"},\"value\":{\"type\":\"string\"}}},\"StringPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/StringPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"StringPredicate\"}}}]},\"SubStringValueFilter-1\":{\"type\":\"object\",\"properties\":{\"beginIndex\":{\"type\":\"integer\"},\"endIndex\":{\"type\":\"integer\"}}},\"SubStringValueFilter-2\":{\"allOf\":[{\"$ref\":\"#/definitions/SubStringValueFilter-1\"},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"substring\"}}}]},\"ValueEmptyPredicate-1\":{\"type\":\"object\"},\"ValueEmptyPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/ValueEmptyPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"ValueEmptyPredicate\"}}}]},\"ValueNotEmptyPredicate-1\":{\"type\":\"object\"},\"ValueNotEmptyPredicate-2\":{\"allOf\":[{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-1\"},{\"type\":\"object\",\"properties\":{\"predicateType\":{\"const\":\"ValueNotEmptyPredicate\"}}}]},\"WebsocketHTTPSubscription-1\":{\"type\":\"object\",\"properties\":{\"body\":{},\"contentType\":{\"type\":\"string\"},\"headers\":{\"$ref\":\"#/definitions/Map(String,List(String))\"},\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"PUT\",\"POST\"]},\"type\":{\"type\":\"string\"},\"uri\":{\"type\":\"string\"}}},\"WebsocketHTTPSubscription-2\":{\"allOf\":[{\"$ref\":\"#/definitions/WebsocketHTTPSubscription-1\"},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"WebsocketHTTPSubscription\"}}}]},\"WebsocketSubscription\":{\"anyOf\":[{\"$ref\":\"#/definitions/WebsocketSubscription\"},{\"$ref\":\"#/definitions/WebsocketHTTPSubscription-2\"}]}},\"anyOf\":[{\"allOf\":[{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"oid\":{\"type\":\"string\"},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"SNMPAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"deviceEndpoint\":{\"type\":\"integer\"},\"deviceNodeId\":{\"type\":\"integer\"},\"deviceValue\":{\"type\":\"string\"},\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"ZWaveAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"deviceAddress\":{\"type\":\"integer\"},\"deviceValueLink\":{\"type\":\"string\"},\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"VelbusAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"DefaultAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"replayData\":{\"description\":\"Used to store 24h dataset of values that should be replayed (i.e. written to the linked attribute) in a continuous loop.\",\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"timestamp\":{\"type\":\"integer\"},\"value\":{}}}},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"SimulatorAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"websocketSubscriptions\":{\"description\":\"Array of WebsocketSubscriptions that should be executed when the linked attribute is linked; the subscriptions are executed in the order specified in the array.\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/WebsocketSubscription\"},{\"$ref\":\"#/definitions/WebsocketHTTPSubscription-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"WebsocketAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"contentType\":{\"type\":\"string\"},\"headers\":{\"$ref\":\"#/definitions/Map(String,List(String))\"},\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"method\":{\"type\":\"string\",\"enum\":[\"GET\",\"POST\",\"PUT\",\"DELETE\",\"OPTIONS\",\"PATCH\"]},\"pagingMode\":{\"type\":\"boolean\"},\"path\":{\"type\":\"string\"},\"pollingAttribute\":{\"type\":\"string\"},\"pollingMillis\":{\"type\":\"integer\"},\"queryParameters\":{\"$ref\":\"#/definitions/Map(String,List(String))\"},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"HTTPAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"requiredValue\":{\"type\":\"string\"},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"MockAgentLink\"}}}]},{\"allOf\":[{\"type\":\"object\",\"properties\":{\"actionGroupAddress\":{\"type\":\"string\"},\"dpt\":{\"type\":\"string\"},\"id\":{\"type\":\"string\",\"format\":\"or-agent-id\"},\"messageMatchFilters\":{\"description\":\"ValueFilters to apply to incoming messages prior to comparison with the messageMatchPredicate\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"messageMatchPredicate\":{\"anyOf\":[{\"$ref\":\"#/definitions/StringPredicate-2\"},{\"$ref\":\"#/definitions/BooleanPredicate-2\"},{\"$ref\":\"#/definitions/DateTimePredicate-2\"},{\"$ref\":\"#/definitions/NumberPredicate-2\"},{\"$ref\":\"#/definitions/RadialGeofencePredicate-2\"},{\"$ref\":\"#/definitions/RectangularGeofencePredicate-2\"},{\"$ref\":\"#/definitions/ArrayPredicate-2\"},{\"$ref\":\"#/definitions/ValueEmptyPredicate-2\"},{\"$ref\":\"#/definitions/ValueNotEmptyPredicate-2\"},{\"$ref\":\"#/definitions/CalendarEventPredicate-2\"}]},\"statusGroupAddress\":{\"type\":\"string\"},\"valueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Defines a value converter map to allow for basic value type conversion; the incoming value will be converted to JSON and if this string matches a key in the converter then the value of that key will be 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\"}]},\"valueFilters\":{\"description\":\"Defines ValueFilters to apply to an incoming value before it is written to a protocol linked attribute; this is particularly useful for generic protocols. The message should pass through the filters in array order\",\"type\":\"array\",\"items\":{\"anyOf\":[{\"$ref\":\"#/definitions/RegexValueFilter-2\"},{\"$ref\":\"#/definitions/SubStringValueFilter-2\"},{\"$ref\":\"#/definitions/JsonPathFilter-2\"}]}},\"writeValue\":{\"type\":\"string\",\"description\":\"String to be used for attribute writes and can contain '{$value}' placeholders to allow the written value to be injected into the string or to even hardcode the value written to the protocol\"},\"writeValueConverter\":{\"allOf\":[{\"$ref\":\"#/definitions/ObjectNode\"},{\"description\":\"Similar to valueConverter but will be applied to outgoing values allowing for the opposite conversion\"}]}}},{\"type\":\"object\",\"properties\":{\"type\":{\"const\":\"KNXAgentLink\"}}}]}]}");
+
+ return html`
+ ${agentAndError.error
+ ? html``
+ : html`
+ <div>
+ <or-json-forms .renderers="${jsonFormsAttributeRenderers}" ${ref(jsonForms)}
+ .schema="${schema}" .onChange="${onAgentLinkChanged}"
+ .data="${agentLink}"></or-json-forms>
+ </div>
+ `
+ }
+ `
+ });
+
+ const onAgentPickerLoaded = (agents: Agent[]) => {
+ console.log("Picker loaded");
+ if (!agents) {
+ console.warn("Failed to load agent assets for agent picker");
+ return;
+ }
+
+ if (!agentLink) {
+ // Just remove disabled class
+ editorDiv.value!.classList.remove("disabled");
+ return;
+ }
+
+ const matchedAgent = agents.find(agent => agent.id === agentLink.id);
+ let error = false;
+
+ if (!matchedAgent) {
+ console.warn("Linked agent cannot be found: " + agentLink);
+ error = true;
+ } else {
+ // Check agent link type
+ const agentDescriptor = AssetModelUtil.getAssetDescriptor(matchedAgent.type) as AgentDescriptor;
+ if (!agentDescriptor) {
+ console.warn("Failed to load agent descriptor for agent link: " + agentLink);
+ error = true;
+ } else if (agentDescriptor.agentLinkType !== agentLink.type) {
+ console.warn("Agent link type does not match agent descriptor agent link type: " + agentLink);
+ error = true;
+ }
+ }
+
+ if (matchedAgent) {
+ if (!error) {
+ editorDiv.value!.classList.remove("disabled");
+ }
+ agentPickerLoadedDeferred.resolve({
+ agent: matchedAgent,
+ error: error
+ });
+ }
+ };
+
+ const onAgentChanged = (agent: Agent) => {
+ console.log("AGENT CHANGED! " + (agent ? agent.id : ""));
+ let agentLink: AgentLink | undefined;
+
+ if (agent) {
+ const agentDescriptor = AssetModelUtil.getAssetDescriptor(agent.type) as AgentDescriptor;
+ agentLink = {
+ id: agent.id,
+ type: agentDescriptor.agentLinkType!
+ };
+ }
+
+ valueChangeNotifier({
+ value: agentLink
+ });
+ };
+
+ return html`
+ <style>
+ .disabled {
+ opacity: 0.5;
+ pointer-events: none;
+ }
+ </style>
+ <div ${ref(editorDiv)} class="disabled">
+ <div>
+ <or-agent-picker .agentId="${agentLink ? agentLink.id : undefined}" @or-agent-picker-loaded="${(ev: OrAgentPickerLoadedEvent) => onAgentPickerLoaded(ev.detail)}" @or-agent-picker-changed="${(ev: OrAgentPickerChangedEvent) => onAgentChanged(ev.detail)}"></or-agent-picker>
+ </div>
+ ${until(schemaEditorPromise, html``)}
+ </div>
+ `;
+ };
+
+ return {
+ templateFunction: templateFunction,
+ supportsHelperText: false,
+ supportsLabel: false,
+ supportsSendButton: false
+ };
+ }
+
+ return fallback;
+};
+
const DEFAULT_TIMEOUT = 5000;
// TODO: Add support for attribute not found and attribute deletion/addition
@@ -519,15 +661,21 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
return;
}
- // Fallback to simple input provider
- const valueChangeHandler = (detail: OrInputChangedEventDetail) => {
- if (detail.enterPressed || !this._templateProvider || !this.showButton || !this._templateProvider.supportsSendButton) {
+ // Use json forms with fallback to simple input provider
+ const valueChangeHandler = (detail: OrInputChangedEventDetail | undefined) => {
+ if (detail && (detail.enterPressed || !this._templateProvider || !this.showButton || !this._templateProvider.supportsSendButton)) {
this._onInputValueChanged(detail.value);
} else {
- this._newValue = detail.value;
+ this._newValue = detail ? detail.value : undefined;
}
};
- this._templateProvider = getValueHolderInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (e: OrInputChangedEventDetail) => valueChangeHandler(e), options);
+
+ const standardInputProvider = getValueHolderInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (e) => valueChangeHandler(e), options);
+ this._templateProvider = jsonFormsInputTemplateProvider(this.assetType, this.attribute, this._attributeDescriptor, valueDescriptor, (v: any) => this._onInputValueChanged(v), options, standardInputProvider);
+
+ if (!this._templateProvider) {
+ this._templateProvider = standardInputProvider;
+ }
}
public getLabel(): string | undefined {
@@ -569,7 +717,7 @@ export class OrAttributeInput extends subscribe(manager)(translate(i18next)(LitE
const buttonIcon = !this.showButton ? (this.disableButton ? undefined : "") : this._writeTimeoutHandler ? "send-clock" : "send";
if (this._templateProvider && this._templateProvider.templateFunction) {
- content = this._templateProvider.templateFunction(value, focus, loading, !!this._writeTimeoutHandler, this._sendError, this._templateProvider.supportsHelperText ? helperText : undefined);
+ content = html`${until(this._templateProvider.templateFunction(value, focus, loading, !!this._writeTimeoutHandler, this._sendError, this._templateProvider.supportsHelperText ? helperText : undefined), ``)}`;
} else {
content = html`<or-translate .value="attributeUnsupported"></or-translate>`;
}
diff --git a/ui/component/or-attribute-input/src/or-agent-picker.ts b/ui/component/or-attribute-input/src/or-agent-picker.ts
new file mode 100644
index 000000000..bf798a411
--- /dev/null
+++ b/ui/component/or-attribute-input/src/or-agent-picker.ts
@@ -0,0 +1,137 @@
+import {html, LitElement, PropertyValues} from "lit";
+import {customElement, property, state} from "lit/decorators.js";
+import {manager, OREvent} from "@openremote/core";
+import {Agent} from "@openremote/model";
+import "@openremote/or-mwc-components/or-mwc-input";
+import {InputType, OrInputChangedEvent} from "@openremote/or-mwc-components/or-mwc-input";
+import {i18next} from "@openremote/or-translate";
+
+export class OrAgentPickerLoadedEvent extends CustomEvent<Agent[]> {
+
+ public static readonly NAME = "or-agent-picker-loaded";
+
+ constructor(value: Agent[]) {
+ super(OrAgentPickerLoadedEvent.NAME, {
+ detail: value,
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+export class OrAgentPickerChangedEvent extends CustomEvent<Agent> {
+
+ public static readonly NAME = "or-agent-picker-changed";
+
+ constructor(value?: Agent) {
+ super(OrAgentPickerChangedEvent.NAME, {
+ detail: value,
+ bubbles: true,
+ composed: true
+ });
+ }
+}
+
+declare global {
+ export interface HTMLElementEventMap {
+ [OrAgentPickerChangedEvent.NAME]: OrAgentPickerChangedEvent;
+ [OrAgentPickerLoadedEvent.NAME]: OrAgentPickerLoadedEvent;
+ }
+}
+
+function getAgents(): Promise<Agent[]> {
+ return manager.rest.api.AssetResource.queryAssets({
+ tenant: {
+ realm: manager.displayRealm
+ },
+ types: [
+ "Agent"
+ ],
+ select: {
+ excludeParentInfo: true,
+ excludePath: true,
+ excludeAttributes: true
+ }
+ }).then(response => response.data as Agent[]);
+}
+
+/**
+ * This function creates a short lived cache for loading the list of agents; this is useful when multiple instances
+ * of this control are used in a single UI
+ */
+let agents: Agent[] | undefined;
+let loadingPromise: Promise<Agent[]> | undefined;
+const timeout = 2000;
+function loadAgents(): PromiseLike<Agent[]> {
+
+ if (agents) {
+ return Promise.resolve(agents);
+ }
+
+ if (loadingPromise) {
+ return loadingPromise;
+ }
+
+ loadingPromise = getAgents()
+ .then(agnts => {
+ agents = agnts;
+ manager.addListener((ev: OREvent) => {
+ switch (ev) {
+ case OREvent.DISPLAY_REALM_CHANGED:
+ agents = undefined;
+ loadingPromise = undefined;
+ break;
+ }
+ });
+ manager.events!.subscribeAssetEvents(undefined, false, undefined, (assetEvent) => {
+ if (assetEvent.asset && assetEvent.asset.type!.endsWith("Agent")) {
+ agents = undefined;
+ loadingPromise = undefined;
+ }
+ })
+
+ return agnts;
+ });
+
+ return loadingPromise;
+}
+
+@customElement("or-agent-picker")
+export class OrAgentPicker extends LitElement {
+
+ @property({type: String})
+ public agentId?: string;
+
+ @property({type: Boolean})
+ public disabled: boolean = false;
+
+ @state()
+ protected agents?: Agent[];
+
+ connectedCallback() {
+ super.connectedCallback();
+ loadAgents().then((agents) => {
+ this.agents = agents;
+ this.dispatchEvent(new OrAgentPickerLoadedEvent(agents));
+ });
+ }
+
+ render() {
+
+ if (!this.agents) {
+ return html`
+ <or-mwc-input .disabled="${true}" .type="${InputType.SELECT}"></or-mwc-input>
+ `;
+ }
+
+ const agentOptions: [string ,string][] = this.agents ? this.agents.map(agent => [agent.id!, agent.name + " (" + agent.id + ")"]) : [];
+
+ return html`
+ <or-mwc-input .disabled="${this.disabled}" @or-mwc-input-changed="${(ev: OrInputChangedEvent) => this.onAgentChanged(ev.detail.value as string)}" type="${InputType.SELECT}" .value="${this.agentId}" .placeholder="${agentOptions.length > 0 ? "" : i18next.t("loading")}" .options="${agentOptions}"></or-mwc-input>
+ `;
+ }
+
+ onAgentChanged(id?: string) {
+ this.dispatchEvent(new OrAgentPickerChangedEvent(this.agents?.find(agent => agent.id === id)));
+ }
+}
diff --git a/ui/component/or-attribute-input/tsconfig.json b/ui/component/or-attribute-input/tsconfig.json
index bcce51453..210ada43f 100644
--- a/ui/component/or-attribute-input/tsconfig.json
+++ b/ui/component/or-attribute-input/tsconfig.json
@@ -13,6 +13,7 @@
{ "path": "../core" },
{ "path": "../or-translate" },
{ "path": "../or-map" },
- { "path": "../or-mwc-components" }
+ { "path": "../or-mwc-components" },
+ { "path": "../or-json-forms" }
]
}
diff --git a/ui/component/or-json-forms/package.json b/ui/component/or-json-forms/package.json
index 03a6f4a96..ffb2433d4 100644
--- a/ui/component/or-json-forms/package.json
+++ b/ui/component/or-json-forms/package.json
@@ -19,7 +19,7 @@
"haunted": "^4.8.1"
},
"devDependencies": {
- "@jsonforms/core": "^3.0.0-alpha.0",
+ "@jsonforms/core": "^3.0.0-alpha.1",
"tslint": ">=5.11.0",
"typescript": ">=4.1.3",
"webpack": "^5.16.0",
diff --git a/ui/component/or-json-forms/src/controls/control-base-element.ts b/ui/component/or-json-forms/src/controls/control-base-element.ts
index ae7e2e31d..7e80d037a 100644
--- a/ui/component/or-json-forms/src/controls/control-base-element.ts
+++ b/ui/component/or-json-forms/src/controls/control-base-element.ts
@@ -4,11 +4,9 @@ import {
createId,
isControl,
JsonSchema,
- Labels,
mapDispatchToControlProps,
OwnPropsOfControl,
- removeId,
- StatePropsOfControl
+ removeId
} from "@jsonforms/core";
import {PropertyValues} from "lit";
import {property} from "lit/decorators.js";
@@ -17,7 +15,7 @@ import {BaseElement} from "../base-element";
export abstract class ControlBaseElement extends BaseElement<ControlElement, ControlProps> implements OwnPropsOfControl, ControlProps {
@property()
- public label!: string | Labels;
+ public label!: string;
@property()
public description?: string | undefined;
diff --git a/ui/component/or-json-forms/src/controls/control-input-element.ts b/ui/component/or-json-forms/src/controls/control-input-element.ts
index ce8f35d5d..3dc5ad379 100644
--- a/ui/component/or-json-forms/src/controls/control-input-element.ts
+++ b/ui/component/or-json-forms/src/controls/control-input-element.ts
@@ -5,7 +5,7 @@ import {ControlBaseElement} from "./control-base-element";
import {baseStyle} from "../styles";
import { isBooleanControl,
isEnumControl, isIntegerControl, isNumberControl, isOneOfEnumControl, isRangeControl, isStringControl, JsonSchema, JsonSchema7 } from "@jsonforms/core";
-import {isEnumArray} from "../renderers";
+import {isEnumArray} from "../standardRenderers";
// language=CSS
const style = css`
diff --git a/ui/component/or-json-forms/src/index.ts b/ui/component/or-json-forms/src/index.ts
index c9e81cc05..dd1dbedb1 100644
--- a/ui/component/or-json-forms/src/index.ts
+++ b/ui/component/or-json-forms/src/index.ts
@@ -22,10 +22,11 @@ import {
StatePropsOfJsonFormsRenderer,
UISchemaElement
} from "@jsonforms/core";
-import {renderers} from "./renderers";
+import {getTemplateWrapper, StandardRenderers} from "./standardRenderers";
import {getTemplateFromProps} from "./util";
import {useEffect, useMemo, useReducer, useRef} from "haunted";
import {baseStyle} from "./styles";
+import { Util } from "@openremote/core";
declare global {
interface SymbolConstructor {
@@ -33,7 +34,7 @@ declare global {
}
}
-export {ErrorObject};
+export {ErrorObject, StandardRenderers, getTemplateWrapper, JsonFormsRendererRegistryEntry};
export interface JsonFormsStateContext extends JsonFormsSubStates {
dispatch: Dispatch<CoreActions>;
@@ -89,7 +90,7 @@ export class OrJSONForms extends HauntedLitElement implements OwnPropsOfJsonForm
public data: any;
@property({type: Array})
- public renderers?: JsonFormsRendererRegistryEntry[] = renderers;
+ public renderers?: JsonFormsRendererRegistryEntry[] = StandardRenderers;
@property({type: Array})
public cells?: JsonFormsCellRendererRegistryEntry[];
@@ -116,7 +117,7 @@ export class OrJSONForms extends HauntedLitElement implements OwnPropsOfJsonForm
render() {
const schemaToUse = useMemo(
- () => (this.schema !== undefined ? this.schema : generateJsonSchema(this.data)),
+ () => (this.schema !== undefined ? this.schema : this.data !== undefined ? generateJsonSchema(this.data) : {}),
[this.schema, this.data]
);
@@ -130,7 +131,7 @@ export class OrJSONForms extends HauntedLitElement implements OwnPropsOfJsonForm
undefined,
() => coreReducer(
{
- ajv: createAjv({useDefaults: true}),
+ ajv: createAjv({useDefaults: true, format: false}),
data: {},
schema: schemaToUse,
uischema: uischemaToUse
@@ -168,7 +169,7 @@ export class OrJSONForms extends HauntedLitElement implements OwnPropsOfJsonForm
}), [core, this.renderers, this.cells, config, this.readonly]);
useEffect(() => {
- if (this.onChange) {
+ if (this.onChange && !Util.objectsEqual(core.data, this.data, true)) {
this.onChange({data: core.data, errors: core.errors});
}
}, [core.data, core.errors]);
diff --git a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
index fd070f9c1..eb3a9f913 100644
--- a/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
+++ b/ui/component/or-json-forms/src/layouts/layout-vertical-element.ts
@@ -1,4 +1,4 @@
-import {computeLabel, createDefaultValue, isControl, isPlainLabel, JsonFormsState, LayoutProps, mapStateToControlProps,
+import {computeLabel, createDefaultValue, isControl, JsonFormsState, LayoutProps, mapStateToControlProps,
OwnPropsOfControl, OwnPropsOfRenderer, RankedTester, rankWith, StatePropsOfControl, uiTypeIs, update, VerticalLayout} from "@jsonforms/core";
import {css, html, PropertyValues, TemplateResult, unsafeCSS} from "lit";
import {customElement} from "lit/decorators.js";
@@ -164,7 +164,7 @@ export class LayoutVerticalElement extends LayoutBaseElement<VerticalLayout> {
let selectedParameter: StatePropsOfControl | undefined;
const listItems: ListItem[] = optionalProps.map(props => {
- const labelStr = isPlainLabel(props.label) ? computeLabel(props.label, !!props.required, false) : props.label.default;
+ const labelStr = computeLabel(props.label, !!props.required, false);
return {
text: labelStr,
value: labelStr,
diff --git a/ui/component/or-json-forms/src/renderers.ts b/ui/component/or-json-forms/src/standardRenderers.ts
similarity index 94%
rename from ui/component/or-json-forms/src/renderers.ts
rename to ui/component/or-json-forms/src/standardRenderers.ts
index 429109a17..971218110 100644
--- a/ui/component/or-json-forms/src/renderers.ts
+++ b/ui/component/or-json-forms/src/standardRenderers.ts
@@ -17,7 +17,6 @@ import {
isNumberControl,
isObjectControl,
isOneOfEnumControl,
- isPlainLabel,
isStringControl,
isTimeControl,
JsonFormsRendererRegistryEntry,
@@ -31,7 +30,6 @@ import {
mapStateToLayoutProps,
or,
OwnPropsOfRenderer,
- Paths,
RankedTester,
rankWith,
RendererProps,
@@ -147,7 +145,7 @@ export const objectControlRenderer = (state: JsonFormsStateContext, props: Contr
rootSchema
);
- const labelStr = isPlainLabel(label) ? computeLabel(label, !!required, false) : label.default;
+ const labelStr = computeLabel(label, !!required, false);
const contentProps: OwnPropsOfRenderer & WithTitle & WithRequired & DispatchPropsOfControl = {
title: labelStr,
visible: visible,
@@ -183,15 +181,8 @@ export const anyOfControlRenderer = (state: JsonFormsStateContext, props: Contro
rootSchema
} = toControlDetailProps(state, props);
- // mapStateToAnyOfProps has issues with $ref in allOfs so resolve them before calling
const anyOfSchema = resolveSubSchemas(schema, rootSchema, "anyOf");
- for(let i=0; i<anyOfSchema.anyOf!.length; i++) {
- if (anyOfSchema.anyOf![i].allOf) {
- anyOfSchema.anyOf![i] = resolveSubSchemas(anyOfSchema.anyOf![i], rootSchema, "allOf");
- }
- }
-
const anyOfProps = mapStateToCombinatorRendererProps({jsonforms: {...state}}, {
schema: anyOfSchema,
path: path,
@@ -203,7 +194,7 @@ export const anyOfControlRenderer = (state: JsonFormsStateContext, props: Contro
uischemas: uischemas
}, "anyOf");
- if (anyOfProps.indexOfFittingSchema < 0) {
+ if (anyOfProps.indexOfFittingSchema === undefined) {
console.warn("Cannot match anyOf schema to instance data");
return html`<or-json-forms-unknown class="item-container"></or-json-forms-unknown>`;
}
@@ -261,7 +252,7 @@ export const allOfControlRenderer = (state: JsonFormsStateContext, props: Contro
const allOfSchema = resolveSubSchemas(schema, rootSchema, 'allOf');
- const allOfProps = mapStateToAllOfProps({jsonforms: {...state}}, {
+ const allOfProps = mapStateToCombinatorRendererProps({jsonforms: {...state}}, {
schema: allOfSchema,
path: path,
visible: visible,
@@ -270,7 +261,7 @@ export const allOfControlRenderer = (state: JsonFormsStateContext, props: Contro
renderers: renderers,
cells: cells,
uischemas: uischemas
- });
+ }, "allOf");
const allOfRenderInfos = createCombinatorRenderInfos(
allOfSchema.allOf!,
@@ -343,8 +334,7 @@ export function getTemplateWrapper(elementTemplate: TemplateResult, state: JsonF
`;
}
-
-export const renderers: JsonFormsRendererRegistryEntry[] = [
+export const StandardRenderers: JsonFormsRendererRegistryEntry[] = [
{tester: verticalLayoutTester, renderer: verticalLayoutRenderer},
{tester: inputControlTester, renderer: inputControlRenderer},
diff --git a/ui/component/or-json-forms/src/util.ts b/ui/component/or-json-forms/src/util.ts
index acaddfa28..464c26289 100644
--- a/ui/component/or-json-forms/src/util.ts
+++ b/ui/component/or-json-forms/src/util.ts
@@ -12,19 +12,20 @@ import {
JsonFormsRendererRegistryEntry,
JsonFormsState,
JsonSchema,
+ JsonSchema4,
mapStateToControlProps,
mapStateToControlWithDetailProps,
OwnPropsOfControl,
OwnPropsOfRenderer,
Resolve,
+ resolveSchema,
resolveSubSchemas,
StatePropsOfCombinator,
StatePropsOfControl,
StatePropsOfControlWithDetail,
} from "@jsonforms/core";
-import { ErrorObject } from "ajv";
import {html, TemplateResult} from "lit";
-import {JsonFormsStateContext} from "./index";
+import {ErrorObject, JsonFormsStateContext} from "./index";
export function getTemplateFromProps<T extends OwnPropsOfRenderer>(state: JsonFormsStateContext | undefined, props: T | undefined): TemplateResult {
if (!state || !props) {
@@ -146,8 +147,8 @@ function getSchemaObjectProperties(schema: JsonSchema): [string, JsonSchema][] {
}
/**
- * Copied from eclipse source code as there is a bug (https://github.com/eclipsesource/jsonforms/issues/1787)
- * which means indexOfFittingSchema always returns 0 if there is only a const error
+ * Copied from eclipse source code to inject global definitions into the validating schema otherwise AJV will fail
+ * to compile the schema - not perfect but works for our cases
*/
export function mapStateToCombinatorRendererProps(
state: JsonFormsState,
@@ -193,7 +194,11 @@ export function mapStateToCombinatorRendererProps(
// element
for (let i = 0; i < _schema[keyword]!.length; i++) {
try {
- const valFn = ajv.compile(_schema[keyword]![i]);
+ const schema = {
+ definitions: rootSchema.definitions,
+ ..._schema[keyword]![i]
+ } as JsonSchema;
+ const valFn = ajv.compile(schema);
valFn(data);
if (dataIsValid(valFn.errors!)) {
indexOfFittingSchema = i;
@@ -217,3 +222,41 @@ export function mapStateToCombinatorRendererProps(
};
}
+export function resolveSubSchemasRecursive(
+ schema: JsonSchema,
+ rootSchema: JsonSchema,
+ keyword?: CombinatorKeyword
+): JsonSchema {
+ const combinators: string[] = keyword ? [keyword] : ["allOf", "anyOf", "oneOf"];
+
+ if (schema.$ref) {
+ return resolveSubSchemasRecursive(resolveSchema(rootSchema, schema.$ref), rootSchema);
+ }
+
+ combinators.forEach((combinator) => {
+ const schemas = (schema as any)[combinator] as JsonSchema[];
+
+ if (schemas) {
+ (schema as any)[combinator] = schemas.map(subSchema =>
+ resolveSubSchemasRecursive(subSchema, rootSchema)
+ );
+ }
+ });
+
+ if (schema.items) {
+ if (Array.isArray(schema.items)) {
+ schema.items = (schema.items as JsonSchema4[]).map((itemSchema) => resolveSubSchemasRecursive(itemSchema, rootSchema) as JsonSchema4);
+ } else {
+ schema.items = resolveSubSchemasRecursive(schema.items as JsonSchema, rootSchema);
+ }
+ }
+
+ if (schema.properties) {
+ Object.keys(schema.properties).forEach((prop) =>
+ schema.properties![prop] = resolveSubSchemasRecursive(schema.properties![prop], rootSchema)
+ );
+ }
+
+ return schema;
+}
+
diff --git a/ui/component/or-map/src/index.ts b/ui/component/or-map/src/index.ts
index b5a4fd67b..93747d56a 100644
--- a/ui/component/or-map/src/index.ts
+++ b/ui/component/or-map/src/index.ts
@@ -185,7 +185,21 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
const compact = !!(options && options.compact);
const comfortable = !!(options && options.comfortable);
const centerControl = new CenterControl();
- const coordinatesControl = new CoordinatesControl(disabled, valueChangeNotifier);
+
+ const valueChangeHandler = (value: LngLatLike | undefined) => {
+ if (!valueChangeNotifier) {
+ return;
+ }
+ if (value) {
+ valueChangeNotifier({
+ value: value
+ });
+ } else {
+ valueChangeNotifier(undefined);
+ }
+ };
+
+ const coordinatesControl = new CoordinatesControl(disabled, valueChangeHandler);
const templateFunction: ValueInputTemplateFunction = (value, focused, loading, sending, error, helperText) => {
let pos: { lng: number, lat: number } | undefined;
@@ -205,12 +219,6 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
let dialog: OrMwcDialog | undefined;
- const updateHandler = () => {
- if (valueChangeNotifier) {
- valueChangeNotifier(Util.getGeoJSONPoint(pos));
- }
- };
-
const setPos = (lngLat: LngLatLike | undefined) => {
if (readonly || disabled) {
return;
@@ -227,7 +235,7 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
const centerStr = center ? center.join(", ") : undefined;
coordinatesControl.value = centerStr;
} else {
- updateHandler();
+ valueChangeHandler(pos as LngLatLike);
}
};
@@ -264,14 +272,14 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
content: i18next.t("none"),
action: () => {
setPos(undefined);
- updateHandler();
+ valueChangeHandler(pos as LngLatLike);
}
},
{
actionName: "ok",
content: i18next.t("ok"),
action: () => {
- updateHandler();
+ valueChangeHandler(pos as LngLatLike);
}
},
{
@@ -293,7 +301,7 @@ export const geoJsonPointInputTemplateProvider: ValueInputProviderGenerator = (a
}
</style>
<div id="geo-json-point-input-compact-wrapper">
- <or-mwc-input .comfortable="${comfortable}" .type="${InputType.TEXT}" .value="${centerStr}" .pattern="${CoordinatesRegexPattern}" @keyup="${(e: KeyboardEvent) => getCoordinatesInputKeyHandler(valueChangeNotifier)(e)}"></or-mwc-input>
+ <or-mwc-input .comfortable="${comfortable}" .type="${InputType.TEXT}" .value="${centerStr}" .pattern="${CoordinatesRegexPattern}" @keyup="${(e: KeyboardEvent) => getCoordinatesInputKeyHandler(valueChangeHandler)(e)}"></or-mwc-input>
<or-mwc-input style="width: auto;" .type="${InputType.BUTTON}" compact icon="crosshairs-gps" @click="${onClick}"></or-mwc-input>
</div>
`;
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 7e9830adc..95d44bae7 100644
--- a/ui/component/or-mwc-components/src/or-mwc-input.ts
+++ b/ui/component/or-mwc-components/src/or-mwc-input.ts
@@ -143,9 +143,9 @@ export interface ValueInputProvider {
supportsSendButton: boolean;
}
-export type ValueInputTemplateFunction = ((value: any, focused: boolean, loading: boolean, sending: boolean, error: boolean, helperText: string | undefined) => TemplateResult) | undefined;
+export type ValueInputTemplateFunction = ((value: any, focused: boolean, loading: boolean, sending: boolean, error: boolean, helperText: string | undefined) => TemplateResult | PromiseLike<TemplateResult>) | undefined;
-export type ValueInputProviderGenerator = (assetDescriptor: AssetDescriptor | string, valueHolder: NameHolder & ValueHolder<any> | undefined, valueHolderDescriptor: ValueDescriptorHolder | undefined, valueDescriptor: ValueDescriptor, valueChangeNotifier: (value: OrInputChangedEventDetail | any | undefined) => void, options: ValueInputProviderOptions) => ValueInputProvider;
+export type ValueInputProviderGenerator = (assetDescriptor: AssetDescriptor | string, valueHolder: NameHolder & ValueHolder<any> | undefined, valueHolderDescriptor: ValueDescriptorHolder | undefined, valueDescriptor: ValueDescriptor, valueChangeNotifier: (value: OrInputChangedEventDetail | undefined) => void, options: ValueInputProviderOptions) => ValueInputProvider;
function inputTypeSupportsButton(inputType: InputType): boolean {
return inputType === InputType.NUMBER
diff --git a/yarn.lock b/yarn.lock
index 263a2c161..7ce58b27d 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -985,10 +985,10 @@
dependencies:
"@fortawesome/fontawesome-common-types" "^0.2.35"
-"@jsonforms/core@^3.0.0-alpha.0":
- version "3.0.0-alpha.0"
- resolved "https://registry.yarnpkg.com/@jsonforms/core/-/core-3.0.0-alpha.0.tgz#c960e37ebf47c17c4ef2839b3410ee140e3909be"
- integrity sha512-CIUh7uDlhH8a5/zk6YF5LXAbmu299eYBTJXLzjZSnCL1lyZtckCnEGvWzF8Y7A9cgAg18URRyjyloxfT0ARaRQ==
+"@jsonforms/core@^3.0.0-alpha.1":
+ version "3.0.0-alpha.1"
+ resolved "https://registry.yarnpkg.com/@jsonforms/core/-/core-3.0.0-alpha.1.tgz#2330aaef0f5d2458109c7eb8ac715edeba33c027"
+ integrity sha512-wiPk8kMQr91FaBeBSj7U/jPhTH52yF0GC1Z5QIyrexVWz/QP9xwoAZpRaXM1TL4nNzX0Cgl2WBRedxB/4LmNmA==
dependencies:
"@types/json-schema" "^7.0.3"
ajv "^6.10.2"