Skip to content

armgit / core

Public Imported from GitHub
0

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

Add HTTP endpoints to allow update of attributes at a defined timestamp (#1487)

Panos Kalogeropoulos2090e42a4e1e
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index 506f2737c..8c6254669 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -415,14 +415,18 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
@Override
public Response writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Object value) {
+ return writeAttributeValue(requestParams, assetId, attributeName, null, value);
+ }
+ @Override
+ public Response writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Long timestamp, Object value) {
Response.Status status = Response.Status.OK;
if (value instanceof NullNode) {
value = null;
}
- AttributeEvent event = new AttributeEvent(assetId, attributeName, value);
+ AttributeEvent event = new AttributeEvent(assetId, attributeName, value, timestamp);
// Check authorisation
if (!clientEventService.authorizeEventWrite(getRequestRealmName(), getAuthContext(), event)) {
@@ -446,10 +450,17 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
@Override
public AttributeWriteResult[] writeAttributeValues(RequestParams requestParams, AttributeState[] attributeStates) {
+ return writeAttributeValues(requestParams,
+ Arrays.stream(attributeStates)
+ .map(AttributeEvent::new)
+ .toArray(AttributeEvent[]::new)
+ );
+ }
+ @Override
+ public AttributeWriteResult[] writeAttributeValues(RequestParams requestParams, AttributeEvent[] attributeEvents) {
// Process asynchronously but block for a little while waiting for the result
- return Arrays.stream(attributeStates).map(attributeState -> {
- AttributeEvent event = new AttributeEvent(attributeState);
+ return Arrays.stream(attributeEvents).map(event -> {
if (!clientEventService.authorizeEventWrite(getRequestRealmName(), getAuthContext(), event)) {
return new AttributeWriteResult(event.getRef(), AttributeWriteFailure.INSUFFICIENT_ACCESS);
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.java
index 7f54bfacc..570a20613 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java
@@ -30,6 +30,7 @@ import jakarta.validation.constraints.Size;
import jakarta.ws.rs.*;
import jakarta.ws.rs.core.Response;
import org.openremote.model.Constants;
+import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeState;
import org.openremote.model.attribute.AttributeWriteResult;
@@ -246,6 +247,23 @@ public interface AssetResource {
schema = @Schema(implementation = AttributeWriteResult.class)))})
Response writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, Object value);
+ @PUT
+ //TODO: Using {timestamp:(\\d+)?} does not correctly tokenize when using the assetResource proxy client in Groovy tests.
+ @Path("{assetId}/attribute/{attributeName}/{timestamp}")
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @Operation(operationId = "writeAttributeValue", summary = "Write to a single attribute with a timestamp", responses = {
+ @ApiResponse(
+ description = "The result of the write operation",
+ content = @Content(mediaType = "application/json", schema = @Schema(implementation = AttributeWriteResult.class))
+ )})
+ Response writeAttributeValue(@BeanParam RequestParams requestParams,
+ @PathParam("assetId") String assetId,
+ @PathParam("attributeName") String attributeName,
+ @PathParam("timestamp") Long timestamp,
+ Object value);
+
+
@PUT
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@@ -253,6 +271,13 @@ public interface AssetResource {
@Operation(operationId = "writeAttributeValues", summary = "Update attribute values")
AttributeWriteResult[] writeAttributeValues(@BeanParam RequestParams requestParams, AttributeState[] attributeStates);
+ @PUT
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @Path("attributes/timestamp")
+ @Operation(operationId = "writeAttributeValues", summary = "Update attribute values")
+ AttributeWriteResult[] writeAttributeValues(@BeanParam RequestParams requestParams, AttributeEvent[] attributeStates);
+
/**
* Creates an asset. The identifier value of the asset can be provided, it should be a globally unique string value,
* and must be 22 characters long. If no identifier value is provided, a unique value will be generated by
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
index 27902980e..dbd8b844b 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy
@@ -1,14 +1,18 @@
package org.openremote.test.assets
-
import jakarta.ws.rs.WebApplicationException
import org.jboss.resteasy.api.validation.ViolationReport
-import org.openremote.model.util.UniqueIdentifierGenerator
+import org.openremote.container.timer.TimerService
+import org.openremote.manager.datapoint.AssetDatapointService
+import org.openremote.manager.event.ClientEventService
import org.openremote.manager.setup.SetupService
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.impl.RoomAsset
import org.openremote.model.asset.impl.ThingAsset
import org.openremote.model.attribute.Attribute
+import org.openremote.model.attribute.AttributeState
+import org.openremote.model.attribute.AttributeEvent
+import org.openremote.model.util.UniqueIdentifierGenerator
import org.openremote.model.value.ValueType
import org.openremote.setup.integration.KeycloakTestSetup
import org.openremote.setup.integration.ManagerTestSetup
@@ -16,6 +20,8 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import java.util.concurrent.TimeUnit
+
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD
import static org.openremote.manager.security.ManagerIdentityProvider.OR_ADMIN_PASSWORD_DEFAULT
@@ -164,4 +170,189 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTrait
ex = thrown()
ex.response.status == 400
}
+
+ def "Test writing attributes with timestamps"() {
+ given: "the server container is started"
+ def container = startContainer(defaultConfig(), defaultServices())
+ def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+ def clientEventService = container.getService(ClientEventService.class)
+ TimerService timerService = container.getService(TimerService.class);
+ AssetDatapointService datapointService = container.getService(AssetDatapointService.class);
+
+ and: "an authenticated admin user"
+ def accessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), OR_ADMIN_PASSWORD, OR_ADMIN_PASSWORD_DEFAULT)
+ ).token
+
+ and: "the asset resource"
+ def serverUri = serverUri(serverPort)
+ def assetResource = getClientApiTarget(serverUri, MASTER_REALM, accessToken).proxy(AssetResource.class)
+
+ when: "an asset is created in the authenticated realm"
+ RoomAsset testAsset = new RoomAsset("Test Room")
+ .setRealm(keycloakTestSetup.realmMaster.name)
+ .addAttributes(new Attribute<Object>("noTimestampTest", ValueType.LONG))
+ testAsset = assetResource.create(null, testAsset)
+
+ then: "the asset should exist"
+ testAsset.name == "Test Room"
+ testAsset.type == RoomAsset.DESCRIPTOR.getName()
+ testAsset.realm == keycloakTestSetup.realmMaster.name
+ testAsset.parentId == null
+
+ when: "an attribute is updated with no timestamp"
+ testAsset = assetResource.get(null, testAsset.getId())
+
+ timerService.clock.advanceTime(10, TimeUnit.MINUTES);
+ timerService.stop(container)
+ Long timestamp = timerService.getCurrentTimeMillis()
+
+ assetResource.writeAttributeValue(null, testAsset.getId(), "noTimestampTest", 123)
+
+ then: "the attribute's timestamp should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute("noTimestampTest").get().getTimestamp().get() == timestamp;
+ assert asset.getAttribute("noTimestampTest").get().getValue().get() == 123;
+
+ }
+
+ when: "an attribute is updated with a timestamp"
+ testAsset = assetResource.get(null, testAsset.getId())
+
+ timerService.clock.advanceTime(10, TimeUnit.MINUTES);
+ timerService.stop(container)
+ timestamp = timerService.getCurrentTimeMillis()
+
+ assetResource.writeAttributeValue(null, testAsset.getId(), testAsset.AREA.name, timestamp-2000, 123)
+
+ then: "the attribute's timestamp should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(testAsset.AREA.name).get().getTimestamp().get() == timestamp-2000;
+ assert asset.getAttribute(testAsset.AREA.name).get().getValue().get() == 123;
+
+ }
+
+ when: "an attribute is updated with the current timestamp"
+ testAsset = assetResource.get(null, testAsset.getId())
+
+ timerService.clock.advanceTime(10, TimeUnit.MINUTES);
+ timerService.stop(container)
+ timestamp = timerService.getCurrentTimeMillis()
+
+ assetResource.writeAttributeValue(null, testAsset.getId(), testAsset.AREA.name, timestamp-2000, 123)
+
+ then: "the attribute's timestamp should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(testAsset.AREA.name).get().getTimestamp().get() == timestamp-2000;
+ assert asset.getAttribute(testAsset.AREA.name).get().getValue().get() == 123;
+
+ }
+
+ when: "an attribute value is updated with a timestamp earlier than the current value"
+
+ assetResource.writeAttributeValue(null, testAsset.getId(), testAsset.AREA.name, timestamp-3000, 1234)
+
+ then: "the timestamp and value of the attribute should be the original one"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(testAsset.AREA.name).get().getTimestamp().get() == timestamp-2000;
+ assert asset.getAttribute(testAsset.AREA.name).get().getValue().get() == 123;
+ }
+
+ when: "an attribute value is updated with a timestamp of current clock time"
+ assetResource.writeAttributeValue(null, testAsset.getId(), testAsset.AREA.name, 0, 12345)
+
+ then: "the timestamp and value of the attribute should be the new ones"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(testAsset.AREA.name).get().getTimestamp().get() == timestamp;
+ assert asset.getAttribute(testAsset.AREA.name).get().getValue().get() == 12345;
+ }
+
+ timerService.clock.advanceTime(10, TimeUnit.MINUTES);
+
+ when: "Multiple attribute values are updated with current timestamps"
+ timestamp = timerService.getCurrentTimeMillis();
+
+ List<AttributeEvent> states = new ArrayList<>();
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.AREA.getName(), 123456), timestamp-3000));
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.ROOM_NUMBER.getName(), 123456), timestamp-3000));
+
+ assetResource.writeAttributeValues(null, states.toArray() as AttributeEvent[])
+
+ then: "the attribute value should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(asset.AREA.getName()).get().getValue().get() == 123456;
+ assert asset.getAttribute(asset.AREA.getName()).get().getTimestamp().get() == timestamp-3000;
+
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getValue().get() == 123456;
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getTimestamp().get() == timestamp-3000;
+ }
+
+ when: "Multiple attribute values are updated with future timestamps"
+ timestamp = timerService.getCurrentTimeMillis();
+
+ states = new ArrayList<>();
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.AREA.getName(), 1234567), timestamp-2000));
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.ROOM_NUMBER.getName(), 1234567), timestamp-2000));
+
+ assetResource.writeAttributeValues(null, states.toArray() as AttributeEvent[])
+
+ then: "the attribute value should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(asset.AREA.getName()).get().getValue().get() == 1234567;
+ assert asset.getAttribute(asset.AREA.getName()).get().getTimestamp().get() == timestamp-2000;
+
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getValue().get() == 1234567;
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getTimestamp().get() == timestamp-2000;
+ }
+
+ when: "Multiple attribute values are updated with past timestamps"
+ states = new ArrayList<>();
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.AREA.getName(), 12345678), timestamp-4000));
+ states.add(new AttributeEvent(new AttributeState(testAsset.getId(), testAsset.ROOM_NUMBER.getName(), 12345678), timestamp-4000));
+
+ assetResource.writeAttributeValues(null, states.toArray() as AttributeEvent[])
+
+ then: "the attribute value should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(asset.AREA.getName()).get().getValue().get() == 1234567;
+ assert asset.getAttribute(asset.AREA.getName()).get().getTimestamp().get() == timestamp-2000;
+
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getValue().get() == 1234567;
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getTimestamp().get() == timestamp-2000;
+ }
+
+ when: "Multiple attribute values are updated with no timestamps"
+ timerService.stop(container)
+ timestamp = timerService.getCurrentTimeMillis();
+
+ List<AttributeState> noTimestampStates = new ArrayList<>();
+ noTimestampStates.add(new AttributeState(testAsset.getId(), testAsset.AREA.getName(), 123456789));
+ noTimestampStates.add(new AttributeState(testAsset.getId(), testAsset.ROOM_NUMBER.getName(), 123456789));
+
+ assetResource.writeAttributeValues(null, noTimestampStates.toArray() as AttributeState[])
+
+ then: "the attribute value should match"
+ new PollingConditions(timeout: 5, delay: 0.2).eventually {
+ RoomAsset asset = assetResource.get(null, testAsset.getId()) as RoomAsset
+ assert asset.getAttribute(asset.AREA.getName()).get().getValue().get() == 123456789;
+ assert asset.getAttribute(asset.AREA.getName()).get().getTimestamp().get() == timestamp;
+
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getValue().get() == 123456789;
+ assert asset.getAttribute(asset.ROOM_NUMBER.getName()).get().getTimestamp().get() == timestamp;
+ }
+
+ }
}