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
Wrap all attribute event processing in a database transaction, cleanup asset state classes for rules
Christian Bauer2db81c5e18be
diff --git a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.javaindex 1a1d58aae..4bdb96efa 100644--- a/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/AbstractProtocol.java@@ -295,9 +295,9 @@ public abstract class AbstractProtocol implements Protocol {return;}- if (state.getCurrentValue().isPresent()) {+ if (state.getValue().isPresent()) {List<MessageFilter> filters;- Value value = state.getCurrentValue().get();+ Value value = state.getValue().get();synchronized (linkedAttributeFilters) {filters = linkedAttributeFilters.get(state.getAttributeRef());@@ -361,7 +361,7 @@ public abstract class AbstractProtocol implements Protocol {if (updateLocation) {// Check value type is compatible- Point location = state.getCurrentValue().map(value -> {+ Point location = state.getValue().map(value -> {if (value.getType() != ValueType.ARRAY) {LOG.warning("Location linked attribute type is not an array");return null;diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.javaindex 3886a7472..d06779a22 100644--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java@@ -249,7 +249,7 @@ public class MacroProtocol extends AbstractProtocol {LOG.fine("No actions are available for the linked macro, maybe it is disabled?: " + macroRef);} else {actionIndex = Math.min(actions.size(), Math.max(0, actionIndex));- actionValue = actions.get(actionIndex).getAttributeState().getCurrentValue().orElse(null);+ actionValue = actions.get(actionIndex).getAttributeState().getValue().orElse(null);LOG.fine("Attribute is linked to the value of macro action index: actionIndex");}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.javaindex 8070e1537..47a5e0dc9 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@@ -416,7 +416,7 @@ public class SimulatorProtocol extends AbstractProtocol {}Optional<Value> oldValue = element.getValue();- element.setValue(attributeState.getCurrentValue().orElse(null));+ element.setValue(attributeState.getValue().orElse(null));List<ValidationFailure> failures = element.getValidationFailures();if (!failures.isEmpty()) {diff --git a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.javaindex cb75c4626..b093d77f0 100644--- a/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/timer/TimerProtocol.java@@ -338,7 +338,7 @@ public class TimerProtocol extends AbstractProtocol {MetaItem.replaceMetaByName(protocolConfig.getMeta(),META_TIMER_CRON_EXPRESSION,- state.getCurrentValue().orElse(null)+ state.getValue().orElse(null));});diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.javaindex 795d71315..53055e8ae 100644--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java@@ -30,20 +30,20 @@ import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.timer.TimerService;import org.openremote.container.web.WebService;-import org.openremote.manager.asset.AssetProcessingService;-import org.openremote.manager.asset.AssetStorageService;-import org.openremote.manager.asset.ServerAsset;+import org.openremote.manager.asset.*;import org.openremote.manager.event.ClientEventService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.asset.*;import org.openremote.model.asset.agent.*;import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.event.shared.TenantFilter;import org.openremote.model.security.ClientRole;import org.openremote.model.util.Pair;import org.openremote.model.value.ObjectValue;+import javax.persistence.EntityManager;import java.util.*;import java.util.function.Consumer;import java.util.function.Predicate;@@ -56,8 +56,8 @@ import static org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC;import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;import static org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE;-import static org.openremote.manager.asset.AssetRoute.isPersistenceEventForAssetType;-import static org.openremote.manager.asset.AssetRoute.isPersistenceEventForEntityType;+import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForAssetType;+import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;@@ -65,6 +65,7 @@ import static org.openremote.model.asset.AssetType.AGENT;import static org.openremote.model.asset.agent.AgentLink.getAgentLink;import static org.openremote.model.asset.agent.ConnectionStatus.*;import static org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE;+import static org.openremote.model.attribute.AttributeEvent.Source.SENSOR;import static org.openremote.model.util.TextUtil.isNullOrEmpty;import static org.openremote.model.util.TextUtil.isValidURN;@@ -73,7 +74,7 @@ import static org.openremote.model.util.TextUtil.isValidURN;* <p>* Finds all {@link AssetType#AGENT} assets and manages their {@link ProtocolConfiguration}s.*/-public class AgentService extends RouteBuilder implements ContainerService, Consumer<AssetState>, ProtocolAssetService {+public class AgentService extends RouteBuilder implements ContainerService, AssetUpdateProcessor, ProtocolAssetService {private static final Logger LOG = Logger.getLogger(AgentService.class.getName());@@ -102,9 +103,9 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsclientEventService.addSubscriptionAuthorizer((auth, subscription) ->subscription.isEventType(AgentStatusEvent.class)&& identityService.getIdentityProvider()- .canSubscribeWith(auth, subscription.getFilter() instanceof TenantFilter- ? ((TenantFilter) subscription.getFilter())- : null, ClientRole.READ_ASSETS));+ .canSubscribeWith(auth, subscription.getFilter() instanceof TenantFilter+ ? ((TenantFilter) subscription.getFilter())+ : null, ClientRole.READ_ASSETS));container.getService(WebService.class).getApiSingletons().add(new AgentResourceImpl(@@ -180,7 +181,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Consfrom(SENSOR_QUEUE).routeId("FromSensorUpdates").filter(body().isInstanceOf(AttributeEvent.class))- .setHeader(HEADER_SOURCE, () -> AttributeEvent.Source.SENSOR)+ .setHeader(HEADER_SOURCE, () -> SENSOR).to(ASSET_QUEUE);}@@ -256,7 +257,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons).collect(Collectors.toList());List<AssetAttribute> removedAttributes = getAddedOrModifiedAttributes(- updatedAttributes, existingAttributes, options.getIgnoredAttributeNames(), options.getIgnoredAttributeKeys()+ updatedAttributes, existingAttributes, options.getIgnoredAttributeNames(), options.getIgnoredAttributeKeys()).collect(Collectors.toList());if (addedOrModifiedAttributes.isEmpty() && removedAttributes.isEmpty()) {@@ -635,23 +636,19 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons* required (i.e. the protocol is responsible for synchronising state with the database).*/@Override- public void accept(AssetState assetState) {- if (assetState.getSource() == AttributeEvent.Source.SENSOR) {- return;+ public boolean processAssetUpdate(EntityManager entityManager, Asset asset, AssetAttribute attribute, Source source) throws AssetProcessingException {+ if (source == SENSOR) {+ return false;}- AgentLink.getAgentLink(assetState.getAttribute())+ return AgentLink.getAgentLink(attribute).map(ref ->getProtocolConfiguration(ref)- .orElseGet(() -> {- assetState.setError(new RuntimeException("Attribute has an invalid agent link: " + assetState.getAttribute()));- assetState.setProcessingStatus(AssetState.ProcessingStatus.ERROR);- return null;- })+ .orElseThrow(() -> new AssetProcessingException(AssetProcessingException.Reason.INVALID_AGENT_LINK))).map(protocolConfiguration -> {// Its' a send to actuator - push the update to the protocol- assetState.getAttribute().getStateEvent().ifPresent(attributeEvent -> {+ attribute.getStateEvent().ifPresent(attributeEvent -> {LOG.fine("Sending to actuator topic: " + attributeEvent);messageBrokerService.getProducerTemplate().sendBodyAndHeader(ACTUATOR_TOPIC,@@ -660,13 +657,9 @@ public class AgentService extends RouteBuilder implements ContainerService, ConsprotocolConfiguration.getValueAsString().orElse(""));});- assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);- return protocolConfiguration;+ return true; // Processing complete, skip other processors})- .orElseGet(() -> {- // This is just a non protocol attribute so allow the processing to continue- return null;- });+ .orElse(false); // This is just a non protocol attribute so allow the processing to continue}/**diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.javaindex 5e1c3cf77..50c3be36f 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java@@ -21,30 +21,29 @@ package org.openremote.manager.asset;import org.openremote.container.Container;import org.openremote.container.ContainerService;+import org.openremote.manager.asset.AssetProcessingException.Reason;+import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetMeta;import org.openremote.model.asset.AssetQuery;-import org.openremote.model.asset.AssetState;-import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.attribute.AttributeLink;-import org.openremote.model.attribute.AttributeRef;-import org.openremote.model.attribute.MetaItem;+import org.openremote.model.attribute.*;+import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.util.Pair;import org.openremote.model.value.*;+import javax.persistence.EntityManager;import java.util.Locale;import java.util.NoSuchElementException;import java.util.Optional;-import java.util.function.Consumer;import java.util.logging.Logger;import static org.openremote.model.asset.AssetQuery.Include;import static org.openremote.model.asset.AssetQuery.Select;+import static org.openremote.model.attribute.AttributeEvent.Source.ATTRIBUTE_LINKING_SERVICE;import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;/**- * This service listens for attribute events on attributes that have one or more {@link AssetMeta#ATTRIBUTE_LINK} meta- * items.+ * This service processes asset updates on attributes that have one or more {@link AssetMeta#ATTRIBUTE_LINK} meta items.* <p>* If such an event occurs then the event is 'forwarded' to the linked attribute; an attribute can contain multiple* {@link AssetMeta#ATTRIBUTE_LINK} meta items; optionally the value forwarded to the linked attribute can be modified@@ -58,13 +57,6 @@ import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;* <p>* To convert null values the converter key of "NULL" can be used.* <p>- * <b>- * NOTE: State converters (e.g. {@link AttributeLink.ConverterType#TOGGLE}, {@link AttributeLink.ConverterType#INCREMENT}, {@link AttributeLink.ConverterType#DECREMENT}) are- * not synchronised so if the initiating attribute (the one with the {@link AssetMeta#ATTRIBUTE_LINK} meta items)- * generates multiple attribute events in a short period of time then the value pushed to the linked attribute may not- * be correct.- * </b>- * <p>* Example {@link AssetMeta#ATTRIBUTE_LINK} meta items:* <blockquote><pre>{@code* [@@ -92,7 +84,7 @@ import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo;* }</pre></blockquote>*/// TODO: Improve AssetAttributeLinkingService so that outbound events are synchronsied with inbound-public class AssetAttributeLinkingService implements ContainerService, Consumer<AssetState> {+public class AssetAttributeLinkingService implements ContainerService, AssetUpdateProcessor {private static final Logger LOG = Logger.getLogger(AssetAttributeLinkingService.class.getName());protected AssetProcessingService assetProcessingService;@@ -113,49 +105,57 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<}@Override- public void accept(AssetState assetState) {- if (assetState.getSource() == AttributeEvent.Source.ATTRIBUTE_LINKING_SERVICE) {- LOG.fine("Attribute update came from this service so ignoring to avoid infinite loops: " + assetState);- return;+ public boolean processAssetUpdate(EntityManager em,+ Asset asset,+ AssetAttribute attribute,+ Source source) throws AssetProcessingException {+ if (source == ATTRIBUTE_LINKING_SERVICE) {+ LOG.fine("Attribute update came from this service so ignoring to avoid infinite loops: " + attribute);+ return false;}- assetState- .getAttribute()- .getMetaStream()+ attribute.getMetaStream().filter(isMetaNameEqualTo(AssetMeta.ATTRIBUTE_LINK))- .forEach(metaItem -> processLinkedAttributeUpdate(metaItem, assetState));+ .forEach(metaItem -> processLinkedAttributeUpdate(em, metaItem, attribute.getState().orElse(null)));++ return false;}protected void sendAttributeEvent(AttributeEvent attributeEvent) {LOG.fine("Sending attribute event for linked attribute: " + attributeEvent);- assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.ATTRIBUTE_LINKING_SERVICE);+ assetProcessingService.sendAttributeEvent(attributeEvent, ATTRIBUTE_LINKING_SERVICE);}- protected void processLinkedAttributeUpdate(MetaItem metaItem, AssetState assetState) {- LOG.fine("Processing attribute event for linked attribute");+ protected void processLinkedAttributeUpdate(EntityManager em, MetaItem metaItem, AttributeState attributeState) {+ if (attributeState == null)+ return;+ LOG.fine("Processing attribute state for linked attribute");Optional<AttributeLink> attributeLink = metaItem.getValue().flatMap(AttributeLink::fromValue);if (!attributeLink.isPresent()) {- LOG.info("Invalid attribute link on: " + assetState.getAttributeRef());- return;+ throw new AssetProcessingException(Reason.INVALID_ATTRIBUTE_LINK);}// Convert the value as requiredPair<Boolean, Value> sendConvertedValue = convertValueForLinkedAttribute(- assetState.getValue().orElse(null),- attributeLink.get(),- assetStorageService+ em,+ assetStorageService,+ attributeState.getValue().orElse(null),+ attributeLink.get());if (!sendConvertedValue.key) {- // Do not forward the event (either marked as ignored or there was a problem with the value conversion)+ // Do not forward the attribute state (conversion resulted in NULL or IGNORE)return;}sendAttributeEvent(new AttributeEvent(attributeLink.get().getAttributeRef(), sendConvertedValue.value));}- protected static Pair<Boolean, Value> convertValueForLinkedAttribute(Value originalValue, AttributeLink attributeLink, AssetStorageService assetStorageService) {+ protected static Pair<Boolean, Value> convertValueForLinkedAttribute(EntityManager em,+ AssetStorageService assetStorageService,+ Value originalValue,+ AttributeLink attributeLink) throws AssetProcessingException {return attributeLink.getConverter().map(converter -> {@@ -165,7 +165,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<return converterValue.map(value ->getSpecialConverter(value)- .map(c -> doSpecialConversion(c, attributeLink.getAttributeRef(), assetStorageService))+ .map(c -> doSpecialConversion(em, assetStorageService, c, attributeLink.getAttributeRef())).orElse(new Pair<>(true, value))) // use the converter value as the new value.orElseGet(() -> new Pair<>(true, originalValue)); // use the original value})@@ -179,7 +179,10 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<return Optional.empty();}- protected static Pair<Boolean, Value> doSpecialConversion(AttributeLink.ConverterType converter, AttributeRef linkedAttributeRef, AssetStorageService assetStorageService) {+ protected static Pair<Boolean, Value> doSpecialConversion(EntityManager em,+ AssetStorageService assetStorageService,+ AttributeLink.ConverterType converter,+ AttributeRef linkedAttributeRef) throws AssetProcessingException {switch (converter) {case IGNORE:LOG.fine("Converter set to ignore value so not forwarding to linked attribute");@@ -187,12 +190,14 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<case NULL:return new Pair<>(true, null);case TOGGLE:- // Look up current value of the linked attribute+ // Look up current value of the linked attribute within the same database sessiontry {- Value currentValue = getCurrentValue(linkedAttributeRef, assetStorageService);+ Value currentValue = getCurrentValue(em, assetStorageService, linkedAttributeRef);if (currentValue == null || currentValue.getType() != ValueType.BOOLEAN) {- LOG.fine("Cannot toggle attribute value as attribute is not of type BOOLEAN: " + linkedAttributeRef);- return new Pair<>(false, null);+ throw new AssetProcessingException(+ Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ "cannot toggle value as attribute is not of type BOOLEAN: " + linkedAttributeRef+ );}return new Pair<>(true, Values.create(!((BooleanValue) currentValue).getBoolean()));} catch (NoSuchElementException e) {@@ -201,12 +206,14 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<}case INCREMENT:case DECREMENT:- // Look up current value of the linked attribute+ // Look up current value of the linked attribute within the same database sessiontry {- Value currentValue = getCurrentValue(linkedAttributeRef, assetStorageService);+ Value currentValue = getCurrentValue(em, assetStorageService, linkedAttributeRef);if (currentValue == null || currentValue.getType() != ValueType.NUMBER) {- LOG.fine("Cannot increment/decrement attribute value as attribute is not of type NUMBER: " + linkedAttributeRef);- return new Pair<>(false, null);+ throw new AssetProcessingException(+ Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ "cannot increment/decrement value as attribute is not of type NUMBER: " + linkedAttributeRef+ );}int change = converter == AttributeLink.ConverterType.INCREMENT ? +1 : -1;return new Pair<>(true, Values.create(((NumberValue) currentValue).getNumber() + change));@@ -215,12 +222,18 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<return new Pair<>(false, null);}default:- throw new UnsupportedOperationException("Converter is not supported: " + converter);+ throw new AssetProcessingException(+ Reason.LINKED_ATTRIBUTE_CONVERSION_FAILURE,+ "converter is not supported: " + converter+ );}}- protected static Value getCurrentValue(AttributeRef attributeRef, AssetStorageService assetStorageService) throws NoSuchElementException {+ protected static Value getCurrentValue(EntityManager em,+ AssetStorageService assetStorageService,+ AttributeRef attributeRef) throws NoSuchElementException {ServerAsset asset = assetStorageService.find(+ em,new AssetQuery().id(attributeRef.getEntityId()).select(new Select(Include.ALL, false, attributeRef.getAttributeName()))diff --git a/model/src/main/java/org/openremote/model/asset/AssetProcessingException.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.javasimilarity index 81%rename from model/src/main/java/org/openremote/model/asset/AssetProcessingException.javarename to manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.javaindex acc692b1d..6c1bf9ec2 100644--- a/model/src/main/java/org/openremote/model/asset/AssetProcessingException.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingException.java@@ -17,7 +17,7 @@* 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;+package org.openremote.manager.asset;import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetType;@@ -52,10 +52,21 @@ public class AssetProcessingException extends RuntimeException {ATTRIBUTE_NOT_FOUND,/**- * A sensor update must be for an attribute with a valid agent link.+ * 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 AssetType#AGENT} can not be individually updated.*/@@ -92,6 +103,16 @@ public class AssetProcessingException extends RuntimeException {* 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}final protected Reason 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 1ecb232da..0689305d5 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java@@ -20,12 +20,14 @@package org.openremote.manager.asset;import org.apache.camel.Exchange;+import org.apache.camel.Processor;import org.apache.camel.builder.RouteBuilder;import org.openremote.agent.protocol.Protocol;import org.openremote.container.Container;import org.openremote.container.ContainerService;import org.openremote.container.message.MessageBrokerService;import org.openremote.container.message.MessageBrokerSetupService;+import org.openremote.container.persistence.PersistenceService;import org.openremote.container.security.AuthContext;import org.openremote.container.timer.TimerService;import org.openremote.manager.agent.AgentService;@@ -33,35 +35,41 @@ import org.openremote.manager.datapoint.AssetDatapointService;import org.openremote.manager.event.ClientEventService;import org.openremote.manager.rules.RulesService;import org.openremote.manager.security.ManagerIdentityService;-import org.openremote.model.asset.AssetProcessingException;-import org.openremote.model.asset.AssetResource;import org.openremote.model.Constants;+import org.openremote.model.ValidationFailure;import org.openremote.model.asset.*;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeEvent.Source;+import org.openremote.model.attribute.AttributeExecuteStatus;+import org.openremote.model.rules.AssetEvent;+import org.openremote.model.rules.AssetState;import org.openremote.model.security.ClientRole;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;+import javax.persistence.EntityManager;import java.util.ArrayList;+import java.util.Date;import java.util.List;-import java.util.function.Consumer;+import java.util.Optional;import java.util.logging.Level;import java.util.logging.Logger;-import static org.openremote.manager.asset.AssetRoute.*;+import static org.openremote.manager.asset.AssetProcessingException.Reason.*;import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;+import static org.openremote.model.asset.agent.AgentLink.getAgentLink;import static org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE;-import static org.openremote.model.attribute.AttributeEvent.Source.CLIENT;-import static org.openremote.model.attribute.AttributeEvent.Source.INTERNAL;+import static org.openremote.model.attribute.AttributeEvent.Source.*;/**- * Receives {@link AttributeEvent}s from {@link AttributeEvent.Source}s and processes them.+ * Receives {@link AttributeEvent} from {@link Source} and processes them.* <dl>- * <dt>{@link AttributeEvent.Source#CLIENT}</dt>+ * <dt>{@link Source#CLIENT}</dt>* <dd><p>Client events published through event bus or sent by web service. These exchanges must contain an {@link AuthContext}* header named {@link Constants#AUTH_CONTEXT}.</dd>- * <dt>{@link AttributeEvent.Source#INTERNAL}</dt>- * <dd><p>Events sent to {@link #ASSET_QUEUE} or through {@link #sendAttributeEvent} convenience method.</dd>- * <dt>{@link AttributeEvent.Source#SENSOR}</dt>+ * <dt>{@link Source#INTERNAL}</dt>+ * <dd><p>Events sent to {@link #ASSET_QUEUE} or through {@link #sendAttributeEvent} convenience method by processors.</dd>+ * <dt>{@link Source#SENSOR}</dt>* <dd><p>Protocol sensor updates sent to {@link Protocol#SENSOR_QUEUE}.</dd>* </dl>* NOTE: An attribute value can be changed during Asset CRUD but this does not come through@@ -85,15 +93,12 @@ import static org.openremote.model.attribute.AttributeEvent.Source.INTERNAL;* <h2>Agent service processing logic</h2>* <p>* The agent service's role is to communicate asset attribute writes to actuators, through protocols.- * When the update messages' source is {@link AttributeEvent.Source#SENSOR}, the agent service ignores the message.+ * When the update messages' source is {@link Source#SENSOR}, the agent service ignores the message.* The message will also be ignored if the updated attribute is not linked to a protocol configuration.* <p>- * If the updated attribute has an invalid agent link, the message status is set to {@link AssetState.ProcessingStatus#ERROR}.- * <p>* If the updated attribute has a valid agent link, an {@link AttributeEvent} is sent on the {@link Protocol#ACTUATOR_TOPIC},- * for execution on an actual device or service 'things'. The update is then marked as- * {@link AssetState.ProcessingStatus#COMPLETED} and no further processing is necessary. The update will not reach the- * rules engine or the database processors.+ * for execution on an actual device or service 'things'. The update is then considered complete, and no further processing+ * is necessary. The update will not reach the rules engine or the database.* <p>* This means that a protocol implementation is responsible for producing a new {@link AttributeEvent} to* indicate to the rules and database memory that the attribute value has/has not changed. The protocol should know@@ -133,6 +138,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprotected TimerService timerService;protected ManagerIdentityService identityService;+ protected PersistenceService persistenceService;protected RulesService rulesService;protected AgentService agentService;protected AssetStorageService assetStorageService;@@ -143,12 +149,13 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// Used in testing to detect if initial/startup processing has completedprotected long lastProcessedEventTimestamp = System.currentTimeMillis();- final protected List<Consumer<AssetState>> processors = new ArrayList<>();+ final protected List<AssetUpdateProcessor> processors = new ArrayList<>();@Overridepublic void init(Container container) throws Exception {timerService = container.getService(TimerService.class);identityService = container.getService(ManagerIdentityService.class);+ persistenceService = container.getService(PersistenceService.class);rulesService = container.getService(RulesService.class);agentService = container.getService(AgentService.class);assetStorageService = container.getService(AssetStorageService.class);@@ -200,7 +207,6 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprocessors.add(agentService);processors.add(rulesService);- processors.add(assetStorageService);processors.add(assetDatapointService);processors.add(assetAttributeLinkingService);@@ -228,7 +234,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer.to(ASSET_QUEUE);// Process attribute events- /* TODO This message consumer should be transactionally consistent with the database, this is currenlty not the case+ /* TODO This message consumer should be transactionally consistent with the database, this is currently not the caseOur "if I have not processed this message before" duplicate detection:@@ -238,34 +244,16 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerPossible improvements moving towards at-least-once:- - Hibernate ThreadLocal Session & Transaction for the whole Camel Exchange/route- 0. Receive attribute event, security/404 checks- 1. Open DB local transaction- 2. Read last asset state- 3. Write non-duplicate attribute event- 4. Commit DB local transaction- 5. Commit reception on message broker-- - See pseudocode here: http://activemq.apache.org/should-i-use-xa.html-- - Replace at-most-once ClientEventService with at-least-once capable, embeddable message broker/protocol-- - Do we want JMS/AMQP/WSS or SOME_API/MQTT/WSS? ActiveMQ or Moquette?+ - Make AssetUpdateProcessor transactional with a two-phase commit API+ - Replace at-most-once ClientEventService with at-least-once capable, embeddable message broker/protocol+ - See pseudocode here: http://activemq.apache.org/should-i-use-xa.html+ - Do we want JMS/AMQP/WSS or SOME_API/MQTT/WSS? ActiveMQ or Moquette?*/from(ASSET_QUEUE).routeId("AssetUpdates").filter(body().isInstanceOf(AttributeEvent.class)).doTry()- .process(extractAttributeEventDetails(assetStorageService))- .process(validateAttributeEvent())- .choice()- .when(header(HEADER_SOURCE).isEqualTo(CLIENT))- .process(validateAttributeEventFromClient(assetStorageService, identityService))- .when(header(HEADER_SOURCE).isEqualTo(Source.SENSOR))- .process(validateAttributeEventFromSensor(agentService))- .end()- .process(buildAssetState(timerService))- .process(this::processAssetState)+ .process(processAttributeEvent()).endDoTry().doCatch(AssetProcessingException.class).process(handleAssetProcessingException(LOG));@@ -277,7 +265,8 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerpublic void sendAttributeEvent(AttributeEvent attributeEvent) {sendAttributeEvent(attributeEvent, INTERNAL);}- public void sendAttributeEvent(AttributeEvent attributeEvent, AttributeEvent.Source source) {++ public void sendAttributeEvent(AttributeEvent attributeEvent, Source source) {// Set event source time if not already setif (attributeEvent.getTimestamp() <= 0) {attributeEvent.setTimestamp(timerService.getCurrentTimeMillis());@@ -286,46 +275,237 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer}/**- * This deals with single {@link AssetState} and pushes them through the chain where each- * consumer is given the opportunity to consume the event or allow its progress to the next- * consumer, see {@link AssetState.ProcessingStatus}.+ * This deals with single {@link AssetAttribute} updates and pushes them through the chain where each+ * processor is given the opportunity to consume the update or allow its progress to the next+ * processor, see {@link AssetUpdateProcessor#processAssetUpdate}.*/- protected void processAssetState(Exchange exchange) {- AssetState assetState = exchange.getIn().getHeader(HEADER_ASSET_STATE, AssetState.class);- LOG.fine(">>> Processing start: " + assetState);+ protected void processAssetUpdate(EntityManager em,+ Asset asset,+ AssetAttribute attribute,+ Source source) throws AssetProcessingException {+ LOG.fine(">>> Processing start: " + attribute);+// Need to record time here otherwise an infinite loop generated inside one of the processors means the timestamp// is not updated so tests can't then detect the problem.lastProcessedEventTimestamp = System.currentTimeMillis();- processorLoop:- for (Consumer<AssetState> processor : processors) {++ boolean complete;+ for (AssetUpdateProcessor processor : processors) {+ LOG.finest("==> Processor " + processor + " accepts: " + attribute);try {- LOG.finest("==> Processor " + processor + " accepts: " + assetState);- processor.accept(assetState);+ complete = processor.processAssetUpdate(em, asset, attribute, source);+ } catch (AssetProcessingException ex) {+ throw ex;} catch (Throwable t) {- LOG.log(Level.SEVERE, "!!! Processor " + processor + " threw an exception whilst consuming: " + assetState, t);- assetState.setProcessingStatus(AssetState.ProcessingStatus.ERROR);- assetState.setError(t);+ throw new AssetProcessingException(+ PROCESSOR_FAILURE,+ "processor '" + processor + "' threw exception: " + t.toString()+ );}-- switch (assetState.getProcessingStatus()) {- case COMPLETED:- LOG.finest("<== Processor " + processor + " finally handled: " + assetState);- break processorLoop;- case ERROR:- LOG.log(Level.SEVERE, "<== Processor " + processor + " error: " + assetState, assetState.getError());- break processorLoop;- default:- LOG.finest("<== Processor " + processor + " done with: " + assetState);+ if (complete) {+ LOG.finest("<== Processor " + processor + " finally handled: " + attribute);+ break;+ } else {+ LOG.finest("<== Processor " + processor + " done with: " + attribute);}}- if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.ERROR) {- if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.COMPLETED)- assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);- clientEventService.publishEvent(new AttributeEvent(- assetState.getId(), assetState.getAttributeName(), assetState.getValue().orElse(null), timerService.getCurrentTimeMillis()- ));++ // Store state in database after all processors are done+ storeAttribute(em, asset, attribute);++ LOG.fine("<<< Processing complete: " + attribute);+ }++ public Processor processAttributeEvent() {+ return exchange -> {+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);+ if (event.getEntityId() == null || event.getEntityId().isEmpty())+ return;+ if (event.getAttributeName() == null || event.getAttributeName().isEmpty())+ return;+ Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Source.class);+ if (source == null) {+ throw new AssetProcessingException(MISSING_SOURCE);+ }++ // Process the asset update in a database transaction, this ensures that processors+ // will see consistent database state and we only commit if no processor failed. This+ // still won't make this procedure consistent with the message queue from which we consume!+ persistenceService.doTransaction(em -> {+ ServerAsset asset = assetStorageService.find(em, event.getEntityId(), true);+ if (asset == null)+ throw new AssetProcessingException(ASSET_NOT_FOUND);++ AssetAttribute attribute = asset.getAttribute(event.getAttributeName()).orElse(null);+ if (attribute == null)+ throw new AssetProcessingException(ATTRIBUTE_NOT_FOUND);++ // Agent attributes can't be updated with events+ if (asset.getWellKnownType() == AssetType.AGENT) {+ throw new AssetProcessingException(ILLEGAL_AGENT_UPDATE);+ }++ // For executable attributes, non-sensor sources can set a writable attribute execute status+ if (attribute.isExecutable() && source != SENSOR) {+ Optional<AttributeExecuteStatus> status = event.getValue()+ .flatMap(Values::getString)+ .flatMap(AttributeExecuteStatus::fromString);++ if (status.isPresent() && !status.get().isWrite()) {+ throw new AssetProcessingException(INVALID_ATTRIBUTE_EXECUTE_STATUS);+ }+ }++ switch (source) {+ case CLIENT:+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);+ if (authContext == null) {+ throw new AssetProcessingException(NO_AUTH_CONTEXT);+ }++ // Check realm, must be accessible+ if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);+ }++ // Check read-only+ if (attribute.isReadOnly() && !authContext.isSuperUser()) {+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);+ }++ // Regular user must have write assets role+ if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);+ }++ // Check restricted user+ if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {+ // Must be asset linked to user+ if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);+ }+ // Must be writable by restricted client+ if (!attribute.isAccessRestrictedWrite()) {+ throw new AssetProcessingException(INSUFFICIENT_ACCESS);+ }+ }+ break;++ case SENSOR:+ Optional<AssetAttribute> protocolConfiguration =+ getAgentLink(attribute).flatMap(agentService::getProtocolConfiguration);++ // Sensor event must be for an attribute linked to a protocol configuration+ if (!protocolConfiguration.isPresent()) {+ throw new AssetProcessingException(INVALID_AGENT_LINK);+ }+ break;+ }++ // Either use the timestamp of the event or set event time to processing time+ long processingTime = timerService.getCurrentTimeMillis();+ long eventTime = event.getTimestamp() > 0 ? event.getTimestamp() : processingTime;++ // Ensure timestamp of event is not in the future as that would essentially block access to+ // the attribute until after that time (maybe that is desirable behaviour)+ if (eventTime - processingTime > 0) {+ // TODO: Decide how to handle update events in the future - ignore or change timestamp+ throw new AssetProcessingException(+ EVENT_IN_FUTURE,+ "current time: " + new Date(processingTime) + "/" + processingTime+ + ", event time: " + new Date(eventTime) + "/" + eventTime+ );+ }++ // Check the last update timestamp of the attribute, ignoring any event that is older than last update+ // TODO This means we drop out-of-sequence events but accept events with the same source timestamp+ // TODO Several attribute events can occur in the same millisecond, then order of application is undefined+ attribute.getValueTimestamp().filter(t -> t >= 0 && eventTime < t).ifPresent(+ lastStateTime -> {+ throw new AssetProcessingException(+ EVENT_OUTDATED,+ "last asset state time: " + new Date(lastStateTime) + "/" + lastStateTime+ + ", event time: " + new Date(eventTime) + "/" + eventTime);+ }+ );++ // Create a copy of the attribute and set the new value and timestamp+ AssetAttribute updatedAttribute = attribute.deepCopy();+ updatedAttribute.setValue(event.getValue().orElse(null), eventTime);++ // Validate constraints of attribute+ List<ValidationFailure> validationFailures = updatedAttribute.getValidationFailures();+ if (!validationFailures.isEmpty()) {+ throw new AssetProcessingException(ATTRIBUTE_VALIDATION_FAILURE, validationFailures.toString());+ }++ // Push through all processors+ processAssetUpdate(em, asset, updatedAttribute, source);++ // Publish a new event for clients+ publishClientEvent(asset, attribute);+ });+ };+ }++ public static Processor handleAssetProcessingException(Logger logger) {+ return exchange -> {+ AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);+ Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);++ StringBuilder error = new StringBuilder();++ Source source = exchange.getIn().getHeader(HEADER_SOURCE, "unknown source", Source.class);+ if (source != null) {+ error.append("Error processing from ").append(source);+ }++ String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);+ if (protocolName != null) {+ error.append(" (protocol: ").append(protocolName).append(")");+ }++ // TODO Better exception handling - dead letter queue?+ if (exception instanceof AssetProcessingException) {+ AssetProcessingException processingException = (AssetProcessingException) exception;+ error.append(" - ").append(processingException.getReasonPhrase());+ error.append(": ").append(event.toString());+ logger.warning(error.toString());+ } else {+ error.append(": ").append(event.toString());+ logger.log(Level.WARNING, error.toString(), exception);+ }++ // Make the exception available if MEP is InOut+ exchange.getOut().setBody(exception);+ };+ }++ protected void storeAttribute(EntityManager em, Asset asset, AssetAttribute attribute) throws AssetProcessingException {+ String attributeName = attribute.getName()+ .orElseThrow(() -> new AssetProcessingException(+ STATE_STORAGE_FAILED,+ "cannot store asset state for attribute with no name on: " + asset)+ );+ Value value = attribute.getValue().orElse(null);++ // If there is no timestamp, use system time (0 or -1 are "no timestamp")+ Optional<Long> timestamp = attribute.getValueTimestamp();+ String valueTimestamp = Long.toString(+ timestamp.filter(ts -> ts > 0).orElseGet(() -> timerService.getCurrentTimeMillis())+ );++ if (!assetStorageService.storeAttributeValue(em, asset.getId(), attributeName, value, valueTimestamp)) {+ throw new AssetProcessingException(+ STATE_STORAGE_FAILED, "database update failed, no rows updated"+ );}- LOG.fine("<<< Processing complete: " + assetState);+ }++ protected void publishClientEvent(Asset asset, AssetAttribute attribute) {+ clientEventService.publishEvent(new AttributeEvent(+ asset.getId(), attribute.getNameOrThrow(), attribute.getValue().orElse(null), timerService.getCurrentTimeMillis()+ ));}@Overridediff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.javaindex 1be67240f..d769af58d 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java@@ -23,7 +23,6 @@ import org.openremote.container.message.MessageBrokerService;import org.openremote.container.timer.TimerService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.web.ManagerWebResource;-import org.openremote.model.asset.AssetProcessingException;import org.openremote.model.asset.AssetResource;import org.openremote.model.security.Tenant;import org.openremote.model.Constants;@@ -244,8 +243,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResourfor (AssetAttribute updatedAttribute : asset.getAttributesList()) {// Proper validation happens on merge(), here we only need the name to continue- String updatedAttributeName =- updatedAttribute.getName().orElseThrow(() -> new IllegalStateException("Missing attribute name"));+ String updatedAttributeName = updatedAttribute.getNameOrThrow();// Check if attribute is present on the asset in storageOptional<AssetAttribute> serverAttribute = resultAsset.getAttribute(updatedAttributeName);diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetRoute.java b/manager/src/main/java/org/openremote/manager/asset/AssetRoute.javadeleted file mode 100644index 9ff25c989..000000000--- a/manager/src/main/java/org/openremote/manager/asset/AssetRoute.java+++ /dev/null@@ -1,302 +0,0 @@-/*- * Copyright 2016, 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.manager.asset;--import org.apache.camel.Exchange;-import org.apache.camel.Predicate;-import org.apache.camel.Processor;-import org.openremote.agent.protocol.Protocol;-import org.openremote.container.persistence.PersistenceEvent;-import org.openremote.container.security.AuthContext;-import org.openremote.container.timer.TimerService;-import org.openremote.manager.agent.AgentService;-import org.openremote.manager.security.ManagerIdentityService;-import org.openremote.model.asset.AssetProcessingException;-import org.openremote.model.asset.AssetProcessingException.Reason;-import org.openremote.model.Constants;-import org.openremote.model.ValidationFailure;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetState;-import org.openremote.model.asset.AssetType;-import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.attribute.AttributeEvent.Source;-import org.openremote.model.attribute.AttributeExecuteStatus;-import org.openremote.model.event.Event;-import org.openremote.model.security.ClientRole;-import org.openremote.model.value.Values;--import java.util.Date;-import java.util.List;-import java.util.Optional;-import java.util.logging.Level;-import java.util.logging.Logger;--import static org.openremote.model.asset.agent.AgentLink.getAgentLink;-import static org.openremote.model.attribute.AttributeEvent.HEADER_SOURCE;--public final class AssetRoute {-- public static final String HEADER_ASSET = AssetRoute.class.getName() + ".ASSET";- public static final String HEADER_ATTRIBUTE = AssetRoute.class.getName() + ".ATTRIBUTE";- public static final String HEADER_ASSET_STATE = AssetRoute.class.getName() + ".ASSET_STATE";-- public static Predicate isPersistenceEventForEntityType(Class<?> type) {- return exchange -> {- Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);- return type.isAssignableFrom(entityType);- };- }-- public static Predicate isPersistenceEventForAssetType(AssetType assetType) {- return exchange -> {- if (!(exchange.getIn().getBody() instanceof PersistenceEvent))- return false;- PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);- Asset asset = (Asset) persistenceEvent.getEntity();- return asset.getWellKnownType() == assetType;- };- }-- public static Processor extractAttributeEventDetails(AssetStorageService assetStorageService) {- return exchange -> {- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);- if (event.getEntityId() == null || event.getEntityId().isEmpty())- return;- if (event.getAttributeName() == null || event.getAttributeName().isEmpty())- return;-- ServerAsset asset;- if (exchange.getIn().getHeader(HEADER_ASSET) == null) {- asset = assetStorageService.find(event.getEntityId(), true);- if (asset == null)- return;- exchange.getIn().setHeader(HEADER_ASSET, asset);- } else {- asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);- }-- AssetAttribute attribute;- if (exchange.getIn().getHeader(HEADER_ATTRIBUTE) == null) {- attribute = asset.getAttribute(event.getAttributeName()).orElse(null);- if (attribute == null)- return;- exchange.getIn().setHeader(HEADER_ATTRIBUTE, attribute);- }- };- }-- public static Processor validateAttributeEvent() {- return exchange -> {-- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);-- Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);- if (source == null) {- throw new AssetProcessingException(Reason.MISSING_SOURCE);- }-- ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);- if (asset == null) {- throw new AssetProcessingException(Reason.ASSET_NOT_FOUND);- }-- AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);- if (attribute == null) {- throw new AssetProcessingException(Reason.ATTRIBUTE_NOT_FOUND);- }-- if (asset.getWellKnownType() == AssetType.AGENT) {- throw new AssetProcessingException(Reason.ILLEGAL_AGENT_UPDATE);- }-- // For executable attributes, non-sensor sources can set a writable attribute execute status- if (attribute.isExecutable() && source != Source.SENSOR) {- Optional<AttributeExecuteStatus> status = event.getValue()- .flatMap(Values::getString)- .flatMap(AttributeExecuteStatus::fromString);-- if (status.isPresent() && !status.get().isWrite()) {- throw new AssetProcessingException(Reason.INVALID_ATTRIBUTE_EXECUTE_STATUS);- }- }- };- }-- public static Processor validateAttributeEventFromClient(AssetStorageService assetStorageService,- ManagerIdentityService identityService) {- return exchange -> {-- AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);- if (authContext == null) {- throw new AssetProcessingException(Reason.NO_AUTH_CONTEXT);- }-- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);- ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);- AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);- Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);-- if (source != Source.CLIENT) {- throw new AssetProcessingException(Reason.ILLEGAL_SOURCE);- }-- // Check realm, must be accessible- if (!identityService.getIdentityProvider().isTenantActiveAndAccessible(authContext, asset)) {- throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);- }-- // Check read-only- if (attribute.isReadOnly() && !authContext.isSuperUser()) {- throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);- }-- // Regular user must have write assets role- if (!authContext.hasResourceRoleOrIsSuperUser(ClientRole.WRITE_ASSETS.getValue(), Constants.KEYCLOAK_CLIENT_ID)) {- throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);- }-- // Check restricted user- if (identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId())) {- // Must be asset linked to user- if (!assetStorageService.isUserAsset(authContext.getUserId(), event.getEntityId())) {- throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);- }- // Must be writable by restricted client- if (!attribute.isAccessRestrictedWrite()) {- throw new AssetProcessingException(Reason.INSUFFICIENT_ACCESS);- }- }- };- }-- public static Processor validateAttributeEventFromSensor(AgentService agentService) {- return exchange -> {-- AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);- Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, () -> null, Source.class);-- if (source != Source.SENSOR) {- throw new AssetProcessingException(Reason.ILLEGAL_SOURCE);- }-- Optional<AssetAttribute> protocolConfiguration =- getAgentLink(attribute).flatMap(agentService::getProtocolConfiguration);-- if (!protocolConfiguration.isPresent()) {- throw new AssetProcessingException(Reason.INVALID_AGENT_LINK);- }-- };- }-- public static Processor buildAssetState(TimerService timerService) {- return exchange -> {-- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);- AttributeEvent.Source source = exchange.getIn().getHeader(HEADER_SOURCE, AttributeEvent.Source.class);- ServerAsset asset = exchange.getIn().getHeader(HEADER_ASSET, ServerAsset.class);- AssetAttribute attribute = exchange.getIn().getHeader(HEADER_ATTRIBUTE, AssetAttribute.class);-- long eventTime = event.getTimestamp();- long processingTime = timerService.getCurrentTimeMillis();-- // Ensure timestamp of event is not in the future as that would essentially block access to- // the attribute until after that time (maybe that is desirable behaviour)- // Allow a leniency of 1s- if (eventTime - processingTime > 1000) {- // TODO: Decide how to handle update events in the future - ignore or change timestamp- throw new AssetProcessingException(- Reason.EVENT_IN_FUTURE,- "current time: " + new Date(processingTime) + "/" + processingTime- + ", event time: " + new Date(eventTime) + "/" + eventTime- );- }-- // Hold on to existing attribute state so we can use it during processing- Optional<AttributeEvent> lastStateEvent = attribute.getStateEvent();-- // Check the last update timestamp of the attribute, ignoring any event that is older than last update- // TODO This means we drop out-of-sequence events but accept events with the same source timestamp- // TODO Several attribute events can occur in the same millisecond, then order of application is undefined- lastStateEvent.map(Event::getTimestamp).filter(t -> t >= 0 && eventTime < t).ifPresent(- lastStateTime -> {- throw new AssetProcessingException(- Reason.EVENT_OUTDATED,- "last asset state time: " + new Date(lastStateTime) + "/" + lastStateTime- + ", event time: " + new Date(eventTime) + "/" + eventTime);- }- );-- // Set new value and event timestamp on attribute- attribute.setValue(event.getValue().orElse(null), eventTime);-- // Validate constraints of attribute- List<ValidationFailure> validationFailures = attribute.getValidationFailures();- if (!validationFailures.isEmpty()) {- throw new AssetProcessingException(- Reason.ATTRIBUTE_VALIDATION_FAILURE, validationFailures.toString()- );- }-- AssetState assetState = new AssetState(- asset,- attribute,- lastStateEvent.flatMap(AttributeEvent::getValue).orElse(null),- lastStateEvent.map(AttributeEvent::getTimestamp).orElse(-1L),- source- );-- exchange.getIn().setHeader(HEADER_ASSET_STATE, assetState);- };- }-- public static Processor handleAssetProcessingException(Logger logger) {- return exchange -> {- AttributeEvent event = exchange.getIn().getBody(AttributeEvent.class);- Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);-- StringBuilder error = new StringBuilder();-- Source source = exchange.getIn().getHeader(AttributeEvent.HEADER_SOURCE, "unknown source", Source.class);- if (source != null) {- error.append("Error processing from ").append(source);- }-- String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);- if (protocolName != null) {- error.append(" (protocol: ").append(protocolName).append(")");- }-- if (exception instanceof AssetProcessingException) {- AssetProcessingException processingException = (AssetProcessingException) exception;- error.append(" - ").append(processingException.getReasonPhrase());- error.append(": ").append(event.toString());- logger.warning(error.toString());- } else {- error.append(": ").append(event.toString());- logger.log(Level.WARNING, error.toString(), exception);- }-- // Make the exception available if MEP is InOut- exchange.getOut().setBody(exception);- };- }-}diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex 84ee88328..5b0fb42ee 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -57,7 +57,7 @@ import java.util.function.Consumer;import java.util.logging.Logger;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;-import static org.openremote.manager.asset.AssetRoute.isPersistenceEventForEntityType;+import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_TOPIC;import static org.openremote.manager.event.ClientEventService.getSessionKey;import static org.openremote.model.asset.BaseAssetQuery.*;@@ -67,7 +67,7 @@ import static org.openremote.model.asset.BaseAssetQuery.Include.ALL;import static org.openremote.model.asset.BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;import static org.openremote.model.util.TextUtil.isNullOrEmpty;-public class AssetStorageService extends RouteBuilder implements ContainerService, Consumer<AssetState> {+public class AssetStorageService extends RouteBuilder implements ContainerService {protected class PreparedAssetQuery {final protected String querySql;@@ -130,22 +130,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}- @Override- public void accept(AssetState assetState) {- String assetId = assetState.getId();- String attributeName = assetState.getAttribute().getName()- .orElseThrow(() -> new IllegalStateException("Cannot store asset state for attribute with no name"));- Value value = assetState.getAttribute().getValue().orElse(null);- // If there is no timestamp, use system time (0 or -1 are "no timestamp")- Optional<Long> timestamp = assetState.getAttribute().getValueTimestamp();- String valueTimestamp = Long.toString(- timestamp.filter(ts -> ts > 0).orElseGet(() -> timerService.getCurrentTimeMillis())- );- if (!storeAttributeValue(assetId, attributeName, value, valueTimestamp)) {- throw new RuntimeException("Database update failed, no rows updated");- }- }-@SuppressWarnings("unchecked")@Overridepublic void configure() throws Exception {@@ -209,6 +193,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicreturn find(new AssetQuery().select(new Select(loadComplete ? ALL : ALL_EXCEPT_PATH_AND_ATTRIBUTES)).id(assetId));}+ /**+ * @param loadComplete If the whole asset data (including path and attributes) should be loaded.+ */+ public ServerAsset find(EntityManager em, String assetId, boolean loadComplete) {+ return find(em, assetId, loadComplete, PRIVATE_READ);+ }+/*** @param loadComplete If the whole asset data (including path and attributes) should be loaded.* @param access The required access permissions of the asset data.@@ -223,6 +214,17 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicreturn persistenceService.doReturningTransaction(em -> find(em, query));}+ public ServerAsset find(EntityManager em, BaseAssetQuery query) {+ List<ServerAsset> result = findAll(em, query);+ if (result.size() == 0)+ return null;+ if (result.size() > 1) {+ throw new IllegalArgumentException("Query returned more than one asset");+ }+ return result.get(0);++ }+public List<ServerAsset> findAll(BaseAssetQuery query) {return persistenceService.doReturningTransaction(em -> findAll(em, query));}@@ -490,10 +492,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServicvoid acceptStatement(PreparedStatement st) throws SQLException;}- protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete) {- return find(em, assetId, loadComplete, PRIVATE_READ);- }-protected ServerAsset find(EntityManager em, String assetId, boolean loadComplete, Access access) {if (assetId == null)throw new IllegalArgumentException("Can't query null asset identifier");@@ -505,17 +503,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic);}- public ServerAsset find(EntityManager em, BaseAssetQuery query) {- List<ServerAsset> result = findAll(em, query);- if (result.size() == 0)- return null;- if (result.size() > 1) {- throw new IllegalArgumentException("Query returned more than one asset");- }- return result.get(0);-- }-protected List<ServerAsset> findAll(EntityManager em, BaseAssetQuery query) {// Use a default projection if it's missing@@ -682,7 +669,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic// Filter non-private access attributesAssetQuery.AttributeMetaPredicate accessPredicate =new AssetQuery.AttributeMetaPredicate()- .itemName(access == RESTRICTED_READ ? AssetMeta.ACCESS_RESTRICTED_READ: AssetMeta.ACCESS_PUBLIC_READ)+ .itemName(access == RESTRICTED_READ ? AssetMeta.ACCESS_RESTRICTED_READ : AssetMeta.ACCESS_PUBLIC_READ).itemValue(new AssetQuery.BooleanPredicate(true));sb.append(buildAttributeMetaFilter(accessPredicate, binders));}@@ -1070,57 +1057,54 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic}}- protected boolean storeAttributeValue(String assetId, String attributeName, Value value, String timestamp) {- return persistenceService.doReturningTransaction(entityManager ->- entityManager.unwrap(Session.class).doReturningWork(connection -> {-- String update =- "update ASSET" +- " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" +- " where ID = ? and ATTRIBUTES -> ? is not null";- try (PreparedStatement statement = connection.prepareStatement(update)) {-- // Bind the value (and check we don't have a SQL injection hole in attribute name!)- if (!AssetAttribute.ATTRIBUTE_NAME_VALIDATOR.test(attributeName)) {- LOG.fine(- "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName- );- return false;- }-- Array attributeValuePath = connection.createArrayOf(- "text",- new String[]{attributeName, "value"}+ public boolean storeAttributeValue(EntityManager em, String assetId, String attributeName, Value value, String timestamp) {+ return em.unwrap(Session.class).doReturningWork(connection -> {+ String update =+ "update ASSET" ++ " set ATTRIBUTES = jsonb_set(jsonb_set(ATTRIBUTES, ?, ?, true), ?, ?, true)" ++ " where ID = ? and ATTRIBUTES -> ? is not null";+ try (PreparedStatement statement = connection.prepareStatement(update)) {++ // Bind the value (and check we don't have a SQL injection hole in attribute name!)+ if (!AssetAttribute.ATTRIBUTE_NAME_VALIDATOR.test(attributeName)) {+ LOG.fine(+ "Invalid attribute name (must match '" + AssetAttribute.ATTRIBUTE_NAME_PATTERN + "'): " + attributeName);- statement.setArray(1, attributeValuePath);-- PGobject pgJsonValue = new PGobject();- pgJsonValue.setType("jsonb");- // Careful, do not set Java null (as returned by value.toJson()) here! It will erase your whole SQL column!- pgJsonValue.setValue(value == null ? "null" : value.toJson());- statement.setObject(2, pgJsonValue);-- // Bind the value timestamp- Array attributeValueTimestampPath = connection.createArrayOf(- "text",- new String[]{attributeName, "valueTimestamp"}- );- statement.setArray(3, attributeValueTimestampPath);- PGobject pgJsonValueTimestamp = new PGobject();- pgJsonValueTimestamp.setType("jsonb");- pgJsonValueTimestamp.setValue(timestamp);- statement.setObject(4, pgJsonValueTimestamp);-- // Bind asset ID and attribute name- statement.setString(5, assetId);- statement.setString(6, attributeName);-- int updatedRows = statement.executeUpdate();- LOG.fine("Stored asset '" + assetId + "' attribute '" + attributeName + "' value, affected rows: " + updatedRows);- return updatedRows == 1;+ return false;}- })- );++ Array attributeValuePath = connection.createArrayOf(+ "text",+ new String[]{attributeName, "value"}+ );+ statement.setArray(1, attributeValuePath);++ PGobject pgJsonValue = new PGobject();+ pgJsonValue.setType("jsonb");+ // Careful, do not set Java null (as returned by value.toJson()) here! It will erase your whole SQL column!+ pgJsonValue.setValue(value == null ? "null" : value.toJson());+ statement.setObject(2, pgJsonValue);++ // Bind the value timestamp+ Array attributeValueTimestampPath = connection.createArrayOf(+ "text",+ new String[]{attributeName, "valueTimestamp"}+ );+ statement.setArray(3, attributeValueTimestampPath);+ PGobject pgJsonValueTimestamp = new PGobject();+ pgJsonValueTimestamp.setType("jsonb");+ pgJsonValueTimestamp.setValue(timestamp);+ statement.setObject(4, pgJsonValueTimestamp);++ // Bind asset ID and attribute name+ statement.setString(5, assetId);+ statement.setString(6, attributeName);++ int updatedRows = statement.executeUpdate();+ LOG.fine("Stored asset '" + assetId + "' attribute '" + attributeName + "' value, affected rows: " + updatedRows);+ return updatedRows == 1;+ }+ });}protected void publishModificationEvents(PersistenceEvent<ServerAsset> persistenceEvent) {diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.javanew file mode 100644index 000000000..9983d6b8d--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/asset/AssetUpdateProcessor.java@@ -0,0 +1,63 @@+/*+ * Copyright 2016, 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.manager.asset;++import org.apache.camel.Predicate;+import org.openremote.container.persistence.PersistenceEvent;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetType;+import org.openremote.model.attribute.AttributeEvent.Source;++import javax.persistence.EntityManager;++public interface AssetUpdateProcessor {++ static Predicate isPersistenceEventForEntityType(Class<?> type) {+ return exchange -> {+ Class<?> entityType = exchange.getIn().getHeader(PersistenceEvent.HEADER_ENTITY_TYPE, Class.class);+ return type.isAssignableFrom(entityType);+ };+ }++ static Predicate isPersistenceEventForAssetType(AssetType assetType) {+ return exchange -> {+ if (!(exchange.getIn().getBody() instanceof PersistenceEvent))+ return false;+ PersistenceEvent persistenceEvent = exchange.getIn().getBody(PersistenceEvent.class);+ Asset asset = (Asset) persistenceEvent.getEntity();+ return asset.getWellKnownType() == assetType;+ };+ }++ /**+ * @param em The current session and transaction on the database, processors may use this to query additional data.+ * @param asset The current asset state with the old value and old value timestamp.+ * @param attribute The attribute to be updated, with new value and value timestamp already set. Value and timestamp can be mutated by processors.+ * @param source The source of the update.+ * @return <code>true</code> if processing is complete and subsequent processor should be skipped.+ * @throws AssetProcessingException When processing failed and the update can not continue.+ */+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, Source source) throws AssetProcessingException;++ /* TODO Processors should be transactional, so an exception in one processor can roll back the update in others */+ // void commit();+ // void rollback();+}diff --git a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.javaindex c35431ca3..e990e0574 100644--- a/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java+++ b/manager/src/main/java/org/openremote/manager/datapoint/AssetDatapointService.java@@ -7,10 +7,13 @@ import org.openremote.container.ContainerService;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;import org.openremote.container.web.WebService;+import org.openremote.manager.asset.AssetProcessingException;import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.asset.AssetUpdateProcessor;import org.openremote.manager.security.ManagerIdentityService;+import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetState;+import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.datapoint.AssetDatapoint;import org.openremote.model.datapoint.Datapoint;@@ -18,18 +21,18 @@ import org.openremote.model.datapoint.DatapointInterval;import org.openremote.model.datapoint.NumberDatapoint;import org.postgresql.util.PGInterval;+import javax.persistence.EntityManager;import java.sql.*;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.List;-import java.util.function.Consumer;import java.util.function.Function;import java.util.logging.Logger;/*** Store and retrieve datapoints for asset attributes.*/-public class AssetDatapointService implements ContainerService, Consumer<AssetState> {+public class AssetDatapointService implements ContainerService, AssetUpdateProcessor {private static final Logger LOG = Logger.getLogger(AssetDatapointService.class.getName());@@ -59,14 +62,18 @@ public class AssetDatapointService implements ContainerService, Consumer<AssetSt}@Override- public void accept(AssetState assetState) {- if (Datapoint.isDatapointsCapable(assetState.getAttribute())- && assetState.getAttribute().isStoreDatapoints()- && assetState.getAttribute().getStateEvent().isPresent()) {- LOG.finest("Storing datapoint for: " + assetState);- AssetDatapoint assetDatapoint = new AssetDatapoint(assetState.getAttribute().getStateEvent().get());- persistenceService.doTransaction(entityManager -> entityManager.persist(assetDatapoint));+ public boolean processAssetUpdate(EntityManager em,+ Asset asset,+ AssetAttribute attribute,+ Source source) throws AssetProcessingException {+ if (Datapoint.isDatapointsCapable(attribute)+ && attribute.isStoreDatapoints()+ && attribute.getStateEvent().isPresent()) {+ LOG.finest("Storing datapoint for: " + attribute);+ AssetDatapoint assetDatapoint = new AssetDatapoint(attribute.getStateEvent().get());+ em.persist(assetDatapoint);}+ return false;}public List<AssetDatapoint> getDatapoints(AttributeRef attributeRef) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 80c2be42c..9f6ce3707 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -24,11 +24,7 @@ import org.jeasy.rules.core.RulesEngineParameters;import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.concurrent.ManagerExecutorService;-import org.openremote.model.asset.AssetEvent;-import org.openremote.model.asset.AssetState;-import org.openremote.model.rules.Assets;-import org.openremote.model.rules.Ruleset;-import org.openremote.model.rules.Users;+import org.openremote.model.rules.*;import java.util.*;import java.util.concurrent.ScheduledFuture;@@ -140,7 +136,7 @@ public class RulesEngine<T extends Ruleset> {}}- public Throwable getError() {+ public RuntimeException getError() {synchronized (deployments) {List<RulesetDeployment> deploymentsWithCompilationError = new ArrayList<>();List<RulesetDeployment> deploymentsWithExecutionError = new ArrayList<>();@@ -156,7 +152,7 @@ public class RulesEngine<T extends Ruleset> {"Ruleset deployments have errors, failed compilation: "+ deploymentsWithCompilationError.size()+ ", failed execution: "- + deploymentsWithExecutionError.size()+ + deploymentsWithExecutionError.size() + " - on: " + this);}return null;@@ -302,6 +298,12 @@ public class RulesEngine<T extends Ruleset> {// If we still have temporary facts and there is no firing scheduledif (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {// Schedule firing again so temporary facts can be expired+ // TODO: Optimized algo:+ // 1. Check when the next temporary fact expires+ // 2. Schedule repeated check with GUARANTEED_MIN_EXPIRATION_MILLIS running on wall clock+ // 3. Check if rules clock == next temporary fact expires+ // 3a. If true, cancel schedule and fire+ // 3b. If false, keep checkingeventsTimer = executorService.schedule(this::fire, AssetEvent.GUARANTEED_MIN_EXPIRATION_MILLIS, TimeUnit.MILLISECONDS);diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex c75e2723d..2a5c95e55 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -20,10 +20,10 @@package org.openremote.manager.rules;import org.jeasy.rules.api.*;-import org.openremote.model.asset.AssetEvent;+import org.openremote.model.rules.AssetEvent;import org.openremote.model.asset.AssetQuery;-import org.openremote.model.asset.AssetQueryPredicate;-import org.openremote.model.asset.AssetState;+import org.openremote.model.rules.AssetQueryPredicate;+import org.openremote.model.rules.AssetState;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.rules.Assets;diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex d8c487584..4527f89ed 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -26,28 +26,26 @@ import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.timer.TimerService;-import org.openremote.manager.asset.AssetProcessingService;-import org.openremote.manager.asset.AssetStorageService;-import org.openremote.manager.asset.ServerAsset;+import org.openremote.manager.asset.*;import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.notification.NotificationService;import org.openremote.manager.rules.facade.AssetsFacade;import org.openremote.manager.rules.facade.UsersFacade;import org.openremote.manager.security.ManagerIdentityService;-import org.openremote.model.asset.*;-import org.openremote.model.attribute.AttributeEvent;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.AssetQuery;+import org.openremote.model.attribute.AttributeEvent.Source;import org.openremote.model.attribute.AttributeType;-import org.openremote.model.rules.AssetRuleset;-import org.openremote.model.rules.GlobalRuleset;-import org.openremote.model.rules.Ruleset;-import org.openremote.model.rules.TenantRuleset;+import org.openremote.model.rules.*;import org.openremote.model.security.Tenant;import org.openremote.model.util.Pair;import org.openremote.model.value.ObjectValue;+import javax.persistence.EntityManager;import java.util.*;import java.util.function.BiFunction;-import java.util.function.Consumer;import java.util.logging.Logger;import java.util.stream.Collectors;import java.util.stream.Stream;@@ -55,7 +53,7 @@ import java.util.stream.Stream;import static java.util.logging.Level.FINEST;import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;import static org.openremote.container.util.MapAccess.getString;-import static org.openremote.manager.asset.AssetRoute.isPersistenceEventForEntityType;+import static org.openremote.manager.asset.AssetUpdateProcessor.isPersistenceEventForEntityType;import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;@@ -73,7 +71,7 @@ import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttrib* with the same scope is not guaranteed)</li>* </ol>*/-public class RulesService extends RouteBuilder implements ContainerService, Consumer<AssetState> {+public class RulesService extends RouteBuilder implements ContainerService, AssetUpdateProcessor {private static final Logger LOG = Logger.getLogger(RulesService.class.getName());@@ -176,9 +174,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.forEach(pair -> {ServerAsset asset = pair.key;pair.value.forEach(ruleAttribute -> {- AssetState assetState = new AssetState(asset, ruleAttribute, AttributeEvent.Source.INTERNAL);- // Set the status to completed already so rules cannot interfere with this initial insert- assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);+ AssetState assetState = new AssetState(asset, ruleAttribute, Source.INTERNAL);updateAssetState(assetState, true, true);});});@@ -203,26 +199,31 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons}@Override- public void accept(AssetState assetState) {+ public boolean processAssetUpdate(EntityManager em,+ Asset asset,+ AssetAttribute attribute,+ Source source) throws AssetProcessingException {// We might process two facts for a single attribute update, if that is what the user wants// First as asset state- if (assetState.getAttribute().isRuleState()) {+ AssetState assetState = new AssetState(asset, attribute, source);+ if (attribute.isRuleState()) {updateAssetState(assetState,false, // Don't skip the error check on the rules engines- !assetState.getAttribute().isRuleEvent() // If it's not a rule event, fire immediately+ !attribute.isRuleEvent() // If it's not a rule event, fire immediately);}// Then as asset event (if there wasn't an error), this will also fire the rules engines- if (assetState.getProcessingStatus() == AssetState.ProcessingStatus.CONTINUE- && assetState.getAttribute().isRuleEvent()) {+ if (attribute.isRuleEvent()) {process(new AssetEvent(assetState,- assetState.getAttribute().getRuleEventExpires().orElse(configEventExpires)+ attribute.getRuleEventExpires().orElse(configEventExpires)));}++ return false;}protected synchronized void processTenantChange(Tenant tenant, PersistenceEvent.Cause cause) {@@ -266,7 +267,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// We must load the asset from database (only when required), as the// persistence event might not contain a completely loaded assetBiFunction<Asset, AssetAttribute, AssetState> buildAssetState = (loadedAsset, attribute) ->- new AssetState(loadedAsset, attribute.deepCopy(), AttributeEvent.Source.INTERNAL);+ new AssetState(loadedAsset, attribute.deepCopy(), Source.INTERNAL);switch (persistenceEvent.getCause()) {case INSERT:@@ -283,8 +284,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Consreturn;AssetState assetState = buildAssetState.apply(loadedAsset, attribute);- // Set the status to completed already so rules cannot interfere with this initial insert- assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + assetState);updateAssetState(assetState, true, true);});@@ -329,8 +328,6 @@ public class RulesService extends RouteBuilder implements ContainerService, ConsgetAddedOrModifiedAttributes(oldRuleStateAttributes, newRuleStateAttributes, key -> key.equals(VALUE_TIMESTAMP_FIELD_NAME)).forEach(newFactAttribute -> {AssetState assetState = buildAssetState.apply(loadedAsset, newFactAttribute);- // Set the status to completed already so rules cannot interfere with this initial insert- assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);updateAssetState(assetState, true, true);});@@ -344,7 +341,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// We can't load the asset again (it was deleted), so don't use buildAssetState() and// hope that the path of the event asset has been loaded before deletion, although it is// "unlikely" anybody will access it during retraction...- AssetState assetState = new AssetState(asset, attribute, AttributeEvent.Source.INTERNAL);+ AssetState assetState = new AssetState(asset, attribute, Source.INTERNAL);LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), retracting fact: " + assetState);retractAssetState(assetState);});@@ -595,12 +592,10 @@ public class RulesService extends RouteBuilder implements ContainerService, Consif (!skipStatusCheck) {// Check that all engines in the scope are available- // TODO This is not very useful without locking the engines until we are done with the udpate+ // TODO This is not very useful without locking the engines until we are done with the updatefor (RulesEngine rulesEngine : rulesEngines) {if (rulesEngine.isError()) {- assetState.setProcessingStatus(AssetState.ProcessingStatus.ERROR);- assetState.setError(rulesEngine.getError());- return;+ throw rulesEngine.getError();}}}diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.javaindex e17747f9a..46186ea85 100644--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java@@ -24,11 +24,11 @@ import org.openremote.agent.protocol.simulator.SimulatorProtocol;import org.openremote.container.Container;import org.openremote.manager.asset.ServerAsset;import org.openremote.manager.setup.AbstractManagerSetup;-import org.openremote.model.security.Tenant;+import org.openremote.model.asset.Asset;import org.openremote.model.asset.AssetAttribute;-import org.openremote.model.asset.AssetState;import org.openremote.model.asset.UserAsset;import org.openremote.model.attribute.*;+import org.openremote.model.security.Tenant;import org.openremote.model.simulator.element.ColorSimulatorElement;import org.openremote.model.simulator.element.NumberSimulatorElement;import org.openremote.model.simulator.element.SwitchSimulatorElement;@@ -247,60 +247,62 @@ public class ManagerDemoSetup extends AbstractManagerSetup {thingId = thing.getId();// Some sample datapoints- thing = assetStorageService.find(thingId, true);+ final Asset finalThing = assetStorageService.find(thingId, true);ZonedDateTime now = LocalDateTime.now().atZone(ZoneId.systemDefault());AssetAttribute light1PowerConsumptionAttribute = thing.getAttribute("light1PowerConsumption").orElseThrow(() -> new RuntimeException("Invalid test data"));- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ persistenceService.doTransaction(em -> {+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(0.11), now.minusDays(80).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(1.22), now.minusDays(40).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(2.33), now.minusDays(20).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(3.44), now.minusDays(10).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);+ light1PowerConsumptionAttribute.setValue(Values.create(4.55), now.minusDays(8).toEpochSecond() * 1000);- light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(5.66), now.minusDays(6).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(6.77), now.minusDays(3).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(7.88), now.minusDays(1).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(8.99), now.minusHours(10).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(9.11), now.minusHours(5).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(10.22), now.minusHours(2).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(11.33), now.minusHours(1).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(11.44), now.minusMinutes(30).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(12.00), now.minusMinutes(5).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(12.11), now.minusSeconds(5).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);- light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);- assetDatapointService.accept(new AssetState(thing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR));+ light1PowerConsumptionAttribute.setValue(Values.create(12.22), now.minusSeconds(1).toEpochSecond() * 1000);+ assetDatapointService.processAssetUpdate(em, finalThing, light1PowerConsumptionAttribute, AttributeEvent.Source.SENSOR);+ });// ################################ Demo assets for 'customerA' realm ###################################diff --git a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovyindex fa43fab40..556e66a5c 100644--- a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy+++ b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy@@ -11,7 +11,7 @@ package demo.rulesimport org.openremote.manager.rules.RulesBuilderimport org.openremote.model.asset.AssetQuery-import org.openremote.model.asset.AssetState+import org.openremote.model.rules.AssetStateimport org.openremote.model.util.Pairimport java.util.logging.Loggerdiff --git a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovyindex c9222ab05..94b1eb2d5 100644--- a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy+++ b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy@@ -3,7 +3,7 @@ package demo.rulesimport groovy.transform.ToStringimport org.openremote.manager.rules.RulesBuilderimport org.openremote.model.asset.AssetQuery-import org.openremote.model.asset.AssetState+import org.openremote.model.rules.AssetStateimport org.openremote.model.rules.Assetsimport java.util.logging.Loggerdiff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex fb86c98c8..e69b76bf1 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -474,6 +474,10 @@ public class Asset implements IdentifiableEntity {this.parentType = parentType;}+ public AssetType getParentWellKnownType() {+ return AssetType.getByValue(getParentType()).orElse(AssetType.CUSTOM);+ }+public String getRealmId() {return realmId;}diff --git a/model/src/main/java/org/openremote/model/asset/AssetEvent.java b/model/src/main/java/org/openremote/model/asset/AssetEvent.javadeleted file mode 100644index ec1011366..000000000--- a/model/src/main/java/org/openremote/model/asset/AssetEvent.java+++ /dev/null@@ -1,66 +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.asset;--import org.openremote.model.rules.TemporaryFact;-import org.openremote.model.util.TimeUtil;--import java.util.Optional;--/**- * An asset attribute value change as a punctual event in rules processing.- */-public class AssetEvent extends AbstractAssetUpdate implements TemporaryFact {-- final protected long expirationMilliseconds;-- public AssetEvent(AbstractAssetUpdate that, String expires) {- super(that);- this.expirationMilliseconds = TimeUtil.parseTimeString(expires);- }-- @Override- public long getExpirationMilliseconds() {- return expirationMilliseconds;- }-- @Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;-- AssetEvent that = (AssetEvent) o;-- return getAttributeRef().equals(that.getAttributeRef()) &&- getAttribute().getValue().equals(that.getAttribute().getValue()) &&- getTimestamp() == that.getTimestamp() &&- Optional.ofNullable(getOldValue()).equals(Optional.ofNullable(that.getOldValue())) &&- getOldValueTimestamp() == that.getOldValueTimestamp();- }-- @Override- public int hashCode() {- return getAttributeRef().hashCode()- + getAttribute().getValue().hashCode()- + Long.hashCode(getTimestamp())- + Optional.ofNullable(getOldValue()).hashCode()- + Long.hashCode(getOldValueTimestamp());- }-}diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 54d2103dd..3dd572aaa 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -21,6 +21,8 @@ package org.openremote.model.asset;import org.openremote.model.ValidationFailure;import org.openremote.model.attribute.*;+import org.openremote.model.rules.AssetEvent;+import org.openremote.model.rules.AssetState;import org.openremote.model.rules.TemporaryFact;import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;diff --git a/model/src/main/java/org/openremote/model/asset/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.javadeleted file mode 100644index 0b754dccc..000000000--- a/model/src/main/java/org/openremote/model/asset/AssetState.java+++ /dev/null@@ -1,122 +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.asset;--import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.value.Value;--/**- * An asset attribute value update, capturing that asset state at a point in time.- * <p>- * The methods {@link #setValue}, {@link #setProcessingStatus}, and {@link #setError} can not be- * called anymore when the {@link #getProcessingStatus} is {@link ProcessingStatus#COMPLETED}.- */-public class AssetState extends AbstractAssetUpdate {-- /**- * Processors of asset state updates can change the status to direct further processing.- */- public enum ProcessingStatus {- /**- * Processor is happy for update to continue through the system.- */- CONTINUE,-- /**- * Processor encountered an error trying to process the update, cancel further processing and escalate.- */- ERROR,-- /**- * Indicates that this update has been handled; the object can no longer be mutated at this stage.- */- COMPLETED- }-- protected ProcessingStatus processingStatus = ProcessingStatus.CONTINUE;-- protected Throwable error;-- public AssetState(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {- super(asset, attribute, source);- }-- public AssetState(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, AttributeEvent.Source source) {- super(asset, attribute, oldValue, oldValueTimestamp, source);- }-- public ProcessingStatus getProcessingStatus() {- return processingStatus;- }-- public Throwable getError() {- return error;- }-- /**- * @return <code>true</code> is this state has completed processing, it's not currently being processed.- */- public boolean isCompleted() {- return getProcessingStatus() == ProcessingStatus.COMPLETED;- }-- /////////////////////////////////////////////////////////////////- // GETTERS AND SETTERS BELOW CAN ONLY BE USED WHEN STATUS IS NOT COMPLETED- /////////////////////////////////////////////////////////////////-- public void setValue(Value value) {- if (!isCompleted()) {- attribute.setValue(value);- } else {- throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);- }- }-- public void setProcessingStatus(ProcessingStatus processingStatus) {- if (!isCompleted()) {- this.processingStatus = processingStatus;- } else {- throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);- }- }-- public void setError(Throwable error) {- if (!isCompleted()) {- this.error = error;- } else {- throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);- }- }-- @Override- public boolean equals(Object o) {- if (this == o) return true;- if (o == null || getClass() != o.getClass()) return false;-- AssetState that = (AssetState) o;-- return getAttributeRef().equals(that.getAttributeRef());- }-- @Override- public int hashCode() {- return getAttributeRef().hashCode();- }-}diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.javaindex a416e02bd..b2cbb63d1 100644--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java@@ -94,6 +94,10 @@ public abstract class Attribute extends AbstractValueTimestampHolder {return Optional.ofNullable(name);}+ public String getNameOrThrow() {+ return getName().orElseThrow(() -> new IllegalStateException("Attribute doesn't have a name"));+ }+public void setName(String name) {requireNonNullAndNonEmpty(name);this.name = name;diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.javaindex b8a6b9320..b4c9c170a 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java@@ -158,7 +158,7 @@ public class AttributeEvent extends SharedEvent {}public Optional<Value> getValue() {- return getAttributeState().getCurrentValue();+ return getAttributeState().getValue();}@Overridediff --git a/model/src/main/java/org/openremote/model/attribute/AttributeState.java b/model/src/main/java/org/openremote/model/attribute/AttributeState.javaindex 3043841aa..835db403e 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeState.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeState.java@@ -71,15 +71,14 @@ public class AttributeState {return attributeRef;}- // TODO GWT Jackson does not like fields that have a getter with a different type than the field, so rename getter- public Optional<Value> getCurrentValue() {+ public Optional<Value> getValue() {return Optional.ofNullable(value);}public ObjectValue toObjectValue() {ObjectValue objectValue = Values.createObject();objectValue.put("attributeRef", getAttributeRef().toArrayValue());- getCurrentValue().ifPresent(v -> objectValue.put("value", value));+ getValue().ifPresent(v -> objectValue.put("value", value));return objectValue;}diff --git a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java b/model/src/main/java/org/openremote/model/datapoint/Datapoint.javaindex 4266f24d7..04099138d 100644--- a/model/src/main/java/org/openremote/model/datapoint/Datapoint.java+++ b/model/src/main/java/org/openremote/model/datapoint/Datapoint.java@@ -78,7 +78,7 @@ public abstract class Datapoint implements Serializable {}public Datapoint(AttributeState attributeState, long timestamp) {- this(attributeState.getAttributeRef(), attributeState.getCurrentValue().orElse(null), timestamp);+ this(attributeState.getAttributeRef(), attributeState.getValue().orElse(null), timestamp);}public Datapoint(AttributeEvent stateEvent) {diff --git a/model/src/main/java/org/openremote/model/rules/AssetEvent.java b/model/src/main/java/org/openremote/model/rules/AssetEvent.javanew file mode 100644index 000000000..a3f2ac314--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/AssetEvent.java@@ -0,0 +1,41 @@+/*+ * 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.rules;++import org.openremote.model.util.TimeUtil;++/**+ * An asset attribute value update, as a temporary event in rules processing.+ */+public class AssetEvent extends AssetState implements TemporaryFact {++ final protected long expirationMilliseconds;++ public AssetEvent(AssetState that, String expires) {+ super(that);+ this.expirationMilliseconds = TimeUtil.parseTimeString(expires);+ }++ @Override+ public long getExpirationMilliseconds() {+ return expirationMilliseconds;+ }++}diff --git a/model/src/main/java/org/openremote/model/asset/AssetQueryPredicate.java b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.javasimilarity index 76%rename from model/src/main/java/org/openremote/model/asset/AssetQueryPredicate.javarename to model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.javaindex 6427200f9..2ac43a119 100644--- a/model/src/main/java/org/openremote/model/asset/AssetQueryPredicate.java+++ b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java@@ -17,8 +17,9 @@* 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;+package org.openremote.model.rules;+import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.asset.BaseAssetQuery.*;import java.util.Arrays;@@ -29,9 +30,9 @@ import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_EQUALS;import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_THAN;/**- * Test an {@link AbstractAssetUpdate} with a {@link BaseAssetQuery}.+ * Test an {@link AssetState} with a {@link BaseAssetQuery}.*/-public class AssetQueryPredicate implements Predicate<AbstractAssetUpdate> {+public class AssetQueryPredicate implements Predicate<AssetState> {final protected BaseAssetQuery query;@@ -40,33 +41,33 @@ public class AssetQueryPredicate implements Predicate<AbstractAssetUpdate> {}@Override- public boolean test(AbstractAssetUpdate assetUpdate) {+ public boolean test(AssetState assetState) {- if (query.id != null && !query.id.equals(assetUpdate.getId()))+ if (query.id != null && !query.id.equals(assetState.getId()))return false;- if (query.name != null && !asPredicate(query.name).test(assetUpdate.getName()))+ if (query.name != null && !asPredicate(query.name).test(assetState.getName()))return false;- if (query.parent != null && !asPredicate(query.parent).test(assetUpdate))+ if (query.parent != null && !asPredicate(query.parent).test(assetState))return false;- if (query.path != null && !asPredicate(query.path).test(assetUpdate.getPath()))+ if (query.path != null && !asPredicate(query.path).test(assetState.getPath()))return false;- if (query.tenant != null && !asPredicate(query.tenant).test(assetUpdate))+ if (query.tenant != null && !asPredicate(query.tenant).test(assetState))return false;if (query.userId != null) {// TODO Would require linked user IDs in AbstractAssetUpdatethrow new UnsupportedOperationException("Restriction by user ID not implemented in rules matching");}- if (query.type != null && !asPredicate(query.type).test(assetUpdate.getTypeString()))+ if (query.type != null && !asPredicate(query.type).test(assetState.getTypeString()))return false;if (query.attribute != null) {for (BaseAssetQuery.AttributePredicate p : query.attribute) {- if (!asPredicate(p).test(assetUpdate))+ if (!asPredicate(p).test(assetState))return false;}}@@ -169,48 +170,48 @@ public class AssetQueryPredicate implements Predicate<AbstractAssetUpdate> {};}- protected Predicate<AbstractAssetUpdate> asPredicate(ParentPredicate predicate) {- return assetUpdate ->- (predicate.id == null || predicate.id.equals(assetUpdate.getParentId()))- && (predicate.type == null || predicate.type.equals(assetUpdate.getParentTypeString()))- && (!predicate.noParent || assetUpdate.getParentId() == null);+ protected Predicate<AssetState> asPredicate(ParentPredicate predicate) {+ return assetState ->+ (predicate.id == null || predicate.id.equals(assetState.getParentId()))+ && (predicate.type == null || predicate.type.equals(assetState.getParentTypeString()))+ && (!predicate.noParent || assetState.getParentId() == null);}protected Predicate<String[]> asPredicate(PathPredicate predicate) {return givenPath -> Arrays.equals(predicate.path, givenPath);}- protected Predicate<AbstractAssetUpdate> asPredicate(TenantPredicate predicate) {- return assetUpdate ->- (predicate.realm == null || predicate.realm.equals(assetUpdate.getTenantRealm()))- && (predicate.realmId == null || predicate.realmId.equals(assetUpdate.getRealmId()));+ protected Predicate<AssetState> asPredicate(TenantPredicate predicate) {+ return assetState ->+ (predicate.realm == null || predicate.realm.equals(assetState.getTenantRealm()))+ && (predicate.realmId == null || predicate.realmId.equals(assetState.getRealmId()));}- protected Predicate<AbstractAssetUpdate> asPredicate(AttributePredicate predicate) {- return assetUpdate -> {- if (predicate.name != null && !asPredicate(predicate.name).test(assetUpdate.getAttributeName()))+ protected Predicate<AssetState> asPredicate(AttributePredicate predicate) {+ return assetState -> {+ if (predicate.name != null && !asPredicate(predicate.name).test(assetState.getAttributeName()))return false;if (predicate.value == null)return true;- if (predicate.value instanceof AssetQuery.ValueNotEmptyPredicate) {- return assetUpdate.getValue().isPresent();+ if (predicate.value instanceof BaseAssetQuery.ValueNotEmptyPredicate) {+ return assetState.getValue().isPresent();- } else if (predicate.value instanceof AssetQuery.StringPredicate) {+ } else if (predicate.value instanceof BaseAssetQuery.StringPredicate) {- AssetQuery.StringPredicate p = (AssetQuery.StringPredicate) predicate.value;- return asPredicate(p).test(assetUpdate.getValueAsString().orElse(null));+ StringPredicate p = (StringPredicate) predicate.value;+ return asPredicate(p).test(assetState.getValueAsString().orElse(null));- } else if (predicate.value instanceof AssetQuery.BooleanPredicate) {+ } else if (predicate.value instanceof BaseAssetQuery.BooleanPredicate) {- AssetQuery.BooleanPredicate p = (AssetQuery.BooleanPredicate) predicate.value;- return asPredicate(p).test(assetUpdate.getValueAsBoolean().orElse(null));+ BooleanPredicate p = (BooleanPredicate) predicate.value;+ return asPredicate(p).test(assetState.getValueAsBoolean().orElse(null));- } else if (predicate.value instanceof AssetQuery.NumberPredicate) {+ } else if (predicate.value instanceof BaseAssetQuery.NumberPredicate) {- AssetQuery.NumberPredicate p = (AssetQuery.NumberPredicate) predicate.value;- return asPredicate(p).test(assetUpdate.getValueAsNumber().orElse(null));+ NumberPredicate p = (NumberPredicate) predicate.value;+ return asPredicate(p).test(assetState.getValueAsNumber().orElse(null));} else {// TODO Implement more@@ -221,5 +222,4 @@ public class AssetQueryPredicate implements Predicate<AbstractAssetUpdate> {};}-}diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/rules/AssetState.javasimilarity index 53%rename from model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.javarename to model/src/main/java/org/openremote/model/rules/AssetState.javaindex 52b6181ea..1d633d8ea 100644--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java+++ b/model/src/main/java/org/openremote/model/rules/AssetState.java@@ -17,12 +17,15 @@* 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;-+package org.openremote.model.rules;import javaemul.internal.annotations.GwtIncompatible;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.AbstractValueTimestampHolder;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetType;import org.openremote.model.attribute.AttributeEvent;-import org.openremote.model.attribute.AttributeRef;import org.openremote.model.attribute.AttributeType;import org.openremote.model.value.ArrayValue;import org.openremote.model.value.ObjectValue;@@ -33,24 +36,36 @@ import java.time.Instant;import java.time.LocalDateTime;import java.time.ZoneId;import java.util.Date;+import java.util.Objects;import java.util.Optional;-import static org.openremote.model.asset.AssetType.CUSTOM;-/**- * An asset attribute value update, capturing that asset state at a point in time.+ * An asset attribute value update, capturing asset state at a point in time.* <p>- * This class layout is convenient for writing expressions that match getters, while- * carrying as much asset details as needed (e.g. for writing rules).+ * This class layout is convenient for writing rules. Two asset states+ * are equal if they have the same asset ID and attribute name (the same attribute+ * reference).*/@GwtIncompatible-public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdate> {+public class AssetState implements Comparable<AssetState> {++ final protected String attributeName;++ final protected AttributeType attributeType;++ final protected Value value;- final public AssetAttribute attribute;+ final protected long timestamp;- final public Date createdOn;+ final protected LocalDateTime time;++ final protected AttributeEvent.Source source;++ final protected Value oldValue;++ final protected long oldValueTimestamp;- final public String id;+ final protected String id;final protected String name;@@ -58,121 +73,112 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdfinal protected AssetType type;- /**- * The identifiers of all parents representing the path in the tree. The first element- * is the root asset without a parent, the last is the identifier of this instance.- */- final public String[] path;+ final protected Date createdOn;- final public String parentId;+ final protected String[] path;- final public String parentName;+ final protected String parentId;- final public String parentTypeString;+ final protected String parentName;- final public AssetType parentType;+ final protected String parentTypeString;- final public String realmId;+ final protected AssetType parentType;- final public String tenantRealm;+ final protected String realmId;- final public double[] coordinates;+ final protected String tenantRealm;- final public Value oldValue;+ final protected double[] coordinates;- final protected long oldValueTimestamp;+ public AssetState(AssetState that) {+ this.attributeName = that.attributeName;+ this.attributeType = that.attributeType;+ this.value = that.value;+ this.timestamp = that.timestamp;+ this.time = that.time;+ this.source = that.source;+ this.oldValue = that.oldValue;+ this.oldValueTimestamp = that.oldValueTimestamp;+ this.id = that.id;+ this.name = that.name;+ this.typeString = that.typeString;+ this.type = that.type;+ this.createdOn = that.createdOn;+ this.path = that.path;+ this.parentId = that.parentId;+ this.parentName = that.parentName;+ this.parentTypeString = that.parentTypeString;+ this.parentType = that.parentType;+ this.realmId = that.realmId;+ this.tenantRealm = that.tenantRealm;+ this.coordinates = that.coordinates;+ }- final public AttributeEvent.Source source;+ public AssetState(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {+ this.attributeName = attribute.getNameOrThrow();+ this.attributeType = attribute.getTypeOrThrow();+ this.value = attribute.getValue().orElse(null);+ this.timestamp = attribute.getValueTimestamp().orElse(-1L);+ this.time = timestamp > 0 ? LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault()) : null;+ this.source = source;+ this.oldValue = asset.getAttribute(attributeName).flatMap(AbstractValueHolder::getValue).orElse(null);+ this.oldValueTimestamp = asset.getAttribute(attributeName).flatMap(AbstractValueTimestampHolder::getValueTimestamp).orElse(-1L);+ this.id = asset.getId();+ this.name = asset.getName();+ this.typeString = asset.getType();+ this.type = asset.getWellKnownType();+ this.createdOn = asset.getCreatedOn();+ this.path = asset.getPath();+ this.parentId = asset.getParentId();+ this.parentName = asset.getParentName();+ this.parentTypeString = asset.getParentType();+ this.parentType = asset.getParentWellKnownType();+ this.realmId = asset.getRealmId();+ this.tenantRealm = asset.getTenantRealm();+ this.coordinates = asset.getCoordinates();+ }- final protected LocalDateTime time;+ public String getAttributeName() {+ return attributeName;+ }- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {- this(asset, attribute, null, 0, source);- }-- public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, Value oldValue, long oldValueTimestamp, AttributeEvent.Source source) {- this(- attribute,- asset.getCreatedOn(),- asset.getId(),- asset.getName(),- asset.getType(),- asset.getWellKnownType(),- asset.getPath(),- asset.getParentId(),- asset.getParentName(),- asset.getParentType(),- AssetType.getByValue(asset.getParentType()).orElse(CUSTOM),- asset.getRealmId(),- asset.getTenantRealm(),- asset.getCoordinates(),- oldValue,- oldValueTimestamp,- source- );- }-- public AbstractAssetUpdate(AbstractAssetUpdate that) {- this(- that.attribute,- that.createdOn,- that.id,- that.name,- that.typeString,- that.type,- that.path,- that.parentId,- that.parentName,- that.parentTypeString,- that.parentType,- that.realmId,- that.tenantRealm,- that.coordinates,- that.oldValue,- that.oldValueTimestamp,- that.source- );- }-- protected AbstractAssetUpdate(AssetAttribute attribute,- Date createdOn, String id, String name, String typeString, AssetType type,- String[] path, String parentId, String parentName, String parentTypeString, AssetType parentType,- String realmId, String tenantRealm,- double[] coordinates,- Value oldValue,- long oldValueTimestamp,- AttributeEvent.Source source) {- this.attribute = attribute;- this.createdOn = createdOn;- this.id = id;- this.name = name;- this.typeString = typeString;- this.type = type;- if (path == null) {- throw new IllegalArgumentException("Empty path (asset not completely loaded?): " + id);- }- this.path = path;- this.parentId = parentId;- this.parentName = parentName;- this.parentTypeString = parentTypeString;- this.parentType = parentType;- this.realmId = realmId;- this.tenantRealm = tenantRealm;- this.coordinates = coordinates;- this.oldValue = oldValue;- this.oldValueTimestamp = oldValueTimestamp;- this.source = source;- this.time = attribute.getValueTimestamp().map(ts -> LocalDateTime.ofInstant(Instant.ofEpochMilli(ts), ZoneId.systemDefault())).orElse(null);+ public AttributeType getAttributeType() {+ return attributeType;}- public Date getCreatedOn() {- return createdOn;+ public Optional<Value> getValue() {+ return Optional.ofNullable(value);+ }++ public long getTimestamp() {+ return timestamp;+ }++ public LocalDateTime getTime() {+ return time;+ }++ public AttributeEvent.Source getSource() {+ return source;+ }++ public Optional<Value> getOldValue() {+ return Optional.ofNullable(oldValue);+ }++ public long getOldValueTimestamp() {+ return oldValueTimestamp;}public String getId() {return id;}+ public Date getCreatedOn() {+ return createdOn;+ }+public String getName() {return name;}@@ -217,64 +223,28 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdreturn coordinates;}- public Value getOldValue() {- return oldValue;- }-- public long getOldValueTimestamp() {- return oldValueTimestamp;- }-- public AttributeEvent.Source getSource() {- return source;- }-- public Optional<Value> getValue() {- return attribute.getValue();+ public boolean isValueChanged() {+ return !getValue().equals(Optional.ofNullable(oldValue));}public Optional<Boolean> getValueAsBoolean() {- return attribute.getValueAsBoolean();+ return getValue().flatMap(Values::getBoolean);}public Optional<Double> getValueAsNumber() {- return attribute.getValueAsNumber();+ return getValue().flatMap(Values::getNumber);}public Optional<String> getValueAsString() {- return attribute.getValueAsString();+ return getValue().flatMap(Values::getString);}public Optional<ObjectValue> getValueAsObject() {- return attribute.getValueAsObject();+ return getValue().flatMap(Values::getObject);}public Optional<ArrayValue> getValueAsArray() {- return attribute.getValueAsArray();- }-- public AssetAttribute getAttribute() {- return attribute;- }-- public String getAttributeName() {- return attribute.getName().orElse(null);- }-- public long getTimestamp() {- return attribute.getValueTimestamp().orElse(-1L);- }-- public LocalDateTime getTime() {- return time;- }-- public AttributeType getAttributeType() {- return attribute.getType().orElse(null);- }-- public boolean isValueChanged() {- return !attribute.getValue().equals(Optional.ofNullable(oldValue));+ return getValue().flatMap(Values::getArray);}/**@@ -289,7 +259,7 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpd* <code>true</code> if this value is not empty and the old value is null or this value is greater than old value.*/public boolean isValueGreaterThanOldValue() {- return isValueGreaterThan(Values.getNumber(getOldValue()).orElse(null));+ return isValueGreaterThan(Values.getNumber(getOldValue().orElse(null)).orElse(null));}/**@@ -304,7 +274,7 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpd* <code>true</code> if this value is empty and the old value is not null or this value is less than old value.*/public boolean isValueLessThanOldValue() {- return isValueLessThan(Values.getNumber(getOldValue()).orElse(null));+ return isValueLessThan(Values.getNumber(getOldValue().orElse(null)).orElse(null));}/**@@ -321,10 +291,6 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdreturn getValueAsBoolean().isPresent() && getValueAsBoolean().get();}- public AttributeRef getAttributeRef() {- return attribute.getReferenceOrThrow();- }-/*** Compares entity identifier, attribute name, value, and timestamp.*/@@ -335,15 +301,16 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpd/*** Compares entity identifier, attribute name, value, source, and optional timestamp.*/- public boolean matches(AttributeEvent that, AttributeEvent.Source source, boolean ignoreTimestamp) {- return getAttributeRef().equals(that.getAttributeRef())- && getValue().equals(that.getValue())- && (ignoreTimestamp || getTimestamp() == that.getTimestamp())+ public boolean matches(AttributeEvent event, AttributeEvent.Source source, boolean ignoreTimestamp) {+ return getId().equals(event.getEntityId())+ && getAttributeName().equals(event.getAttributeName())+ && getValue().equals(event.getValue())+ && (ignoreTimestamp || getTimestamp() == event.getTimestamp())&& (source == null || getSource() == source);}@Override- public int compareTo(AbstractAssetUpdate that) {+ public int compareTo(AssetState that) {int result = getId().compareTo(that.getId());if (result == 0)result = getAttributeName().compareTo(that.getAttributeName());@@ -356,17 +323,14 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdpublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;-- AbstractAssetUpdate that = (AbstractAssetUpdate) o;-- return getId().equals(that.getId()) &&- getAttribute().getName().equals(that.getAttribute().getName());+ AssetState that = (AssetState) o;+ return Objects.equals(attributeName, that.attributeName) &&+ Objects.equals(id, that.id);}@Overridepublic int hashCode() {- return getId().hashCode()- + getAttributeName().hashCode();+ return Objects.hash(attributeName, id);}@Override@@ -375,13 +339,13 @@ public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpd"id='" + getId() + '\'' +", name='" + getName() + '\'' +", parentName='" + getParentName() + '\'' +- ", typeString='" + getType() + '\'' ++ ", type='" + getType() + '\'' +", attributeName='" + getAttributeName() + '\'' +", attributeType=" + getAttributeType() +", value='" + (getValue().isPresent() ? getValue().get().toJson() : "null") + '\'' + // TODO Performance?", timestamp=" + getTimestamp() +", time=" + getTime() +- ", oldValue='" + (getOldValue() != null ? getOldValue().toJson() : "null") + '\'' ++ ", oldValue='" + (getOldValue().isPresent() ? getOldValue().get().toJson() : "null") + '\'' +", oldValueTimestamp=" + getOldValueTimestamp() +", source=" + getSource() +'}';diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex 66ba9b5f0..42f452abc 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -1,15 +1,13 @@package org.openremote.test.assetsimport org.openremote.agent.protocol.AbstractProtocol-import org.openremote.manager.asset.AssetProcessingService-import org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.asset.ServerAsset+import org.openremote.manager.asset.*import org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.asset.Assetimport org.openremote.model.asset.AssetAttributeimport org.openremote.model.asset.AssetMeta-import org.openremote.model.asset.AssetStateimport org.openremote.model.asset.AssetTypeimport org.openremote.model.asset.agent.ProtocolConfigurationimport org.openremote.model.attribute.*@@ -18,7 +16,7 @@ import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions-import java.util.function.Consumer+import javax.persistence.EntityManagerimport java.util.logging.Loggerclass AssetProcessingTest extends Specification implements ManagerContainerTrait {@@ -86,30 +84,50 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait}and: "mock attribute state consumers"- List<AssetState> updatesPassedStartOfProcessingChain = []- List<AssetState> updatesPassedRulesService = []- List<AssetState> updatesPassedAgentService = []- List<AssetState> updatesPassedAssetStorageService = []- List<AssetState> updatesPassedDatapointService = []-- Consumer<AssetState> mockStartConsumer = { assetUpdate ->- updatesPassedStartOfProcessingChain.add(assetUpdate)+ List<Attribute> updatesPassedStartOfProcessingChain = []+ List<Attribute> updatesPassedAgentService = []+ List<Attribute> updatesPassedRulesService = []+ List<Attribute> updatesPassedDatapointService = []+ List<Attribute> updatesPassedAttributeLinkingService = []++ AssetUpdateProcessor firstProcessor = new AssetUpdateProcessor() {+ @Override+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, AttributeEvent.Source source) throws AssetProcessingException {+ updatesPassedStartOfProcessingChain.add(attribute)+ false+ }}- Consumer<AssetState> mockRulesServiceConsumer = { assetState ->- updatesPassedRulesService.add(assetState)+ AssetUpdateProcessor afterAgentServiceProcessor = new AssetUpdateProcessor() {+ @Override+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, AttributeEvent.Source source) throws AssetProcessingException {+ updatesPassedAgentService.add(attribute)+ false+ }}- Consumer<AssetState> mockAgentServiceConsumer = { assetState ->- updatesPassedAgentService.add(assetState)+ AssetUpdateProcessor afterRulesServiceProcessor = new AssetUpdateProcessor() {+ @Override+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, AttributeEvent.Source source) throws AssetProcessingException {+ updatesPassedRulesService.add(attribute)+ false+ }}- Consumer<AssetState> mockAssetStorageConsumer = { assetState ->- updatesPassedAssetStorageService.add(assetState)+ AssetUpdateProcessor afterDatapointServiceProcessor = new AssetUpdateProcessor() {+ @Override+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, AttributeEvent.Source source) throws AssetProcessingException {+ updatesPassedDatapointService.add(attribute)+ false+ }}- Consumer<AssetState> mockDatapointServiceConsumer = { assetState ->- updatesPassedDatapointService.add(assetState)+ AssetUpdateProcessor afterAttributeLinkingServiceProcessor = new AssetUpdateProcessor() {+ @Override+ boolean processAssetUpdate(EntityManager em, Asset asset, AssetAttribute attribute, AttributeEvent.Source source) throws AssetProcessingException {+ updatesPassedAttributeLinkingService.add(attribute)+ false+ }}when: "the container is started with the mock protocol and consumers"@@ -126,11 +144,11 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait}then: "register mock asset processors"- assetProcessingService.processors.add(mockDatapointServiceConsumer)- assetProcessingService.processors.add(3, mockAssetStorageConsumer)- assetProcessingService.processors.add(2, mockRulesServiceConsumer)- assetProcessingService.processors.add(1, mockAgentServiceConsumer)- assetProcessingService.processors.add(0, mockStartConsumer)+ assetProcessingService.processors.add(0, firstProcessor)+ assetProcessingService.processors.add(2, afterAgentServiceProcessor)+ assetProcessingService.processors.add(4, afterRulesServiceProcessor)+ assetProcessingService.processors.add(6, afterDatapointServiceProcessor)+ assetProcessingService.processors.add(8, afterAttributeLinkingServiceProcessor)when: "a mock agent that uses the mock protocol is created"def mockAgent = new ServerAsset()@@ -190,47 +208,40 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitthen: "the attribute event should reach the protocol and stop at the agent service with a status of COMPLETED"conditions.eventually {assert updatesPassedStartOfProcessingChain.size() == 1+ assert updatesPassedStartOfProcessingChain[0].nameOrThrow == "light1Toggle"+ assert !updatesPassedStartOfProcessingChain[0].valueAsBoolean.get()+ assert sendToActuatorEvents.size() == 1assert updatesPassedAgentService.size() == 0assert updatesPassedRulesService.size() == 0- assert updatesPassedAssetStorageService.size() == 0assert updatesPassedDatapointService.size() == 0- assert updatesPassedStartOfProcessingChain[0].attribute.getAssetId().orElse("") == mockThing.getId()- assert updatesPassedStartOfProcessingChain[0].attribute.getName().orElse("") == "light1Toggle"- assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean().get()- assert updatesPassedStartOfProcessingChain[0].error == null- assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED- assert sendToActuatorEvents.size() == 1+ assert updatesPassedAttributeLinkingService.size() == 0}when: "the protocol updates the attributes value with the value it just received"updatesPassedStartOfProcessingChain.clear()updatesPassedRulesService.clear()updatesPassedAgentService.clear()- updatesPassedAssetStorageService.clear()updatesPassedDatapointService.clear()+ updatesPassedAttributeLinkingService.clear()mockProtocol.responseReceived()then: "a new attribute event should occur and reach the end of the processing chain"conditions.eventually {assert updatesPassedStartOfProcessingChain.size() == 1+ assert updatesPassedStartOfProcessingChain[0].nameOrThrow == "light1Toggle"+ assert !updatesPassedStartOfProcessingChain[0].valueAsBoolean.get()assert updatesPassedAgentService.size() == 1assert updatesPassedRulesService.size() == 1- assert updatesPassedAssetStorageService.size() == 1assert updatesPassedDatapointService.size() == 1- assert updatesPassedStartOfProcessingChain[0].attribute.getAssetId().orElse("") == mockThing.getId()- assert updatesPassedStartOfProcessingChain[0].attribute.getName().orElse("") == "light1Toggle"- assert !Values.getBoolean(updatesPassedStartOfProcessingChain[0].getOldValue()).orElse(true)- assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean().get()- assert updatesPassedStartOfProcessingChain[0].error == null- assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED+ assert updatesPassedAttributeLinkingService.size() == 1}when: "an attribute event occurs for the invalid protocol attribute"updatesPassedStartOfProcessingChain.clear()updatesPassedRulesService.clear()updatesPassedAgentService.clear()- updatesPassedAssetStorageService.clear()updatesPassedDatapointService.clear()+ updatesPassedAttributeLinkingService.clear()sendToActuatorEvents.clear()def light2toggleOn = new AttributeEvent(new AttributeState(new AttributeRef(mockThing.getId(), "light2Toggle"), Values.create(true))@@ -240,24 +251,20 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitthen: "the attribute event should pass the start of the processing chain, but not reach the mock protocol or the end of the processing chain and error should be populated"conditions.eventually {assert updatesPassedStartOfProcessingChain.size() == 1+ assert updatesPassedStartOfProcessingChain[0].nameOrThrow == "light2Toggle"+ assert sendToActuatorEvents.size() == 0assert updatesPassedAgentService.size() == 0assert updatesPassedRulesService.size() == 0- assert updatesPassedAssetStorageService.size() == 0assert updatesPassedDatapointService.size() == 0- assert sendToActuatorEvents.size() == 0- assert updatesPassedStartOfProcessingChain[0].id == mockThing.id- assert updatesPassedStartOfProcessingChain[0].attributeName == "light2Toggle"- assert updatesPassedStartOfProcessingChain[0].error != null- assert updatesPassedStartOfProcessingChain[0].error instanceof RuntimeException- assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.ERROR+ assert updatesPassedAttributeLinkingService.size() == 0}when: "an attribute event occurs for the plain attribute"updatesPassedStartOfProcessingChain.clear()updatesPassedRulesService.clear()updatesPassedAgentService.clear()- updatesPassedAssetStorageService.clear()updatesPassedDatapointService.clear()+ updatesPassedAttributeLinkingService.clear()sendToActuatorEvents.clear()def plainAttributeTest = new AttributeEvent(new AttributeState(new AttributeRef(mockThing.getId(), "plainAttribute"), Values.create("test"))@@ -269,15 +276,11 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert updatesPassedStartOfProcessingChain.size() == 1assert updatesPassedAgentService.size() == 1assert updatesPassedRulesService.size() == 1- assert updatesPassedAssetStorageService.size() == 1assert updatesPassedDatapointService.size() == 1+ assert updatesPassedAttributeLinkingService.size() == 1+ assert updatesPassedAttributeLinkingService[0].nameOrThrow == "plainAttribute"+ assert updatesPassedAttributeLinkingService[0].valueAsString.orElse(null) == "test"assert sendToActuatorEvents.size() == 0- assert updatesPassedDatapointService[0].name == "Mock Thing Asset"- assert updatesPassedDatapointService[0].attributeName == "plainAttribute"- assert Values.getString(updatesPassedDatapointService[0].oldValue).orElse(null) == "demo"- assert updatesPassedDatapointService[0].valueAsString.orElse(null) == "test"- assert updatesPassedDatapointService[0].error == null- assert updatesPassedDatapointService[0].processingStatus == AssetState.ProcessingStatus.COMPLETED}cleanup: "the server should be stopped"diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex b1b716d55..03420a259 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -159,7 +159,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassertRulesFired(rulesImport.apartment2Engine, ["All"])assertRulesFired(rulesImport.apartment3Engine, 0)assertRulesFired(smartHomeEngine, 8)- assertRulesFired(smartHomeEngine, ["Living Room All", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])+ assertRulesFired(smartHomeEngine, ["Living Room All", "Kitchen All", "Kitchen Number Attributes", "Parent Type Residence", "Asset Type Room", "Boolean Attributes", "String attributes", "Number value types"])}when: "an attribute event occurs"@@ -178,8 +178,8 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassertRulesFired(rulesImport.apartment2Engine, 1)assertRulesFired(rulesImport.apartment2Engine, ["All"])assertRulesFired(rulesImport.apartment3Engine, 0)- assertRulesFired(smartHomeEngine, 9)- assertRulesFired(smartHomeEngine, ["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])+ assertRulesFired(smartHomeEngine, 8)+ assertRulesFired(smartHomeEngine, ["Living Room All", "Kitchen All", "Kitchen Number Attributes", "Parent Type Residence", "Asset Type Room", "Boolean Attributes", "String attributes", "Number value types"])}cleanup: "the server should be stopped"diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovyindex 8a2311946..f235b3159 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy+++ b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy@@ -2,7 +2,6 @@ package org.openremote.test.rulesimport org.openremote.manager.rules.RulesBuilderimport org.openremote.model.asset.AssetQuery-import org.openremote.model.asset.AssetStateimport org.openremote.model.asset.AssetTypeimport org.openremote.model.attribute.AttributeType@@ -88,20 +87,6 @@ rules.add()facts.put("Number value types", "fired")})-rules.add()- .name("Current Asset Update")- .when(- { facts ->- !facts.matchFirst("Current Asset Update").isPresent() &&- facts.matchAssetState(new AssetQuery())- .filter({ assetState -> assetState.processingStatus != AssetState.ProcessingStatus.COMPLETED })- .findFirst().isPresent()- })- .then(- { facts ->- facts.put("Current Asset Update", "fired")- })-rules.add().name("Parent Type Residence").when(