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
AssetResource update to writeAttributeValue and added writeAttributeValues
Rich Turner1eafb130dd0e
diff --git a/gradle.properties b/gradle.propertiesindex 9f40dc544..09bcd95df 100644--- a/gradle.properties+++ b/gradle.properties@@ -51,3 +51,4 @@ californiumScandiumVersion = 2.1.0zwaveVersion = 3.4.0-SNAPSHOThibernateTypesVersion = 2.10.0reflectionsVersion=0.9.12+swaggerVersion=1.6.2diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.javaindex edb644945..460a2b253 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.java@@ -19,128 +19,29 @@*/package org.openremote.manager.asset;-import org.openremote.model.asset.agent.Agent;-import org.openremote.model.attribute.Attribute;-import org.openremote.model.attribute.AttributeExecuteStatus;-import org.openremote.model.value.ValueType;+import org.openremote.model.attribute.AttributeWriteFailure;/*** The reason why processing an {@link org.openremote.model.attribute.AttributeEvent} failed.*/public class AssetProcessingException extends RuntimeException {- public enum Reason {+ final protected AttributeWriteFailure reason;- /**- * Missing {@link org.openremote.model.attribute.AttributeEvent.Source}.- */- MISSING_SOURCE,-- /**- * The source of the event does not match the expected source (e.g. expected client message- * but received sensor read).- */- ILLEGAL_SOURCE,-- /**- * The asset does not exist.- */- ASSET_NOT_FOUND,-- /**- * The attribute does not exist.- */- ATTRIBUTE_NOT_FOUND,-- /**- * An actuator update must be for an attribute with a valid agent link.- */- INVALID_AGENT_LINK,-- /**- * An attribute is linked to another attribute, but the link is invalid.- */- INVALID_ATTRIBUTE_LINK,-- /**- * An attribute is linked to another attribute, but the linked attribute can't be written- * because conversion to the target attribute's value failed.- */- LINKED_ATTRIBUTE_CONVERSION_FAILURE,-- /**- * Attributes of an {@link Agent} can not be individually updated.- */- ILLEGAL_AGENT_UPDATE,-- /**- * Invalid {@link AttributeExecuteStatus} for {@link Attribute} of type {@link ValueType#EXECUTION_STATUS}.- */- INVALID_ATTRIBUTE_EXECUTE_STATUS,-- /**- * No authentication/authorization context available.- */- NO_AUTH_CONTEXT,-- /**- * Realm configuration or user privileges do not allow update (e.g. realm inactive, user is- * missing required role, attribute is read-only).- */- INSUFFICIENT_ACCESS,-- /**- * The event timestamp is later than the processing time.- */- EVENT_IN_FUTURE,-- /**- * The event timestamp is older than the last updated timestamp of the attribute.- */- EVENT_OUTDATED,-- /**- * Applying the event violates constraints of the attribute.- */- ATTRIBUTE_VALIDATION_FAILURE,-- /**- * Any other error, typically other runtime exceptions thrown by a processor.- */- PROCESSOR_FAILURE,-- /**- * Writing the asset attribute state to database failed.- */- STATE_STORAGE_FAILED,-- /**- * The event value is not the excepted value for the attribute- */- INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE,-- /**- * The event is for a gateway descendant asset but the gateway is not connected- */- GATEWAY_DISCONNECTED- }-- final protected Reason reason;-- public AssetProcessingException(Reason reason) {+ public AssetProcessingException(AttributeWriteFailure reason) {this(reason, null);}- public AssetProcessingException(Reason reason, String message) {+ public AssetProcessingException(AttributeWriteFailure reason, String message) {this(reason, message, null);}- public AssetProcessingException(Reason reason, String message, Throwable cause) {+ public AssetProcessingException(AttributeWriteFailure reason, String message, Throwable cause) {super(reason + (message != null ? " (" + message + ")": ""), cause);this.reason = reason;}- public Reason getReason() {+ public AttributeWriteFailure getReason() {return reason;}}diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.javaindex bfa92c6ee..26b59db47 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java@@ -39,11 +39,8 @@ import org.openremote.model.ContainerService;import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetResource;import org.openremote.model.asset.agent.Protocol;-import org.openremote.model.attribute.Attribute;-import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.*;import org.openremote.model.attribute.AttributeEvent.Source;-import org.openremote.model.attribute.AttributeExecuteStatus;-import org.openremote.model.attribute.MetaItem;import org.openremote.model.security.ClientRole;import org.openremote.model.value.MetaItemType;import org.openremote.model.value.ValueType;@@ -58,7 +55,7 @@ import java.util.logging.Level;import java.util.logging.Logger;import static org.openremote.container.concurrent.GlobalLock.withLock;-import static org.openremote.manager.asset.AssetProcessingException.Reason.*;+import static org.openremote.model.attribute.AttributeWriteFailure.*;import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;import static org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE;import static org.openremote.model.attribute.AttributeEvent.Source.*;@@ -81,7 +78,7 @@ import static org.openremote.model.value.MetaItemType.AGENT_LINK;* <p>* The {@link AttributeEvent}s are first validated depending on their source, and if validation fails* at any point then an {@link AssetProcessingException} will be logged as a warning with an- * {@link AssetProcessingException.Reason}.+ * {@link AttributeWriteFailure}.* <p>* Once successfully validated a chain of {@link AssetUpdateProcessor}s is handling the update message:* <ul>diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.javaindex d1d66561c..aa0fd96f0 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java@@ -19,6 +19,7 @@*/package org.openremote.manager.asset;+import com.fasterxml.jackson.databind.node.NullNode;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.timer.TimerService;import org.openremote.manager.security.ManagerIdentityService;@@ -30,7 +31,6 @@ import org.openremote.model.asset.UserAsset;import org.openremote.model.attribute.*;import org.openremote.model.http.RequestParams;import org.openremote.model.query.AssetQuery;-import org.openremote.model.query.filter.ParentPredicate;import org.openremote.model.query.filter.TenantPredicate;import org.openremote.model.util.TextUtil;import org.openremote.model.value.Values;@@ -39,6 +39,8 @@ import javax.persistence.OptimisticLockException;import javax.validation.ConstraintViolationException;import javax.ws.rs.WebApplicationException;import javax.ws.rs.core.HttpHeaders;+import javax.ws.rs.core.MediaType;+import javax.ws.rs.core.Response;import java.util.*;import java.util.logging.Logger;@@ -46,7 +48,6 @@ import static javax.ws.rs.core.Response.Status.*;import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;import static org.openremote.model.query.AssetQuery.Access;import static org.openremote.model.query.AssetQuery.Select.selectExcludeAll;-import static org.openremote.model.query.AssetQuery.Select.selectExcludePathAndAttributes;import static org.openremote.model.util.TextUtil.isNullOrEmpty;import static org.openremote.model.value.MetaItemType.*;@@ -341,55 +342,63 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour}@Override- public void writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, String valueStr) {- try {+ public Response writeAttributeValue(RequestParams requestParams, String assetId, String attributeName, Object value) {- // JAX-RS converts a null to empty string so simple check here - means cannot actually send an empty string- // but not sure you would want to as really it conveys the same meaning as no value- if (TextUtil.isNullOrEmpty(valueStr)) {- valueStr = null;- }+ Response.Status status = Response.Status.OK;- AttributeEvent event = new AttributeEvent(- new AttributeRef(assetId, attributeName), valueStr, timerService.getCurrentTimeMillis()- );+ if (value instanceof NullNode) {+ value = null;+ }- LOG.info("Write attribute value request: " + event);+ // Process asynchronously but block for a little while waiting for the result+ Map<String, Object> headers = new HashMap<>();+ headers.put(AttributeEvent.HEADER_SOURCE, CLIENT);- // Process asynchronously but block for a little while waiting for the result- Map<String, Object> headers = new HashMap<>();- headers.put(AttributeEvent.HEADER_SOURCE, CLIENT);+ if (isAuthenticated()) {+ headers.put(Constants.AUTH_CONTEXT, getAuthContext());+ }- if (isAuthenticated()) {- headers.put(Constants.AUTH_CONTEXT, getAuthContext());+ AttributeWriteResult result = doAttributeWrite(new AttributeRef(assetId, attributeName), value, headers);++ if (result.getFailure() != null) {+ switch (result.getFailure()) {+ case ILLEGAL_SOURCE:+ case NO_AUTH_CONTEXT:+ case INSUFFICIENT_ACCESS:+ status = FORBIDDEN;+ break;+ case ASSET_NOT_FOUND:+ case ATTRIBUTE_NOT_FOUND:+ status = NOT_FOUND;+ break;+ case INVALID_AGENT_LINK:+ case ILLEGAL_AGENT_UPDATE:+ case INVALID_ATTRIBUTE_EXECUTE_STATUS:+ case INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE:+ status = NOT_ACCEPTABLE;+ break;+ default:+ status = BAD_REQUEST;}- Object result = messageBrokerService.getProducerTemplate().requestBodyAndHeaders(- AssetProcessingService.ASSET_QUEUE, event, headers- );+ }- if (result instanceof AssetProcessingException) {- AssetProcessingException processingException = (AssetProcessingException) result;- switch (processingException.getReason()) {- case ILLEGAL_SOURCE:- case NO_AUTH_CONTEXT:- case INSUFFICIENT_ACCESS:- throw new WebApplicationException(FORBIDDEN);- case ASSET_NOT_FOUND:- case ATTRIBUTE_NOT_FOUND:- throw new WebApplicationException(NOT_FOUND);- case INVALID_AGENT_LINK:- case ILLEGAL_AGENT_UPDATE:- case INVALID_ATTRIBUTE_EXECUTE_STATUS:- case INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE:- throw new IllegalStateException(processingException);- default:- throw processingException;- }- }+ return Response.status(status).entity(result).type(MediaType.APPLICATION_JSON_TYPE).build();+ }- } catch (IllegalStateException ex) {- throw new WebApplicationException(ex, BAD_REQUEST);+ @Override+ public AttributeWriteResult[] writeAttributeValues(RequestParams requestParams, AttributeState[] attributeStates) {++ // Process asynchronously but block for a little while waiting for the result+ Map<String, Object> headers = new HashMap<>();+ headers.put(AttributeEvent.HEADER_SOURCE, CLIENT);++ if (isAuthenticated()) {+ headers.put(Constants.AUTH_CONTEXT, getAuthContext());}++ return Arrays.stream(attributeStates).map(attributeState ->+ doAttributeWrite(attributeState.getRef(), attributeState.getValue().orElse(null), headers)+ ).toArray(AttributeWriteResult[]::new);}@Override@@ -579,4 +588,31 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourreturn result;}++ protected AttributeWriteResult doAttributeWrite(AttributeRef ref, Object value, Map<String, Object> headers) {+ AttributeWriteFailure failure = null;++ try {+ AttributeEvent event = new AttributeEvent(+ ref, value, timerService.getCurrentTimeMillis()+ );++ LOG.info("Write attribute value request: " + event);++ // Process synchronously+ Object result = messageBrokerService.getProducerTemplate().requestBodyAndHeaders(+ AssetProcessingService.ASSET_QUEUE, event, headers+ );++ if (result instanceof AssetProcessingException) {+ AssetProcessingException processingException = (AssetProcessingException) result;+ failure = processingException.getReason();+ }++ } catch (IllegalStateException ex) {+ failure = AttributeWriteFailure.UNKNOWN;+ }++ return new AttributeWriteResult(ref, failure);+ }}diff --git a/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.javaindex 93446827a..fd9042258 100644--- a/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AttributeLinkingService.java@@ -20,7 +20,7 @@package org.openremote.manager.asset;import org.openremote.manager.agent.AgentService;-import org.openremote.manager.asset.AssetProcessingException.Reason;+import org.openremote.model.attribute.AttributeWriteFailure;import org.openremote.model.Container;import org.openremote.model.ContainerService;import org.openremote.model.asset.Asset;@@ -138,7 +138,7 @@ public class AttributeLinkingService implements ContainerService, AssetUpdateProLOG.finer("Processing attribute state for linked attribute");if (attributeLink == null) {- throw new AssetProcessingException(Reason.INVALID_ATTRIBUTE_LINK);+ throw new AssetProcessingException(AttributeWriteFailure.INVALID_ATTRIBUTE_LINK);}// Convert the value as required@@ -230,13 +230,13 @@ public class AttributeLinkingService implements ContainerService, AssetUpdateProtry {Attribute<?> currentAttribute = getAttribute(em, assetStorageService, linkedAttributeRef).orElseThrow(() -> new AssetProcessingException(- Reason.ATTRIBUTE_NOT_FOUND,+ AttributeWriteFailure.ATTRIBUTE_NOT_FOUND,"cannot toggle value as attribute cannot be found: " + linkedAttributeRef));if (!Values.isBoolean(currentAttribute.getType().getType())) {throw new AssetProcessingException(- Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,"cannot toggle value as attribute is not of type BOOLEAN: " + linkedAttributeRef);}@@ -251,13 +251,13 @@ public class AttributeLinkingService implements ContainerService, AssetUpdateProtry {Attribute<?> currentAttribute = getAttribute(em, assetStorageService, linkedAttributeRef).orElseThrow(() -> new AssetProcessingException(- Reason.ATTRIBUTE_NOT_FOUND,+ AttributeWriteFailure.ATTRIBUTE_NOT_FOUND,"cannot toggle value as attribute cannot be found: " + linkedAttributeRef));if (!Values.isNumber(currentAttribute.getType().getType())) {throw new AssetProcessingException(- Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,"cannot increment/decrement value as attribute is not of type NUMBER: " + linkedAttributeRef);}@@ -269,7 +269,7 @@ public class AttributeLinkingService implements ContainerService, AssetUpdatePro}default:throw new AssetProcessingException(- Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ AttributeWriteFailure.LINKED_ATTRIBUTE_CONVERSION_FAILURE,"converter is not supported: " + converter);}diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.javaindex 2ac22248e..d110964ca 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java@@ -15,6 +15,7 @@ import org.openremote.model.asset.Asset;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeWriteFailure;import org.openremote.model.datapoint.AssetDatapoint;import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.ValueDatapoint;@@ -135,7 +136,7 @@ public class AssetDatapointService implements ContainerService, AssetUpdateProcetry {pgJsonValue.setValue(Values.asJSON(attribute.getValue().orElse(null)).orElse("null"));} catch (SQLException e) {- throw new AssetProcessingException(AssetProcessingException.Reason.STATE_STORAGE_FAILED, "Failed to insert or update asset data point for attribute: " + attribute);+ throw new AssetProcessingException(AttributeWriteFailure.STATE_STORAGE_FAILED, "Failed to insert or update asset data point for attribute: " + attribute);}em.unwrap(Session.class).doWork(connection -> {diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.javaindex bcf571df5..1235f823d 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java@@ -42,6 +42,7 @@ import org.openremote.model.asset.impl.GatewayAsset;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeMap;+import org.openremote.model.attribute.AttributeWriteFailure;import org.openremote.model.event.shared.SharedEvent;import org.openremote.model.gateway.GatewayDisconnectEvent;import org.openremote.model.query.AssetQuery;@@ -328,7 +329,7 @@ public class GatewayService extends RouteBuilder implements ContainerService, As} else {if (!connector.isConnected()) {LOG.info("Gateway is not connected so attribute event for descendant asset will be dropped (Asset<?> ID=" + asset.getId() + ", Gateway ID=" + gatewayId + "): " + attribute);- throw new AssetProcessingException(AssetProcessingException.Reason.GATEWAY_DISCONNECTED, "Gateway is not connected: Gateway ID=" + connector.gatewayId);+ throw new AssetProcessingException(AttributeWriteFailure.GATEWAY_DISCONNECTED, "Gateway is not connected: Gateway ID=" + connector.gatewayId);}LOG.fine("Attribute event for a gateway descendant asset being forwarded to the gateway (Asset<?> ID=" + asset.getId() + ", Gateway ID=" + gatewayId + "): " + attribute);connector.sendMessageToGateway(diff --git a/model/build.gradle b/model/build.gradleindex 204d581a3..73341beab 100644--- a/model/build.gradle+++ b/model/build.gradle@@ -27,6 +27,8 @@ dependencies {compile "org.mnode.ical4j:ical4j:$ical4jVersion"compile "org.reflections:reflections:$reflectionsVersion"compile "com.google.guava:guava:$guavaVersion"++ compile "io.swagger:swagger-annotations:$swaggerVersion"}jar {diff --git a/model/src/main/java/org/openremote/model/asset/AssetResource.java b/model/src/main/java/org/openremote/model/asset/AssetResource.javaindex f81fbbdb0..8e2cde8e5 100644--- a/model/src/main/java/org/openremote/model/asset/AssetResource.java+++ b/model/src/main/java/org/openremote/model/asset/AssetResource.java@@ -19,8 +19,11 @@*/package org.openremote.model.asset;+import io.swagger.annotations.ApiOperation;import org.openremote.model.Constants;import org.openremote.model.attribute.AttributeRef;+import org.openremote.model.attribute.AttributeState;+import org.openremote.model.attribute.AttributeWriteResult;import org.openremote.model.http.RequestParams;import org.openremote.model.query.AssetQuery;import org.openremote.model.util.TsIgnore;@@ -29,6 +32,7 @@ import org.openremote.model.value.MetaItemType;import javax.annotation.security.RolesAllowed;import javax.validation.Valid;import javax.ws.rs.*;+import javax.ws.rs.core.Response;import java.util.List;import static javax.ws.rs.core.MediaType.APPLICATION_JSON;@@ -196,7 +200,13 @@ public interface AssetResource {@PUT@Path("{assetId}/attribute/{attributeName}")@Consumes(APPLICATION_JSON)- void writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, String valueStr);+ @ApiOperation(value="Write to a single attribute", response = AttributeWriteResult.class)+ Response writeAttributeValue(@BeanParam RequestParams requestParams, @PathParam("assetId") String assetId, @PathParam("attributeName") String attributeName, Object value);++ @PUT+ @Consumes(APPLICATION_JSON)+ @Path("attributes")+ AttributeWriteResult[] writeAttributeValues(@BeanParam RequestParams requestParams, AttributeState[] attributeStates);/*** Creates an asset. The identifier value of the asset can be provided, it should be a globally unique string value,diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeWriteFailure.java b/model/src/main/java/org/openremote/model/attribute/AttributeWriteFailure.javanew file mode 100644index 000000000..765de9fd9--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeWriteFailure.java@@ -0,0 +1,124 @@+/*+ * 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.attribute;++import org.openremote.model.asset.agent.Agent;+import org.openremote.model.value.ValueType;++public enum AttributeWriteFailure {++ /**+ * Missing {@link AttributeEvent.Source}.+ */+ MISSING_SOURCE,++ /**+ * The source of the event does not match the expected source (e.g. expected client message but received sensor+ * read).+ */+ ILLEGAL_SOURCE,++ /**+ * The asset does not exist.+ */+ ASSET_NOT_FOUND,++ /**+ * The attribute does not exist.+ */+ ATTRIBUTE_NOT_FOUND,++ /**+ * An actuator update must be for an attribute with a valid agent link.+ */+ INVALID_AGENT_LINK,++ /**+ * An attribute is linked to another attribute, but the link is invalid.+ */+ INVALID_ATTRIBUTE_LINK,++ /**+ * An attribute is linked to another attribute, but the linked attribute can't be written because conversion to the+ * target attribute's value failed.+ */+ LINKED_ATTRIBUTE_CONVERSION_FAILURE,++ /**+ * Attributes of an {@link Agent} can not be individually updated.+ */+ ILLEGAL_AGENT_UPDATE,++ /**+ * Invalid {@link AttributeExecuteStatus} for {@link Attribute} of type {@link ValueType#EXECUTION_STATUS}.+ */+ INVALID_ATTRIBUTE_EXECUTE_STATUS,++ /**+ * No authentication/authorization context available.+ */+ NO_AUTH_CONTEXT,++ /**+ * Realm configuration or user privileges do not allow update (e.g. realm inactive, user is missing required role,+ * attribute is read-only).+ */+ INSUFFICIENT_ACCESS,++ /**+ * The event timestamp is later than the processing time.+ */+ EVENT_IN_FUTURE,++ /**+ * The event timestamp is older than the last updated timestamp of the attribute.+ */+ EVENT_OUTDATED,++ /**+ * Applying the event violates constraints of the attribute.+ */+ ATTRIBUTE_VALIDATION_FAILURE,++ /**+ * Any other error, typically other runtime exceptions thrown by a processor.+ */+ PROCESSOR_FAILURE,++ /**+ * Writing the asset attribute state to database failed.+ */+ STATE_STORAGE_FAILED,++ /**+ * The event value is not the excepted value for the attribute+ */+ INVALID_VALUE_FOR_WELL_KNOWN_ATTRIBUTE,++ /**+ * The event is for a gateway descendant asset but the gateway is not connected+ */+ GATEWAY_DISCONNECTED,++ /**+ * Fallback failure when no other value makes sense+ */+ UNKNOWN+}diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeWriteResult.java b/model/src/main/java/org/openremote/model/attribute/AttributeWriteResult.javanew file mode 100644index 000000000..20ac6e14a--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeWriteResult.java@@ -0,0 +1,47 @@+/*+ * 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.attribute;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;++public class AttributeWriteResult {++ protected AttributeRef ref;+ protected AttributeWriteFailure failure;++ public AttributeWriteResult(AttributeRef ref) {+ this.ref = ref;+ }++ @JsonCreator+ public AttributeWriteResult(@JsonProperty("ref") AttributeRef ref, @JsonProperty("failure") AttributeWriteFailure failure) {+ this.ref = ref;+ this.failure = failure;+ }++ public AttributeRef getRef() {+ return ref;+ }++ public AttributeWriteFailure getFailure() {+ return failure;+ }+}diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 4262c9ad6..d214d9eb3 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -178,7 +178,7 @@ trait ContainerTrait {counter = 0def enginesStopped = falsewhile (!enginesStopped) {- enginesStopped = rulesService.tenantEngines == null && rulesService.tenantEngines.isEmpty() && rulesService.assetEngines.isEmpty()+ enginesStopped = (rulesService.tenantEngines == null || rulesService.tenantEngines.isEmpty()) && (rulesService.assetEngines == null || rulesService.assetEngines.isEmpty())if (counter++ > 100) {throw new IllegalStateException("Rule engines have failed to stop")}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovyindex 1174b003a..124f4e754 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy@@ -77,7 +77,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraittestAsset.getAttribute("foo").get().getValue().get() == "bar"when: "an asset attribute value is written directly"- assetResource.writeAttributeValue(null, testAsset.getId(), "foo", "bar2")+ assetResource.writeAttributeValue(null, testAsset.getId(), "foo", '"bar2"')then: "the attribute value should match"new PollingConditions(timeout: 5, delay: 0.2).eventually {diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex bb1647d8b..f4651e440 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -180,7 +180,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 404when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, "Teststreet 123")+ assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')then: "result should match"BuildingAsset asset@@ -191,21 +191,19 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai}when: "an non-existent assets attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, "doesnotexist", BuildingAsset.STREET.name, "Teststreet 123")+ def response = assetResource.writeAttributeValue(null, "doesnotexist", BuildingAsset.STREET.name, '"Teststreet 123"')then: "the attribute should be not found"- ex = thrown()- ex.response.status == 404+ response.status == 404when: "an non-existent attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, "doesnotexist", "Teststreet 123")+ response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, "doesnotexist", '"Teststreet 123"')then: "the attribute should be not found"- ex = thrown()- ex.response.status == 404+ response.status == 404when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, "Teststreet 456")+ assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 456"')then: "result should match"conditions.eventually {@@ -367,7 +365,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, "Teststreet 123")+ assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')then: "result should match"conditions.eventually {@@ -376,11 +374,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai}when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, "Teststreet 456")+ def response = assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 456"')then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403}def "Access assets as testuser2"() {@@ -512,18 +509,16 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "an asset attribute is written in the authenticated realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, "Teststreet 123")+ def response = assetResource.writeAttributeValue(null, managerTestSetup.smartBuildingId, BuildingAsset.STREET.name, '"Teststreet 123"')then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, "Teststreet 456")+ response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 456"')then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403}def "Access assets as testuser3"() {@@ -744,53 +739,46 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiex.response.status == 403when: "a private asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "lightSwitch", "false")+ def response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "lightSwitch", false)then: "the attribute should be not found"- ex = thrown()- ex.response.status == 404+ response.status == 404when: "a restricted read-only asset attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "currentTemperature", "22.123")+ response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "currentTemperature", 22.123)then: "the request should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403when: "an attribute is written on a non-existent user asset"- assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", "false")+ response = assetResource.writeAttributeValue(null, "doesnotexist", "lightSwitch", false)then: "the attribute should be not found"- ex = thrown()- ex.response.status == 404+ response.status == 404when: "an non-existent attribute is written on a user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "doesnotexist", "foo")+ response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1LivingroomId, "doesnotexist", '"foo"')then: "the attribute should be not found"- ex = thrown()- ex.response.status == 404+ response.status == 404when: "an asset attribute is written on a non-user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment3LivingroomId, "lightSwitch", "false")+ response = assetResource.writeAttributeValue(null, managerTestSetup.apartment3LivingroomId, "lightSwitch", false)then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403when: "an asset attribute is written in a foreign realm"- assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, "Teststreet 123")+ response = assetResource.writeAttributeValue(null, managerTestSetup.smartOfficeId, BuildingAsset.STREET.name, '"Teststreet 123"')then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403when: "a non-writable attribute value is written on a user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "presenceDetected", "true")+ response = assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "presenceDetected", true)then: "access should be forbidden"- ex = thrown()- ex.response.status == 403+ response.status == 403when: "a non-writable attribute value is updated on a user asset"testAsset = assetResource.get(null, managerTestSetup.apartment1KitchenId)@@ -820,7 +808,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassert testAsset.getAttribute("myCustomAttribute").get().getValue().get() == 123when: "a writable attribute value is written on a user asset"- assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "myCustomAttribute", "456")+ assetResource.writeAttributeValue(null, managerTestSetup.apartment1KitchenId, "myCustomAttribute", 456)then: "result should match"conditions.eventually {diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex 5e8bb2938..ddd10e28b 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -348,7 +348,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {messages.clear()and: "an authenticated user updates the location of a linked console"- authenticatedAssetResource.writeAttributeValue(null, testUser3Console1.id, Asset.LOCATION.name, Values.asJSON(new GeoJSONPoint(0d, 0d, 0d)).orElse(null))+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console1.id, Asset.LOCATION.name, new GeoJSONPoint(0d, 0d, 0d))then: "the consoles location should have been updated"conditions.eventually {@@ -369,7 +369,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {// ex.response.status == 403when: "a console's location is updated to be at the Smart Building"- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, Values.asJSON(SMART_BUILDING_LOCATION).orElse(null))+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, SMART_BUILDING_LOCATION)long timestamp = Long.MAX_VALUEthen: "a welcome home alert should be sent to the console"@@ -384,7 +384,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {advancePseudoClock(1, TimeUnit.SECONDS, container)and: "a console's location is updated to be at the Smart Building again"- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, Values.asJSON(SMART_BUILDING_LOCATION).orElse(null))+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, SMART_BUILDING_LOCATION)then: "no more alerts should have been sent"conditions.eventually {@@ -417,7 +417,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {advancePseudoClock(1, TimeUnit.SECONDS, container)and: "a console's location is updated to be at the Smart Building again"- authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, Values.asJSON(SMART_BUILDING_LOCATION).orElse(null))+ authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, Asset.LOCATION.name, SMART_BUILDING_LOCATION)then: "another alert should have been sent"conditions.eventually {diff --git a/ui/component/or-app/src/or-header.ts b/ui/component/or-app/src/or-header.tsindex 98a58d69e..ea4a9a442 100644--- a/ui/component/or-app/src/or-header.ts+++ b/ui/component/or-app/src/or-header.ts@@ -457,7 +457,7 @@ class OrHeader extends LitElement {${getContentWithMenuTemplate(html`<div id="realm-picker">- <span>${tenants.find((t) => t.realm === manager.displayRealm)?.displayName}</span>+ <span>${tenants.find((t) => t.realm === manager.displayRealm)?.displayName}</span><or-icon icon="chevron-down"></or-icon></div>`,