100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Add AssetPredictedDataPointEvent for CRUD notification of predicted data changes (#2522)
Eric Bariaux1ba2c3d80487
diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.javaindex 166365c00..8c3bc1a84 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetPredictedDatapointService.java@@ -22,12 +22,21 @@ package org.openremote.manager.datapoint;import org.openremote.agent.protocol.ProtocolPredictedDatapointService;import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.event.ClientEventService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebService;+import org.openremote.model.Constants;import org.openremote.model.Container;+import org.openremote.model.asset.Asset;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.Attribute;+import org.openremote.model.datapoint.AssetPredictedDatapointEvent;import org.openremote.model.datapoint.AssetPredictedDatapoint;import org.openremote.model.datapoint.ValueDatapoint;+import org.openremote.model.event.shared.EventSubscription;+import org.openremote.model.event.shared.EventFilter;+import org.openremote.model.security.ClientRole;+import org.openremote.model.value.MetaItemType;import java.sql.Timestamp;import java.time.Duration;@@ -44,6 +53,9 @@ import static java.time.temporal.ChronoUnit.HOURS;public class AssetPredictedDatapointService extends AbstractDatapointService<AssetPredictedDatapoint> implements ProtocolPredictedDatapointService {private static final Logger LOG = Logger.getLogger(AssetPredictedDatapointService.class.getName());+ protected ClientEventService clientEventService;+ protected ManagerIdentityService identityService;+ protected AssetStorageService assetStorageService;@Overridepublic int getPriority() {@@ -53,6 +65,47 @@ public class AssetPredictedDatapointService extends AbstractDatapointService<Ass@Overridepublic void init(Container container) throws Exception {super.init(container);+ clientEventService = container.getService(ClientEventService.class);+ identityService = container.getService(ManagerIdentityService.class);+ assetStorageService = container.getService(AssetStorageService.class);++ clientEventService.addSubscriptionAuthorizer((requestedRealm, auth, subscription) -> {+ if (!subscription.isEventType(AssetPredictedDatapointEvent.class) || auth == null) {+ return false;+ }++ @SuppressWarnings("unchecked")+ EventSubscription<AssetPredictedDatapointEvent> predictedDatapointSubscription =+ (EventSubscription<AssetPredictedDatapointEvent>) subscription;++ if (identityService.getIdentityProvider().isRestrictedUser(auth)) {+ EventFilter<AssetPredictedDatapointEvent> existingFilter = predictedDatapointSubscription.getFilter();+ predictedDatapointSubscription.setFilter(event -> {+ AssetPredictedDatapointEvent filteredEvent = existingFilter == null ? event : existingFilter.apply(event);+ if (filteredEvent == null) {+ return null;+ }++ String assetId = filteredEvent.getRef().getId();+ String attributeName = filteredEvent.getRef().getName();++ if (!assetStorageService.isUserAsset(auth.getUserId(), assetId)) {+ return null;+ }++ Asset<?> asset = assetStorageService.find(assetId, true);+ Attribute<?> attribute = asset != null ? asset.getAttribute(attributeName).orElse(null) : null;+ if (attribute == null || !attribute.getMeta().getValue(MetaItemType.ACCESS_RESTRICTED_READ).orElse(false)) {+ return null;+ }++ return filteredEvent;+ });+ }++ return auth.hasResourceRoleOrIsSuperUser(ClientRole.READ_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)+ && identityService.getIdentityProvider().isRealmActiveAndAccessible(auth, requestedRealm);+ });container.getService(ManagerWebService.class).addApiSingleton(new AssetPredictedDatapointResourceImpl(@@ -67,7 +120,7 @@ public class AssetPredictedDatapointService extends AbstractDatapointService<Ass@Overridepublic void start(Container container) throws Exception {dataPointsPurgeScheduledFuture = scheduledExecutorService.scheduleAtFixedRate(- this::purgeDataPoints,+ this::purgeDatapoints,getFirstPurgeMillis(timerService.getNow()),Duration.ofDays(1).toMillis(), TimeUnit.MILLISECONDS);@@ -79,22 +132,36 @@ public class AssetPredictedDatapointService extends AbstractDatapointService<Asspublic void updateValue(String assetId, String attributeName, Object value, LocalDateTime timestamp) {upsertValue(assetId, attributeName, value, timestamp);+ publishPredictedDatapointsEvent(assetId, attributeName);}public void updateValues(String assetId, String attributeName, List<ValueDatapoint<?>> valuesAndTimestamps) {- persistenceService.doTransaction(em -> upsertValues(assetId, attributeName, valuesAndTimestamps));+ if (valuesAndTimestamps == null || valuesAndTimestamps.isEmpty()) {+ return;+ }++ upsertValues(assetId, attributeName, valuesAndTimestamps);+ publishPredictedDatapointsEvent(assetId, attributeName);}public void purgeValues(String assetId, String attributeName) {- persistenceService.doTransaction(em -> em.createQuery(+ int deleted = persistenceService.doReturningTransaction(em -> em.createQuery("delete from " + getDatapointClass().getSimpleName() + " dp where dp.assetId=?1 and dp.attributeName=?2").setParameter(1, assetId).setParameter(2, attributeName).executeUpdate());++ if (deleted > 0) {+ publishPredictedDatapointsEvent(assetId, attributeName);+ }}public void purgeValuesBefore(String assetId, String attributeName, Instant timestamp) {- persistenceService.doTransaction(em -> em.createQuery(+ int deleted = persistenceService.doReturningTransaction(em -> em.createQuery("delete from " + getDatapointClass().getSimpleName() + " dp where dp.assetId=?1 and dp.attributeName=?2 and dp.timestamp<?3").setParameter(1, assetId).setParameter(2, attributeName).setParameter(3, Timestamp.from(timestamp)).executeUpdate());++ if (deleted > 0) {+ publishPredictedDatapointsEvent(assetId, attributeName);+ }}@Override@@ -117,7 +184,17 @@ public class AssetPredictedDatapointService extends AbstractDatapointService<Assreturn super.getFirstPurgeMillis(currentTime) - 1800000; // Run half hour before default}- protected void purgeDataPoints() {+ protected void publishPredictedDatapointsEvent(String assetId, String attributeName) {+ if (clientEventService == null) {+ return;+ }++ clientEventService.publishEvent(+ new AssetPredictedDatapointEvent(new AttributeRef(assetId, attributeName), timerService.getNow())+ );+ }++ protected void purgeDatapoints() {try {// Purge data points not in the above list using default durationLOG.finest("Purging predicted data points older than now");diff --git a/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointEvent.java b/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointEvent.javanew file mode 100644index 000000000..dcbf22871--- /dev/null+++ b/model/src/main/java/org/openremote/model/datapoint/AssetPredictedDatapointEvent.java@@ -0,0 +1,60 @@+/*+ * Copyright 2026, 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.datapoint;++import com.fasterxml.jackson.annotation.JsonCreator;+import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.event.shared.SharedEvent;++import java.time.Instant;+import java.util.Objects;++/**+ * This event is used when predicted data points are inserted, updated or deleted for an asset's {@link org.openremote.model.attribute.Attribute}.+ * It does not include any of the data point values.+ */+public class AssetPredictedDatapointEvent extends SharedEvent {++ protected AttributeRef ref;++ public AssetPredictedDatapointEvent(AttributeRef ref, Instant timestamp) {+ this(ref, timestamp.toEpochMilli());+ }++ @JsonCreator+ public AssetPredictedDatapointEvent(AttributeRef ref, Long timestamp) {+ super(timestamp);+ Objects.requireNonNull(ref);+ this.ref = ref;+ }++ public AttributeRef getRef() {+ return ref;+ }+++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "ref=" + ref ++ ", timestamp=" + timestamp ++ '}';+ }+}diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.javaindex 75cf88525..4bcb80882 100644--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java@@ -23,6 +23,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes;import com.fasterxml.jackson.annotation.JsonTypeInfo;import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.datapoint.AssetPredictedDatapointEvent;import org.openremote.model.event.Event;import org.openremote.model.gateway.*;import org.openremote.model.services.ExternalServiceEvent;@@ -42,6 +43,7 @@ import org.openremote.model.alarm.AlarmEvent;@JsonSubTypes.Type(value = ExternalServiceEvent.class, name = "external-service"),@JsonSubTypes.Type(value = SyslogEvent.class, name = "syslog"),@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),+ @JsonSubTypes.Type(value = AssetPredictedDatapointEvent.class, name = "asset-predicted-data-points"),@JsonSubTypes.Type(value = AssetEvent.class, name = "asset"),@JsonSubTypes.Type(value = AssetsEvent.class, name = "assets"),@JsonSubTypes.Type(value = ReadAttributeEvent.class, name = "read-asset-attribute"),diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovyindex 69ea0ec89..5b3901065 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy@@ -1,26 +1,47 @@package org.openremote.test.assets+import io.netty.channel.ChannelHandler+import io.netty.handler.codec.string.StringDecoder+import io.netty.handler.codec.string.StringEncoder+import io.netty.util.CharsetUtil+import org.apache.http.client.utils.URIBuilder+import org.openremote.agent.protocol.io.AbstractNettyIOClientimport org.openremote.agent.protocol.simulator.SimulatorProtocol+import org.openremote.agent.protocol.websocket.WebsocketIOClientimport org.openremote.manager.agent.AgentServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.datapoint.AssetDatapointServiceimport org.openremote.manager.datapoint.AssetPredictedDatapointService+import org.openremote.manager.event.ClientEventService+import org.openremote.manager.security.ManagerIdentityServiceimport org.openremote.manager.setup.SetupService+import org.openremote.model.asset.agent.ConnectionStatus+import org.openremote.model.attribute.Attributeimport org.openremote.model.attribute.AttributeRef+import org.openremote.model.auth.OAuthPasswordGrant+import org.openremote.model.datapoint.AssetPredictedDatapointEventimport org.openremote.model.datapoint.AssetPredictedDatapointResourceimport org.openremote.model.datapoint.ValueDatapointimport org.openremote.model.datapoint.query.AssetDatapointIntervalQuery+import org.openremote.model.event.TriggeredEventSubscription+import org.openremote.model.event.shared.EventSubscription+import org.openremote.model.event.shared.SharedEvent+import org.openremote.model.event.shared.UnauthorizedEventSubscription+import org.openremote.model.security.ClientRoleimport org.openremote.model.util.ValueUtil+import org.openremote.model.value.ValueType+import org.openremote.setup.integration.KeycloakTestSetupimport org.openremote.setup.integration.ManagerTestSetupimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport java.time.Instant-import java.time.LocalDateTimeimport java.time.ZoneIdimport java.time.temporal.ChronoUnit+import java.util.concurrent.CopyOnWriteArrayListimport java.util.concurrent.TimeUnit+import java.util.function.Consumerimport static java.util.concurrent.TimeUnit.*import static org.openremote.manager.datapoint.AssetDatapointService.OR_DATA_POINTS_MAX_AGE_DAYS_DEFAULT@@ -31,6 +52,57 @@ import static spock.util.matcher.HamcrestMatchers.closeToclass AssetDatapointTest extends Specification implements ManagerContainerTrait {+ protected static <T> T messageFromString(String message) {+ try {+ def isSubscription = message.startsWith(EventSubscription.SUBSCRIBED_MESSAGE_PREFIX)+ def isTriggered = !isSubscription && message.startsWith(TriggeredEventSubscription.MESSAGE_PREFIX)+ def isUnauthorized = !isSubscription && !isTriggered && message.startsWith(UnauthorizedEventSubscription.MESSAGE_PREFIX)+ message = message.substring(message.indexOf(":") + 1)+ return ValueUtil.JSON.readValue(message,+ isSubscription ? EventSubscription.class : isTriggered ? TriggeredEventSubscription.class : isUnauthorized ? UnauthorizedEventSubscription.class : SharedEvent.class)+ } catch (Exception e) {+ throw new IllegalArgumentException("Unable to parse message")+ }+ }++ protected static String messageToString(String prefix, Object message) {+ try {+ String str = ValueUtil.asJSON(message).orElse(null)+ return prefix + str+ } catch (Exception e) {+ throw new IllegalArgumentException("Unable to serialise message")+ }+ }++ protected WebsocketIOClient<String> createPredictedDatapointWebsocketClient(+ int serverPort,+ String websocketRealm,+ String authRealm,+ String username,+ String password+ ) {+ def client = new WebsocketIOClient<String>(+ new URIBuilder("ws://127.0.0.1:$serverPort/websocket/events?Realm=$websocketRealm").build(),+ null,+ new OAuthPasswordGrant(+ "http://127.0.0.1:$serverPort/auth/realms/$authRealm/protocol/openid-connect/token",+ KEYCLOAK_CLIENT_ID,+ null,+ null,+ username,+ password+ )+ )+ client.setEncoderDecoderProvider({+ [+ new StringEncoder(CharsetUtil.UTF_8),+ new StringDecoder(CharsetUtil.UTF_8),+ new AbstractNettyIOClient.MessageToMessageDecoder<String>(String.class, client)+ ].toArray(new ChannelHandler[0])+ })+ return client+ }+def "Test number and toggle attribute storage, retrieval and purging"() {given: "expected conditions"@@ -44,6 +116,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitdef assetStorageService = container.getService(AssetStorageService.class)def assetDatapointService = container.getService(AssetDatapointService.class)def assetPredictedDatapointService = container.getService(AssetPredictedDatapointService.class)+ def clientEventService = container.getService(ClientEventService.class)and: "the clock is stopped for testing purposes and advanced to the next hour"stopPseudoClock()@@ -381,7 +454,14 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert datapoints.isEmpty()}- when: "predicted data points are added"+ when: "we subscribe to predicted data points events"+ List<AssetPredictedDatapointEvent> predictedEvents = new CopyOnWriteArrayList<>()+ Consumer<AssetPredictedDatapointEvent> predictedEventConsumer = { event ->+ predictedEvents.add(event)+ }+ clientEventService.addSubscription(AssetPredictedDatapointEvent.class, null, predictedEventConsumer)++ and: "predicted data points are added"predictedDatapointResource.writePredictedDatapoints(null, managerTestSetup.thingId, "light1PowerConsumption",[new ValueDatapoint<>(getClockTimeOf(container)+60000, 10d),@@ -406,6 +486,18 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert predictedData.size() == 5assert predictedData.any {it.value == 20d}+ and: "an event should be published for predicted datapoints"+ conditions.eventually {+ assert predictedEvents.any {+ it.ref.id == managerTestSetup.thingId &&+ it.ref.name == "light1PowerConsumption"+ }+ assert predictedEvents.any {+ it.ref.id == managerTestSetup.thingId &&+ it.ref.name == thingLightToggleAttributeName+ }+ }+when: "the predicted data is purged and then retrieved"assetPredictedDatapointService.purgeValues(managerTestSetup.thingId, "light1PowerConsumption")predictedData = assetPredictedDatapointService.getDatapoints(new AttributeRef(managerTestSetup.thingId, "light1PowerConsumption"))@@ -413,6 +505,14 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitthen: "no predicted data should remain for this attribute"assert predictedData.isEmpty()+ and: "an event should be published"+ conditions.eventually {+ assert predictedEvents.any {+ it.ref.id == managerTestSetup.thingId &&+ it.ref.name == "light1PowerConsumption"+ }+ }+when: "other predicted data is retrieved"predictedData = assetPredictedDatapointService.getDatapoints(new AttributeRef(managerTestSetup.thingId, thingLightToggleAttributeName))@@ -420,4 +520,344 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert predictedData.size() == 5assert predictedData.count {it.value == false} == 2}++ def "Test predicted datapoint change events are received via websocket API"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ and: "the manager container and test setup are available"+ def container = startContainer(defaultConfig(), defaultServices())+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)++ and: "an authenticated predicted datapoint API client"+ def accessToken = authenticate(+ container,+ MASTER_REALM,+ KEYCLOAK_CLIENT_ID,+ "testuser1",+ "testuser1"+ ).token+ def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AssetPredictedDatapointResource.class)++ and: "a websocket client authenticated in the same realm"+ def client = new WebsocketIOClient<String>(+ new URIBuilder("ws://127.0.0.1:$serverPort/websocket/events?Realm=master").build(),+ null,+ new OAuthPasswordGrant(+ "http://127.0.0.1:$serverPort/auth/realms/master/protocol/openid-connect/token",+ KEYCLOAK_CLIENT_ID,+ null,+ null,+ "testuser1",+ "testuser1"+ )+ )+ client.setEncoderDecoderProvider({+ [+ new StringEncoder(CharsetUtil.UTF_8),+ new StringDecoder(CharsetUtil.UTF_8),+ new AbstractNettyIOClient.MessageToMessageDecoder<String>(String.class, client)+ ].toArray(new ChannelHandler[0])+ })++ and: "message and connection listeners are configured"+ def connectionStatus = client.getConnectionStatus()+ List<Object> receivedMessages = new CopyOnWriteArrayList<>()+ client.addMessageConsumer(message -> receivedMessages.add(messageFromString(message)))+ client.addConnectionStatusConsumer(status -> connectionStatus = status)++ when: "the websocket client connects and subscribes to predicted datapoint events"+ client.connect()++ then: "the websocket should be connected"+ conditions.eventually {+ assert client.connectionStatus == ConnectionStatus.CONNECTED+ assert connectionStatus == ConnectionStatus.CONNECTED+ }++ when: "the predicted datapoint event subscription is sent"+ client.sendMessage(messageToString(+ EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,+ new EventSubscription(AssetPredictedDatapointEvent.class, null, "predicted-datapoints")+ ))++ then: "the server should confirm subscription"+ conditions.eventually {+ assert receivedMessages.any {+ it instanceof EventSubscription &&+ it.subscriptionId == "predicted-datapoints"+ }+ }++ when: "a predicted datapoint change is written"+ receivedMessages.clear()+ predictedDatapointResource.writePredictedDatapoints(+ null,+ managerTestSetup.thingId,+ "light1PowerConsumption",+ [new ValueDatapoint<>(getClockTimeOf(container) + 60000, 42d)] as ValueDatapoint<?>[]+ )++ then: "the websocket subscription should receive the corresponding triggered event"+ conditions.eventually {+ assert receivedMessages.any {+ it instanceof TriggeredEventSubscription &&+ it.subscriptionId == "predicted-datapoints" &&+ it.events.any { event ->+ event instanceof AssetPredictedDatapointEvent &&+ event.ref.id == managerTestSetup.thingId &&+ event.ref.name == "light1PowerConsumption"+ }+ }+ }++ cleanup: "the websocket client is disconnected"+ if (client != null) {+ client.disconnect()+ }+ }++ def "Test predicted datapoint websocket subscription is denied without READ_ASSETS role"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ and: "the manager container and setup are available"+ def container = startContainer(defaultConfig(), defaultServices())+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)+ def identityService = container.getService(ManagerIdentityService.class)++ and: "a regular building user has READ_ASSETS removed"+ identityService.getIdentityProvider().updateUserClientRoles(+ keycloakTestSetup.realmBuilding.name,+ keycloakTestSetup.testuser2Id,+ KEYCLOAK_CLIENT_ID,+ ClientRole.WRITE_USER.value,+ ClientRole.READ_MAP.value+ )++ and: "a websocket client authenticated as that user"+ def client = createPredictedDatapointWebsocketClient(serverPort, "building", "building", "testuser2", "testuser2")+ List<Object> receivedMessages = new CopyOnWriteArrayList<>()+ client.addMessageConsumer(message -> receivedMessages.add(messageFromString(message)))++ when: "the websocket client connects and subscribes to predicted datapoint events"+ client.connect()+ conditions.eventually {+ assert client.connectionStatus == ConnectionStatus.CONNECTED+ }++ client.sendMessage(messageToString(+ EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,+ new EventSubscription(AssetPredictedDatapointEvent.class, null, "predicted-no-read-assets")+ ))++ then: "the server should reject subscription"+ conditions.eventually {+ assert receivedMessages.any {+ it instanceof UnauthorizedEventSubscription &&+ it.subscription.subscriptionId == "predicted-no-read-assets"+ }+ }++ cleanup: "the websocket client is disconnected and original roles are restored"+ identityService.getIdentityProvider().updateUserClientRoles(+ keycloakTestSetup.realmBuilding.name,+ keycloakTestSetup.testuser2Id,+ KEYCLOAK_CLIENT_ID,+ ClientRole.WRITE_USER.value,+ ClientRole.READ_MAP.value,+ ClientRole.READ_ASSETS.value+ )+ if (client != null) {+ client.disconnect()+ }+ }++ def "Test predicted datapoint websocket subscription is denied for a different realm"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ and: "the manager container is available"+ def container = startContainer(defaultConfig(), defaultServices())++ and: "a building realm websocket client requests subscriptions in master realm"+ def client = createPredictedDatapointWebsocketClient(serverPort, "master", "building", "testuser2", "testuser2")+ List<Object> receivedMessages = new CopyOnWriteArrayList<>()+ client.addMessageConsumer(message -> receivedMessages.add(messageFromString(message)))++ when: "the websocket client connects and subscribes to predicted datapoint events"+ client.connect()++ then: "the websocket session should never be established in a realm where the user does not belong"+ assert client.connectionStatus != ConnectionStatus.CONNECTED+ assert receivedMessages.isEmpty()++ cleanup: "the websocket client is disconnected"+ if (client != null) {+ client.disconnect()+ }+ }++ def "Test restricted user does not receive predicted datapoint events for unlinked assets"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ and: "the manager container and setup are available"+ def container = startContainer(defaultConfig(), defaultServices())+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)++ and: "a building realm predicted datapoint API client"+ def accessToken = authenticate(+ container,+ "building",+ KEYCLOAK_CLIENT_ID,+ "testuser2",+ "testuser2"+ ).token+ def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), "building", accessToken).proxy(AssetPredictedDatapointResource.class)++ and: "a restricted websocket client in the same realm"+ def client = createPredictedDatapointWebsocketClient(serverPort, "building", "building", "testuser3", "testuser3")+ List<Object> receivedMessages = new CopyOnWriteArrayList<>()+ client.addMessageConsumer(message -> receivedMessages.add(messageFromString(message)))++ when: "the websocket client connects and subscribes to predicted datapoint events"+ client.connect()+ conditions.eventually {+ assert client.connectionStatus == ConnectionStatus.CONNECTED+ }++ client.sendMessage(messageToString(+ EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,+ new EventSubscription(AssetPredictedDatapointEvent.class, null, "predicted-restricted-unlinked")+ ))++ and: "a predicted datapoint update is written on a linked and restricted attribute"+ receivedMessages.clear()+ predictedDatapointResource.writePredictedDatapoints(+ null,+ managerTestSetup.apartment1LivingroomId,+ "targetTemperature",+ [new ValueDatapoint<>(getClockTimeOf(container) + 60000, 22d)] as ValueDatapoint<?>[]+ )++ then: "the restricted user should receive the linked attribute event"+ conditions.eventually {+ assert receivedMessages.any {+ it instanceof TriggeredEventSubscription &&+ it.subscriptionId == "predicted-restricted-unlinked" &&+ it.events.any { event ->+ event instanceof AssetPredictedDatapointEvent &&+ event.ref.id == managerTestSetup.apartment1LivingroomId &&+ event.ref.name == "targetTemperature"+ }+ }+ }++ when: "a predicted datapoint update is written on an unlinked asset"+ receivedMessages.clear()+ predictedDatapointResource.writePredictedDatapoints(+ null,+ managerTestSetup.apartment2LivingroomId,+ "targetTemperature",+ [new ValueDatapoint<>(getClockTimeOf(container) + 60000, 21d)] as ValueDatapoint<?>[]+ )++ then: "no triggered event should be received by the restricted user"+ assert receivedMessages.every {+ !(it instanceof TriggeredEventSubscription) || it.subscriptionId != "predicted-restricted-unlinked"+ }++ cleanup: "the websocket client is disconnected"+ if (client != null) {+ client.disconnect()+ }+ }++ def "Test restricted user does not receive predicted datapoint events for non-restricted attributes"() {++ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ and: "the manager container and setup are available"+ def container = startContainer(defaultConfig(), defaultServices())+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)+ def assetStorageService = container.getService(AssetStorageService.class)++ and: "a non-restricted attribute exists on an asset linked to the restricted user"+ def apartment1 = assetStorageService.find(managerTestSetup.apartment1Id, true)+ apartment1.getAttributes().addOrReplace(new Attribute<>("predictedNonRestricted", ValueType.NUMBER, 0d))+ assetStorageService.merge(apartment1)++ and: "a building realm predicted datapoint API client"+ def accessToken = authenticate(+ container,+ "building",+ KEYCLOAK_CLIENT_ID,+ "testuser2",+ "testuser2"+ ).token+ def predictedDatapointResource = getClientApiTarget(serverUri(serverPort), "building", accessToken).proxy(AssetPredictedDatapointResource.class)++ and: "a restricted websocket client in the same realm"+ def client = createPredictedDatapointWebsocketClient(serverPort, "building", "building", "testuser3", "testuser3")+ List<Object> receivedMessages = new CopyOnWriteArrayList<>()+ client.addMessageConsumer(message -> receivedMessages.add(messageFromString(message)))++ when: "the websocket client connects and subscribes to predicted datapoint events"+ client.connect()+ conditions.eventually {+ assert client.connectionStatus == ConnectionStatus.CONNECTED+ }++ client.sendMessage(messageToString(+ EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,+ new EventSubscription(AssetPredictedDatapointEvent.class, null, "predicted-restricted-attr")+ ))++ and: "a predicted datapoint update is written on a linked restricted attribute"+ receivedMessages.clear()+ predictedDatapointResource.writePredictedDatapoints(+ null,+ managerTestSetup.apartment1LivingroomId,+ "targetTemperature",+ [new ValueDatapoint<>(getClockTimeOf(container) + 60000, 19d)] as ValueDatapoint<?>[]+ )++ then: "the restricted user should receive the restricted attribute event"+ conditions.eventually {+ assert receivedMessages.any {+ it instanceof TriggeredEventSubscription &&+ it.subscriptionId == "predicted-restricted-attr" &&+ it.events.any { event ->+ event instanceof AssetPredictedDatapointEvent &&+ event.ref.id == managerTestSetup.apartment1LivingroomId &&+ event.ref.name == "targetTemperature"+ }+ }+ }++ when: "a predicted datapoint update is written on a non-restricted attribute"+ receivedMessages.clear()+ predictedDatapointResource.writePredictedDatapoints(+ null,+ managerTestSetup.apartment1Id,+ "predictedNonRestricted",+ [new ValueDatapoint<>(getClockTimeOf(container) + 60000, 10d)] as ValueDatapoint<?>[]+ )++ then: "no triggered event should be received by the restricted user"+ assert receivedMessages.every {+ !(it instanceof TriggeredEventSubscription) || it.subscriptionId != "predicted-restricted-attr"+ }++ cleanup: "the websocket client is disconnected"+ if (client != null) {+ client.disconnect()+ }+ }}