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
Cleanup of AssetUpdate and minor bug fixes
Rich Turnerb4fe7d9270f4
diff --git a/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java b/agent/src/main/java/org/openremote/agent/rules/RuleEngine.javaindex 4af7b3b3c..d01c880c8 100644--- a/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java+++ b/agent/src/main/java/org/openremote/agent/rules/RuleEngine.java@@ -45,6 +45,7 @@ import org.openremote.agent.context.AgentContext;import org.openremote.agent.sensor.SensorState;import org.openremote.agent.sensor.SensorStateUpdate;import org.openremote.container.Container;+import org.openremote.container.util.Util;import java.util.Collection;import java.util.HashMap;@@ -65,7 +66,7 @@ public class RuleEngine {private LevelFacade levelFacade;private RangeFacade rangeFacade;private RulePersistence rulePersistence;- private RuleUtil ruleUtil;+ private Util ruleUtil;public void start(AgentContext agentContext) {@@ -101,7 +102,7 @@ public class RuleEngine {rangeFacade = new RangeFacade();levelFacade = new LevelFacade();rulePersistence = new RulePersistence();- ruleUtil = new RuleUtil();+ ruleUtil = new Util();setGlobal("commands", agentContext.getDeployment().getCommands());setGlobal("switches", switchFacade);diff --git a/agent/src/main/java/org/openremote/agent/rules/RuleUtil.java b/container/src/main/java/org/openremote/container/util/Util.javasimilarity index 76%rename from agent/src/main/java/org/openremote/agent/rules/RuleUtil.javarename to container/src/main/java/org/openremote/container/util/Util.javaindex cba49f044..959c9a87c 100644--- a/agent/src/main/java/org/openremote/agent/rules/RuleUtil.java+++ b/container/src/main/java/org/openremote/container/util/Util.java@@ -1,16 +1,34 @@-package org.openremote.agent.rules;+package org.openremote.container.util;+import java.lang.reflect.Array;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;-public class RuleUtil {+public class Util {+ public static <T> T[] reverseArray(T[] array, Class<T> clazz) {+ if (array == null) {+ return null;+ }+ T[] newArray = createArray(array.length, clazz);+ int j = 0;+ for (int i=array.length; i>0; i--) {+ newArray[j] = array[i-1];+ j++;+ }+ return newArray;+ }++ @SuppressWarnings("unchecked")+ public static <T> T[] createArray(int size, Class<T> clazz) {+ return (T[]) Array.newInstance(clazz, size);+ }/*** @param o A timestamp string as 'HH:mm:ss' or 'HH:mm'.* @return Epoch time or 0 if there is a problem parsing the timestamp string.*/- public long parseTimestamp(Object o) {+ public static long parseTimestamp(Object o) {String timestamp = o.toString();SimpleDateFormat sdf;if (timestamp.length() == 8) {@@ -31,7 +49,7 @@ public class RuleUtil {* @param timestamp Epoch time* @return The timestamp formatted as 'HH:mm' or <code>null</code> if the timestamp is <= 0.*/- public String formatTimestamp(long timestamp) {+ public static String formatTimestamp(long timestamp) {if (timestamp <= 0)return null;SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");@@ -42,7 +60,7 @@ public class RuleUtil {* @param timestamp Epoch time* @return The timestamp formatted as 'HH:mm:ss' or <code>null</code> if the timestamp is <= 0.*/- public String formatTimestampWithSeconds(long timestamp) {+ public static String formatTimestampWithSeconds(long timestamp) {if (timestamp <= 0)return null;SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");@@ -55,7 +73,7 @@ public class RuleUtil {* @return Timestamp string as 'HH:mm', modified with the given minutes or the current time + 60 minutes if* the given timestamp was '-' or the given timestamp couldn't be parsed.*/- public String shiftTime(Object o, int minutes) {+ public static String shiftTime(Object o, int minutes) {String timestamp = o.toString();SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");Date date = null;@@ -78,7 +96,7 @@ public class RuleUtil {* @param o A string representation of a double value.* @return The parsed value or 0.0 if the string couldn't be parsed.*/- public Double parseDouble(Object o) {+ public static Double parseDouble(Object o) {String s = o.toString();try {if (s.length() >= 1) {@@ -96,7 +114,7 @@ public class RuleUtil {* @param shift Increments or decrements the parsed value.* @param suffix A string appended to the result.*/- public String shiftDouble(Object o, double shift, String suffix) {+ public static String shiftDouble(Object o, double shift, String suffix) {Double d = parseDouble(o);d = d + shift;return (String.format("%.1f", d) + suffix);diff --git a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.javaindex dff3b6da5..2d9fb125d 100644--- a/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/agent/AgentService.java@@ -31,10 +31,9 @@ import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.AssetUpdate;import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.datapoint.AssetDatapointService;-import org.openremote.model.asset.Asset;-import org.openremote.model.asset.AssetQuery;-import org.openremote.model.asset.AssetType;-import org.openremote.model.asset.ThingAttribute;+import org.openremote.model.AttributeRef;+import org.openremote.model.Function;+import org.openremote.model.asset.*;import java.util.Collection;import java.util.List;@@ -57,6 +56,17 @@ public class AgentService extends RouteBuilder implements ContainerService, Consprivate static final Logger LOG = Logger.getLogger(AgentService.class.getName());+ final protected Function<AttributeRef, ProtocolConfiguration> agentLinkResolver = agentLink -> {+ // Resolve the agent and the protocol configuration+ // TODO This is very inefficient and requires Hibernate second-level caching+ Asset agent = find(agentLink.getEntityId());+ if (agent != null && agent.getWellKnownType().equals(AGENT)) {+ AgentAttributes agentAttributes = new AgentAttributes(agent);+ return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());+ }+ return null;+ };+protected Container container;protected AssetStorageService assetStorageService;protected AssetDatapointService assetDatapointService;@@ -128,7 +138,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Attributes grouped by protocol nameMap<String, List<ThingAttribute>> linkedAttributes = thingAttributes.getLinkedAttributes(// Linked attributes have a reference to an agent, and a protocol configuration attribute of that agent- assetStorageService.getAgentLinkResolver()+ getAgentLinkResolver());LOG.fine("Thing has attribute links to " + linkedAttributes.size() + " protocol(s): " + thing);@@ -184,6 +194,14 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons}}+ protected Asset find(String id) {+ return assetStorageService.find(id, true, false);+ }++ public Function<AttributeRef, ProtocolConfiguration> getAgentLinkResolver() {+ return agentLinkResolver;+ }+/*** If this update is not for an asset of type THING or it has been initiated by* a protocol then we ignore it.@@ -197,7 +215,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons@Overridepublic void accept(AssetUpdate assetUpdate) {// Check that asset is a THING- if (assetUpdate.getAsset().getWellKnownType() != THING) {+ if (!assetUpdate.getAssetType().equals(THING.getValue())) {LOG.fine("Ignoring asset update as asset is not a THING:" + assetUpdate);return;}@@ -208,16 +226,13 @@ public class AgentService extends RouteBuilder implements ContainerService, Consreturn;}- boolean hasAgentLink = ThingAttribute.getAgentLink(assetUpdate.getAttribute()) != null;+ AttributeRef agentLink = ThingAttribute.getAgentLink(assetUpdate.getAttribute());- if (hasAgentLink) {+ if (agentLink != null) {// Check attribute is linked to an actual agent- ThingAttributes thingAttributes = new ThingAttributes(assetUpdate.getAsset());- ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(- assetStorageService.getAgentLinkResolver(), assetUpdate.getAttribute().getName()- );+ ProtocolConfiguration protocolConfiguration = getAgentLinkResolver().apply(agentLink);- if (thingAttribute == null) {+ if (protocolConfiguration == null) {LOG.warning("Cannot process asset update as agent link is invalid:" + assetUpdate);assetUpdate.setStatus(AssetUpdate.Status.ERROR);return;@@ -230,7 +245,7 @@ public class AgentService extends RouteBuilder implements ContainerService, Cons// Its' a send to actuator - push the update to the protocolLOG.fine("Processing asset update: " + assetUpdate);- messageBrokerService.getProducerTemplate().sendBody(ACTUATOR_TOPIC, assetUpdate.getNewState());+ messageBrokerService.getProducerTemplate().sendBody(ACTUATOR_TOPIC, assetUpdate.getAttribute().getState(assetUpdate.getAssetId()));assetUpdate.setStatus(AssetUpdate.Status.HANDLED);}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.javaindex 938a7f4a2..e903cb6b6 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetProcessingService.java@@ -228,7 +228,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerprotected void processSensorUpdate(AttributeEvent attributeEvent) {// Must reference a thing assetServerAsset thing = assetStorageService.find(attributeEvent.getEntityId(), true);- if (thing.getWellKnownType() != THING) {+ if (thing == null || thing.getWellKnownType() != THING) {LOG.fine("Ignoring " + attributeEvent + ", not a thing: " + thing);return;}@@ -241,7 +241,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer// for a day)ThingAttributes thingAttributes = new ThingAttributes(thing);ThingAttribute thingAttribute = thingAttributes.getLinkedAttribute(- assetStorageService.getAgentLinkResolver(), attributeEvent.getAttributeName()+ agentService.getAgentLinkResolver(), attributeEvent.getAttributeName());if (thingAttribute == null) {@@ -285,7 +285,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerreturn;}- processUpdate(new AssetUpdate(asset, attribute, attributeEvent, lastStateEvent));+ processUpdate(new AssetUpdate(asset, attribute, lastStateEvent.getValue(), lastStateEvent.getTimestamp(), attributeEvent.getSender()));}protected void processUpdate(AssetUpdate assetUpdate) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.javaindex 4802827d8..2c6b6508f 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetStorageService.java@@ -57,17 +57,6 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpdaprotected ManagerIdentityService managerIdentityService;protected AssetProcessingService assetProcessingService;- final protected Function<AttributeRef, ProtocolConfiguration> agentLinkResolver = agentLink -> {- // Resolve the agent and the protocol configuration- // TODO This is very inefficient and requires Hibernate second-level caching- Asset agent = find(agentLink.getEntityId(), true, false);- if (agent != null && agent.getWellKnownType().equals(AGENT)) {- AgentAttributes agentAttributes = new AgentAttributes(agent);- return agentAttributes.getProtocolConfiguration(agentLink.getAttributeName());- }- return null;- };-@Overridepublic void init(Container container) throws Exception {persistenceService = container.getService(PersistenceService.class);@@ -94,7 +83,7 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda@Overridepublic void accept(AssetUpdate assetUpdate) {- String assetId = assetUpdate.getAsset().getId();+ String assetId = assetUpdate.getAssetId();String attributeName = assetUpdate.getAttribute().getName();JsonValue value = assetUpdate.getAttribute().getValue();// Some sanity checking, of course the timestamp should never be -1 if we store updated attribute state@@ -107,10 +96,6 @@ public class AssetStorageService implements ContainerService, Consumer<AssetUpda}}- public Function<AttributeRef, ProtocolConfiguration> getAgentLinkResolver() {- return agentLinkResolver;- }-public ServerAsset find(String assetId) {return find(new AssetQuery().id(assetId));}diff --git a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.javaindex 9bc160a90..4a945ac22 100644--- a/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java+++ b/manager/server/src/main/java/org/openremote/manager/server/asset/AssetUpdate.java@@ -19,8 +19,12 @@*/package org.openremote.manager.server.asset;+import elemental.json.JsonValue;import org.openremote.model.Attribute;-import org.openremote.model.AttributeEvent;+import org.openremote.model.AttributeType;+import org.openremote.model.asset.Asset;++import java.util.Date;/*** An asset attribute value change that can be handled by a sequence of processors.@@ -42,7 +46,7 @@ public class AssetUpdate {HANDLED,/**- * Don't process event in any more rules but continue through rest of processing chain.+ * Don't process event in any more rule engines but continue through rest of processing chain.*/RULES_HANDLED,@@ -53,100 +57,189 @@ public class AssetUpdate {/*** Indicates that this update has been through the entire processing chain; the object can no longer be- * mutated at this stage+ * mutated at this stage.*/COMPLETED}- final protected ServerAsset asset;final protected Attribute attribute;- final protected AttributeEvent newState;- final protected AttributeEvent oldState;++ final protected Date assetCreatedOn;++ final protected String assetId;++ final protected String assetName;++ final protected String assetType;++ final protected String[] assetPath;++ final protected String assetParentId;++ final protected String assetParentName;++ final protected String assetParentType;++ final protected String assetRealmId;++ final protected String assetRealmName;++ final protected double[] coordinates;++ final protected JsonValue oldValue;++ final protected long oldValueTimestamp;protected Status status = Status.CONTINUE;+protected Throwable error;- /**- * @throws IllegalArgumentException If the asset, attribute, newState, and oldState don't reference the same asset ID and attribute name.- */- public AssetUpdate(ServerAsset asset, Attribute attribute, AttributeEvent newState, AttributeEvent oldState) throws IllegalArgumentException {- this.asset = asset;+ final protected Class<?> sender;++ public AssetUpdate(Asset asset, Attribute attribute) {+ this(asset, attribute, null, 0, null);+ }++ public AssetUpdate(Asset asset, Attribute attribute, JsonValue oldValue, long oldValueTimestamp, Class<?> sender) {this.attribute = attribute;- this.newState = newState;- this.oldState = oldState;+ this.assetId = asset.getId();+ this.assetName = asset.getName();+ this.assetPath = asset.getPath();+ this.assetType = asset.getType();+ this.assetCreatedOn = asset.getCreatedOn();+ this.assetParentId = asset.getParentId();+ this.assetParentName = asset.getParentName();+ this.assetParentType = asset.getParentType();+ this.assetRealmId = asset.getRealmId();+ this.assetRealmName = asset.getTenantRealm();+ this.coordinates = asset.getCoordinates();+ this.oldValue = oldValue;+ this.oldValueTimestamp = oldValueTimestamp;+ this.sender = sender;+ }- // Resolve attribute references after some sanity checks- if (!newState.getAttributeRef().getEntityId().equals(asset.getId())) {- throw new IllegalArgumentException("New state entity ID must match: " + asset);- }- if (!newState.getAttributeRef().getAttributeName().equals(attribute.getName())) {- throw new IllegalArgumentException("New state attribute name must match: " + attribute);- }+ public Date getAssetCreatedOn() {+ return assetCreatedOn;+ }- if (oldState != null) {- if (!oldState.getAttributeRef().getEntityId().equals(asset.getId())) {- throw new IllegalArgumentException("Old state entity ID must match: " + asset);- }- if (!oldState.getAttributeRef().getAttributeName().equals(attribute.getName())) {- throw new IllegalArgumentException("Old state attribute name must match: " + attribute);- }+ public String getAssetId() {+ return assetId;+ }- oldState.getAttributeRef().setEntityName(asset.getName());- }+ public String getAssetName() {+ return assetName;+ }- newState.getAttributeRef().setEntityName(asset.getName());+ public String getAssetType() {+ return assetType;}- public ServerAsset getAsset() {- return asset;+ public String[] getAssetPath() {+ return assetPath;}- public Attribute getAttribute() {- return attribute;+ public String getAssetParentId() {+ return assetParentId;}- public AttributeEvent getNewState() {- return newState;+ public String getAssetParentName() {+ return assetParentName;}- public Class<?> getSender() {- return newState.getSender();+ public String getAssetParentType() {+ return assetParentType;+ }++ public String getAssetRealmId() {+ return assetRealmId;+ }++ public String getAssetRealmName() {+ return assetRealmName;+ }++ public double[] getCoordinates() {+ return coordinates;+ }++ public JsonValue getOldValue() {+ return oldValue;}- public AttributeEvent getOldState() {- return oldState;+ public long getOldValueTimestamp() {+ return oldValueTimestamp;}public Status getStatus() {return status;}+ public Throwable getError() {+ return error;+ }++ public Class<?> getSender() {+ return sender;+ }++ public JsonValue getValue() {+ return attribute.getValue();+ }++ public String getAttributeName() {+ return attribute.getName();+ }++ public long getValueTimestamp() {+ return attribute.getValueTimestamp();+ }++ public AttributeType getAttributeType() {+ return attribute.getType();+ }+public boolean isCompleted() {return getStatus() == Status.COMPLETED;}public boolean isValueChanged() {- return !newState.getAttributeState().getValue().jsEquals(oldState.getAttributeState().getValue());+ return !attribute.getValue().jsEquals(oldValue);}- public String getEntityName() {- return newState.getEntityName();+ /////////////////////////////////////////////////////////////////+ // GETTERS AND SETTERS BELOW CAN ONLY BE USED WHEN STATUS IS NOT COMPLETED+ /////////////////////////////////////////////////////////////////++ public Attribute getAttribute() {+ if (!isCompleted()) {+ return attribute;+ }++ return null;}- public String getEntityId() {- return newState.getEntityId();+ public void setValue(JsonValue value) {+ if (!isCompleted()) {+ attribute.setValue(value);+ }}- public void setStatus(Status status) {- this.status = status;+ public void setValueUnchecked(JsonValue value) {+ if (!isCompleted()) {+ attribute.setValueUnchecked(value);+ }}- public Throwable getError() {- return error;+ public void setStatus(Status status) {+ if (!isCompleted()) {+ this.status = status;+ }}public void setError(Throwable error) {- this.error = error;+ if (!isCompleted()) {+ this.error = error;+ }}@Override@@ -156,21 +249,28 @@ public class AssetUpdate {AssetUpdate that = (AssetUpdate) o;- return ((oldState == null && that.oldState == null) || (oldState != null && that.oldState != null && oldState.equals(that.oldState)))- && ((newState == null && that.newState == null) || (newState != null && that.newState != null && newState.equals(that.newState)));+ return assetId.equals(that.assetId) &&+ getAttributeName().equalsIgnoreCase(that.getAttributeName()) &&+ getValue().jsEquals(that.getValue()) &&+ getValueTimestamp() == that.getValueTimestamp() &&+ ((oldValue == null && that.oldValue == null) || (oldValue != null && oldValue.jsEquals(that.oldValue))) &&+ oldValueTimestamp == that.oldValueTimestamp;}@Overridepublic int hashCode() {- return oldState.hashCode() + newState.hashCode();+ return assetId.hashCode() + getAttributeName().hashCode() + getValue().hashCode() + Long.hashCode(getValueTimestamp()) + (oldValue != null ? oldValue.hashCode() : 0) + Long.hashCode(oldValueTimestamp);}@Overridepublic String toString() {return getClass().getSimpleName() + "{" +- "newState=" + newState +- ", oldState=" + oldState +- ", status=" + status ++ "assetId=" + getAssetName() ++ "attributeName=" + getAttributeName() ++ "value=" + getValue() ++ "valueTimestamp=" + getValueTimestamp() ++ "oldValue=" + getOldValue() ++ "oldValueTimestamp=" + getOldValueTimestamp() +'}';}}diff --git a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.javaindex 91e070a36..67421823a 100644--- a/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/datapoint/AssetDatapointService.java@@ -36,7 +36,7 @@ public class AssetDatapointService implements ContainerService, Consumer<AssetUp@Overridepublic void accept(AssetUpdate assetUpdate) {if (assetUpdate.getAttribute().isStoreDatapoints()) {- AssetDatapoint assetDatapoint = new AssetDatapoint(assetUpdate.getNewState());+ AssetDatapoint assetDatapoint = new AssetDatapoint(assetUpdate.getAttribute().getStateEvent(assetUpdate.getAssetId()));persistenceService.doTransaction(entityManager -> {entityManager.persist(assetDatapoint);});diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.javadeleted file mode 100644index 29498b8f4..000000000--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RuleUtil.java+++ /dev/null@@ -1,104 +0,0 @@-package org.openremote.manager.server.rules;--import java.text.ParseException;-import java.text.SimpleDateFormat;-import java.util.Date;--public class RuleUtil {-- /**- * @param o A timestamp string as 'HH:mm:ss' or 'HH:mm'.- * @return Epoch time or 0 if there is a problem parsing the timestamp string.- */- public long parseTimestamp(Object o) {- String timestamp = o.toString();- SimpleDateFormat sdf;- if (timestamp.length() == 8) {- sdf = new SimpleDateFormat("HH:mm:ss");- } else if (timestamp.length() == 5) {- sdf = new SimpleDateFormat("HH:mm");- } else {- return (0L);- }- try {- return (sdf.parse(timestamp).getTime());- } catch (ParseException e) {- return (0L);- }- }-- /**- * @param timestamp Epoch time- * @return The timestamp formatted as 'HH:mm' or <code>null</code> if the timestamp is <= 0.- */- public String formatTimestamp(long timestamp) {- if (timestamp <= 0)- return null;- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");- return (sdf.format(new Date(timestamp)));- }-- /**- * @param timestamp Epoch time- * @return The timestamp formatted as 'HH:mm:ss' or <code>null</code> if the timestamp is <= 0.- */- public String formatTimestampWithSeconds(long timestamp) {- if (timestamp <= 0)- return null;- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");- return (sdf.format(new Date(timestamp)));- }-- /**- * @param o A timestamp string as 'HH:mm' or '-'.- * @param minutes The minutes to increment/decrement from timestamp.- * @return Timestamp string as 'HH:mm', modified with the given minutes or the current time + 60 minutes if- * the given timestamp was '-' or the given timestamp couldn't be parsed.- */- public String shiftTime(Object o, int minutes) {- String timestamp = o.toString();- SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");- Date date = null;- if (timestamp != null && timestamp.length() >= 1 && timestamp.substring(0, 1).equals("-")) {- date = new Date();- date.setTime(date.getTime() + 60 * 60000);- } else {- try {- date = sdf.parse(timestamp);- date.setTime(date.getTime() + minutes * 60000);- } catch (ParseException ex) {- date = new Date();- date.setTime(date.getTime() + 60 * 60000);- }- }- return (sdf.format(date));- }-- /**- * @param o A string representation of a double value.- * @return The parsed value or 0.0 if the string couldn't be parsed.- */- public Double parseDouble(Object o) {- String s = o.toString();- try {- if (s.length() >= 1) {- return (Double.parseDouble(s.substring(0, s.length() - 1)));- } else {- return (0.0);- }- } catch (NumberFormatException e) {- return (0.0);- }- }-- /**- * @param o A string representation of a double value.- * @param shift Increments or decrements the parsed value.- * @param suffix A string appended to the result.- */- public String shiftDouble(Object o, double shift, String suffix) {- Double d = parseDouble(o);- d = d + shift;- return (String.format("%.1f", d) + suffix);- }-}diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.javaindex 09b75f551..e3c82def1 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java@@ -20,7 +20,6 @@package org.openremote.manager.server.rules;import elemental.json.Json;-import org.drools.core.factmodel.Fact;import org.kie.api.KieServices;import org.kie.api.builder.KieBuilder;import org.kie.api.builder.KieFileSystem;@@ -38,12 +37,10 @@ import org.kie.api.runtime.conf.ClockTypeOption;import org.kie.api.runtime.conf.TimedRuleExectionOption;import org.kie.api.runtime.rule.FactHandle;import org.kie.api.time.SessionClock;+import org.openremote.container.util.Util;import org.openremote.manager.server.asset.AssetUpdate;import org.openremote.manager.shared.rules.RulesDefinition;-import org.openremote.model.AttributeRef;-import org.openremote.model.asset.Asset;-import java.lang.reflect.Array;import java.util.*;import java.util.concurrent.Executors;import java.util.concurrent.ScheduledExecutorService;@@ -58,7 +55,7 @@ public class RulesDeployment<T extends RulesDefinition> {protected static ClockTypeOption DefaultClockType;private static final int AUTO_START_DELAY_SECONDS = 2;private static Long counter = 1L;- static final protected RuleUtil ruleUtil = new RuleUtil();+ static final protected Util UTIL = new Util();protected final Map<Long, T> ruleDefinitions = new LinkedHashMap<>();protected final RuleExecutionLogger ruleExecutionLogger = new RuleExecutionLogger();protected KieSession knowledgeSession;@@ -87,7 +84,7 @@ public class RulesDeployment<T extends RulesDefinition> {@SuppressWarnings("unchecked")public synchronized T[] getAllRulesDefinitions() {- T[] arr = (T[]) Array.newInstance(clazz, 0);+ T[]arr = Util.createArray(ruleDefinitions.size(), clazz);return ruleDefinitions.values().toArray(arr);}@@ -324,7 +321,7 @@ public class RulesDeployment<T extends RulesDefinition> {try {knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);- setGlobal("util", ruleUtil);+ setGlobal("util", UTIL);setGlobal("JSON", Json.instance());setGlobal("LOG", LOG);@@ -372,29 +369,24 @@ public class RulesDeployment<T extends RulesDefinition> {}protected synchronized void retractFact(AssetUpdate assetUpdate) {- AttributeRef attributeRef = assetUpdate.getNewState().getAttributeRef();// If there already is a fact in working memory for this attribute then delete itAssetUpdate update = facts.keySet().stream()- .filter(au -> au.getAttribute().getAttributeRef(au.getEntityId()).equals(attributeRef))+ .filter(au -> au.getAssetId().equals(assetUpdate.getAssetId()) && au.getAttributeName().equals(assetUpdate.getAttributeName())).findFirst().orElse(null);FactHandle factHandle = update != null ? facts.get(update) : null;- if (factHandle != null && knowledgeSession != null) {- try {- // ... retract it from working memory ...- LOG.finest("Removed stale attribute fact: " + attributeRef);- knowledgeSession.delete(factHandle);- } finally {- // ... and make sure we don't keep a reference to the stale fact- facts.remove(update);- }+ if (factHandle != null && knowledgeSession != null) try {+ // ... retract it from working memory ...+ LOG.finest("Removed stale attribute fact: " + update);+ knowledgeSession.delete(factHandle);+ } finally {+ // ... and make sure we don't keep a reference to the stale fact+ facts.remove(update);}-- return;}protected FactHandle insertFactIntoSession(AssetUpdate assetUpdate) {diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.javaindex ec3923248..f428d097c 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java@@ -27,6 +27,7 @@ import org.openremote.container.message.MessageBrokerSetupService;import org.openremote.container.persistence.PersistenceEvent;import org.openremote.container.persistence.PersistenceService;import org.openremote.container.util.Pair;+import org.openremote.container.util.Util;import org.openremote.manager.server.asset.AssetStorageService;import org.openremote.manager.server.asset.AssetUpdate;import org.openremote.manager.server.asset.ServerAsset;@@ -119,7 +120,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Consreturn rulesFact != null && rulesFact.getValueAsBoolean();}).forEach(attribute -> {- AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ AssetUpdate update = new AssetUpdate(serverAsset, attribute);// Set the status to completed already so rules cannot interfere with this initial insertupdate.setStatus(AssetUpdate.Status.COMPLETED);insertFact(update, true);@@ -155,7 +156,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.stream().noneMatch(newLink -> oldLink.getJsonObject().jsEquals(newLink.getJsonObject()))).forEach(obsoleteLink -> {- AssetUpdate update = new AssetUpdate(serverAsset, obsoleteLink, obsoleteLink.getStateEvent(asset.getId()), null);+ AssetUpdate update = new AssetUpdate(serverAsset, obsoleteLink);retractFact(update);});@@ -166,7 +167,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons.stream().noneMatch(oldFact -> newFact.getJsonObject().jsEquals(newFact.getJsonObject()))).forEach(newLinkedAttribute -> {- AssetUpdate update = new AssetUpdate(serverAsset, newLinkedAttribute, newLinkedAttribute.getStateEvent(asset.getId()), null);+ AssetUpdate update = new AssetUpdate(serverAsset, newLinkedAttribute);// Set the status to completed already so rules cannot interfere with this initial insertinsertFact(update, true);});@@ -181,7 +182,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Consreturn rulesFact != null && rulesFact.getValueAsBoolean();}).forEach(attribute -> {- AssetUpdate update = new AssetUpdate(serverAsset, attribute, attribute.getStateEvent(asset.getId()), null);+ AssetUpdate update = new AssetUpdate(serverAsset, attribute);retractFact(update);});break;@@ -393,8 +394,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons// TODO: implement rules processing error state handling// Get the chain of rule engines that we need to pass through- ServerAsset asset = assetUpdate.getAsset();- List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getReversePath());+ List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getAssetRealmId(), assetUpdate.getAssetPath());// Pass through each engine and try and insert the factfor (RulesDeployment deployment : rulesDeployments) {@@ -416,8 +416,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Consprotected void retractFact(AssetUpdate assetUpdate) {// Get the chain of rule engines that we need to pass through- ServerAsset asset = assetUpdate.getAsset();- List<RulesDeployment> rulesDeployments = getEnginesInScope(asset.getRealmId(), asset.getReversePath());+ List<RulesDeployment> rulesDeployments = getEnginesInScope(assetUpdate.getAssetRealmId(), assetUpdate.getAssetPath());// Pass through each engine and retract this factfor (RulesDeployment deployment : rulesDeployments) {@@ -426,6 +425,9 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons}protected List<RulesDeployment> getEnginesInScope(String assetRealmId, String[] assetPath) {+ // We need to reverse the asset path to start from the top down+ assetPath = Util.reverseArray(assetPath, String.class);+List<RulesDeployment> rulesDeployments = new ArrayList<>();// Add global engine (if it exists)diff --git a/model/src/main/java/org/openremote/model/asset/Asset.java b/model/src/main/java/org/openremote/model/asset/Asset.javaindex cc34b21d1..c89dd745d 100644--- a/model/src/main/java/org/openremote/model/asset/Asset.java+++ b/model/src/main/java/org/openremote/model/asset/Asset.java@@ -482,9 +482,14 @@ public class Asset implements IdentifiableEntity {public String[] getReversePath() {if (path == null)return null;- List<String> list = Arrays.asList(getPath());- Collections.reverse(list);- return list.toArray(new String[list.size()]);++ String[] newArray = new String[path.length];+ int j = 0;+ for (int i=path.length; i>0; i--) {+ newArray[j] = path[i-1];+ j++;+ }+ return newArray;}public boolean pathContains(String assetId) {