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
Added RuleActionUpdateAttribute so it's possible to modify content of ObjectValue and ArrayValue
Michael Rademaker9d99be8c1909
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex a9d897cb0..abb5b3dc6 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -23,25 +23,26 @@ import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.rules.facade.NotificationsFacade;-import org.openremote.model.attribute.Meta;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.asset.Asset;+import org.openremote.model.attribute.Attribute;import org.openremote.model.notification.Notification;+import org.openremote.model.query.AssetQuery;import org.openremote.model.query.BaseAssetQuery;-import org.openremote.model.query.NewAssetQuery;import org.openremote.model.query.UserQuery;-import org.openremote.model.query.filter.AttributeMetaPredicate;-import org.openremote.model.query.filter.NewAttributePredicate;import org.openremote.model.rules.AssetState;import org.openremote.model.rules.Assets;import org.openremote.model.rules.Users;import org.openremote.model.rules.json.*;import org.openremote.model.util.TextUtil;-import org.openremote.model.value.Value;+import org.openremote.model.value.*;-import java.util.*;+import java.util.List;+import java.util.Objects;+import java.util.Optional;import java.util.function.BiConsumer;import java.util.function.BiPredicate;import java.util.function.Predicate;-import java.util.function.Supplier;import java.util.stream.Collectors;import java.util.stream.Stream;@@ -324,6 +325,99 @@ public class JsonRulesBuilder extends RulesBuilder {if (millis > 0) {delay += millis;}+ } else if (ruleAction instanceof RuleActionUpdateAttribute) {+ RuleActionUpdateAttribute attributeUpdateAction = (RuleActionUpdateAttribute) ruleAction;++ if (!TextUtil.isNullOrEmpty(attributeUpdateAction.attributeName)) {+ RuleActionWithTarget.Target target = attributeUpdateAction.target;++ List<String> ids = null;++ if (target != null) {++ // Only assets make sense as the target+ if (target.useAssetsFromWhen && assetStates != null) {+ ids = assetStates.stream().map(AssetState::getId).collect(Collectors.toList());+ } else if (target.assets != null) {+ ids = getAssetIds(assetsFacade, target.assets);+ }+ }++ if (ids != null) {+ List<String> finalIds = ids;+ action = () ->+ finalIds.forEach(id -> {+ ValueType valueType = null;+ Value currentValue = null;+ if (assetStates != null) {+ Optional<AssetState> assetState = assetStates+ .stream()+ .filter(state -> state.getId().equals(id) && state.getAttributeName().equals(attributeUpdateAction.attributeName))+ .findFirst();+ if (assetState.isPresent()) {+ valueType = assetState.get().getAttributeValueType().getValueType();+ if (valueType.equals(ValueType.ARRAY)) {+ currentValue = assetState.get().getValue().orElse(Values.createArray());+ } else if (valueType.equals(ValueType.OBJECT)) {+ currentValue = assetState.get().getValue().orElse(Values.createObject());+ } else {+ throw new IllegalArgumentException("Only Attributes of type ArrayValue or ObjectValue are allowed for RuleActionUpdateAttribute");+ }+ }+ }++ if (valueType == null || currentValue == null) {+ Asset asset = assetStorageService.find(new AssetQuery().select(new BaseAssetQuery.Select(BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES)).id(id).attributeName(attributeUpdateAction.attributeName));+ if (asset != null) {+ valueType = asset.getAttribute(attributeUpdateAction.attributeName).flatMap(Attribute::getType).get().getValueType();+ if (valueType.equals(ValueType.ARRAY)) {+ currentValue = asset.getAttribute(attributeUpdateAction.attributeName).flatMap(AbstractValueHolder::getValueAsArray).orElse(Values.createArray());+ } else if (valueType.equals(ValueType.OBJECT)) {+ currentValue = asset.getAttribute(attributeUpdateAction.attributeName).flatMap(AbstractValueHolder::getValueAsObject).orElse(Values.createObject());+ } else {+ throw new IllegalArgumentException("Only Attributes of type ArrayValue or ObjectValue are allowed for RuleActionUpdateAttribute");+ }+ }+ }++ if (valueType != null && currentValue != null) {++ switch (attributeUpdateAction.updateAction) {+ case ADD:+ if (valueType.equals(ValueType.ARRAY)) {+ ((ArrayValue) currentValue).add(attributeUpdateAction.value);+ } else {+ ((ObjectValue) currentValue).put(attributeUpdateAction.key, attributeUpdateAction.value);+ }+ break;+ case ADD_OR_REPLACE:+ case REPLACE:+ if (valueType.equals(ValueType.ARRAY)) {+ ((ArrayValue) currentValue).set(attributeUpdateAction.index, attributeUpdateAction.value);+ } else {+ ((ObjectValue) currentValue).put(attributeUpdateAction.key, attributeUpdateAction.value);+ }+ break;+ case DELETE:+ if (valueType.equals(ValueType.ARRAY)) {+ ((ArrayValue) currentValue).remove(attributeUpdateAction.index);+ } else {+ ((ObjectValue) currentValue).remove(attributeUpdateAction.key);+ }+ break;+ case CLEAR:+ if (valueType.equals(ValueType.ARRAY)) {+ currentValue = Values.createArray();+ } else {+ currentValue = Values.createObject();+ }+ break;+ }+ assetsFacade.dispatch(id, attributeUpdateAction.attributeName, currentValue);+ }+ });+ }+ }}if (action != null) {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 b41b67967..deed3aa18 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,7 +24,10 @@ import org.openremote.agent.protocol.simulator.SimulatorProtocol;import org.openremote.container.Container;import org.openremote.manager.security.UserConfiguration;import org.openremote.manager.setup.AbstractManagerSetup;-import org.openremote.model.asset.*;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.AssetAttribute;+import org.openremote.model.asset.AssetMeta;+import org.openremote.model.asset.UserAsset;import org.openremote.model.attribute.*;import org.openremote.model.geo.GeoJSONPoint;import org.openremote.model.rules.AssetRuleset;@@ -51,7 +54,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {// Update these numbers whenever you change a RULE_STATE flag in test datapublic static final int DEMO_RULE_STATES_APARTMENT_1 = 44;- public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;+ public static final int DEMO_RULE_STATES_APARTMENT_2 = 13;public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;public static final int DEMO_RULE_STATES_SMART_OFFICE = 1;public static final int DEMO_RULE_STATES_SMART_BUILDING = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;@@ -663,6 +666,16 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new AssetAttribute("windowOpen", AttributeValueType.BOOLEAN, Values.create(false)).setMeta(new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true))+ ),+ new AssetAttribute("lightSwitchTriggerTimes", ARRAY, Values.createArray().add(Values.create("1800")).add(Values.create("0830")))+ .setMeta(+ new MetaItem(LABEL, Values.create("Lightswitch Trigger Times")),+ new MetaItem(RULE_STATE, Values.create(true))+ ),+ new AssetAttribute("plantsWaterLevels", OBJECT, Values.createObject().put("cactus", 0.8))+ .setMeta(+ new MetaItem(LABEL, Values.create("Water levels of the plants")),+ new MetaItem(RULE_STATE, Values.create(true))));apartment2Livingroom = assetStorageService.merge(apartment2Livingroom);diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java b/model/src/main/java/org/openremote/model/rules/json/RuleAction.javaindex 99261ef0d..b042e5899 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleAction.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleAction.java@@ -25,7 +25,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo;@JsonSubTypes({@JsonSubTypes.Type(value = RuleActionWait.class, name = "wait"),@JsonSubTypes.Type(value = RuleActionWriteAttribute.class, name = "write-attribute"),- @JsonSubTypes.Type(value = RuleActionNotification.class, name = "notification")+ @JsonSubTypes.Type(value = RuleActionNotification.class, name = "notification"),+ @JsonSubTypes.Type(value = RuleActionUpdateAttribute.class, name = "update-attribute")})@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleActionUpdateAttribute.java b/model/src/main/java/org/openremote/model/rules/json/RuleActionUpdateAttribute.javanew file mode 100644index 000000000..d2348f8b2--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/json/RuleActionUpdateAttribute.java@@ -0,0 +1,38 @@+/*+ * 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.json;++import org.openremote.model.value.Value;++public class RuleActionUpdateAttribute extends RuleActionWithTarget {+ public String attributeName;+ public Value value;+ public String key;+ public Integer index;+ public UpdateAction updateAction;++ public enum UpdateAction {+ ADD,+ ADD_OR_REPLACE,+ REPLACE,+ DELETE,+ CLEAR+ }+}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovyindex dcb50fb00..3882537a3 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy@@ -92,6 +92,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {conditions.eventually {def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()+ assert livingroomAsset.getAttribute("lightSwitchTriggerTimes").get().valueAsArray.get().length() == 2+ assert livingroomAsset.getAttribute("plantsWaterLevels").get().valueAsObject.get().getNumber("cactus").get() == 0.8def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)assert bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()}@@ -173,6 +175,8 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {conditions.eventually {def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)assert !livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()+ assert livingroomAsset.getAttribute("lightSwitchTriggerTimes").get().valueAsArray.get().length() == 3+ assert livingroomAsset.getAttribute("plantsWaterLevels").get().valueAsObject.get().getNumber("cactus").get() == 0.7def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)assert !bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()}diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.jsonindex a13e3c167..af2893337 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json@@ -62,6 +62,45 @@},"attributeName": "lightSwitch","value": false+ },+ {+ "action": "update-attribute",+ "target": {+ "assets": {+ "parent": {+ "type": "urn:openremote:asset:residence",+ "name": "Apartment 2"+ },+ "type": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "urn:openremote:asset:room"+ }+ }+ },+ "attributeName": "lightSwitchTriggerTimes",+ "value": "2100",+ "updateAction": "ADD"+ },+ {+ "action": "update-attribute",+ "target": {+ "assets": {+ "parent": {+ "type": "urn:openremote:asset:residence",+ "name": "Apartment 2"+ },+ "type": {+ "predicateType": "string",+ "match": "EXACT",+ "value": "urn:openremote:asset:room"+ }+ }+ },+ "attributeName": "plantsWaterLevels",+ "key": "cactus",+ "value": 0.7,+ "updateAction": "REPLACE"}],"reset": {