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
Improved attribute value constraints and rules templates
Christian Bauere9a3ce6a6536
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.javaindex e9f7290c8..520e58a21 100644--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesEngine.java@@ -50,7 +50,6 @@ import org.openremote.manager.server.asset.ServerAsset;import org.openremote.manager.server.concurrent.ManagerExecutorService;import org.openremote.manager.server.notification.NotificationService;import org.openremote.manager.server.security.ManagerIdentityService;-import org.openremote.model.AbstractValueHolder;import org.openremote.model.asset.*;import org.openremote.model.rules.AssetRuleset;import org.openremote.model.rules.GlobalRuleset;@@ -60,7 +59,6 @@ import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.notification.AlertNotification;import org.openremote.model.rules.Assets;import org.openremote.model.rules.Users;-import org.openremote.model.rules.template.AssetStateConstraints;import org.openremote.model.rules.template.TemplateFilter;import org.openremote.model.user.UserQuery;import org.openremote.model.util.Pair;@@ -255,6 +253,7 @@ public class RulesEngine<T extends Ruleset> {for (Message error : errors) {LOG.severe(error.getText());}+ LOG.fine(drl);// If compilation failed, remove rules from FileSystem so it won't fail on next pass here if anykfs.delete("src/main/resources/" + ruleset.getId());} else {@@ -769,22 +768,24 @@ public class RulesEngine<T extends Ruleset> {}protected String compileTemplate(String templateAssetId, String rules) {- ServerAsset asset = assetStorageService.find(templateAssetId, true);+ ServerAsset templateAsset = assetStorageService.find(templateAssetId, true);- if (asset == null)+ if (templateAsset == null)throw new IllegalStateException("Template asset not found: " + templateAssetId);List<TemplateFilter> filters = new ArrayList<>();- asset.getAttributesStream()+ templateAsset.getAttributesStream().filter(AssetAttribute::isRuleStateTemplateFilter).map(attribute -> new Pair<>(attribute.getName(), attribute.getValue())).filter(pair -> pair.key.isPresent() && pair.value.isPresent()).map(pair -> new Pair<>(pair.key.get(), pair.value.get()))- .map(pair -> AssetStateConstraints.fromValue(pair.key, pair.value))+ .map(pair -> TemplateFilter.fromModelValue(pair.key, pair.value)).filter(Optional::isPresent).forEach(filter -> filters.add(filter.get()));+ LOG.fine("Rendering rules template with filters: " + filters);+ObjectDataCompiler converter = new ObjectDataCompiler();InputStream is = new ByteArrayInputStream(rules.getBytes(StandardCharsets.UTF_8));return converter.compile(filters, is);diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.javaindex dd72ba6b3..941acdaae 100644--- a/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/builtin/ManagerDemoSetup.java@@ -32,9 +32,9 @@ import org.openremote.model.asset.AssetAttribute;import org.openremote.model.asset.AssetState;import org.openremote.model.asset.AssetType;import org.openremote.model.attribute.*;-import org.openremote.model.rules.template.AssetStateConstraints;-import org.openremote.model.rules.template.AttributeValueConstraint;-import org.openremote.model.rules.template.ValueComparator;+import org.openremote.model.rules.template.TemplateFilter;+import org.openremote.model.rules.template.AttributeValueConstraintPattern;+import org.openremote.model.value.ValueComparator;import org.openremote.model.value.Values;import java.time.LocalDateTime;@@ -47,7 +47,6 @@ import static org.openremote.model.asset.AssetMeta.*;import static org.openremote.model.asset.AssetType.*;import static org.openremote.model.asset.agent.ProtocolConfiguration.initProtocolConfiguration;import static org.openremote.model.attribute.AttributeType.*;-import static org.openremote.model.value.ValueType.OBJECT;public class ManagerDemoSetup extends AbstractManagerSetup {@@ -643,13 +642,15 @@ public class ManagerDemoSetup extends AbstractManagerSetup {new AssetAttribute("originSwitzerland",TEMPLATE_FILTER,- new AssetStateConstraints(+ new TemplateFilter("originSwitzerland",- new AttributeValueConstraint("originCountry", ValueComparator.EQUALS, Values.create("Switzerland"), true)- ).toObjectValue()+ new AttributeValueConstraintPattern(+ "originCountry", new AttributeValueConstraint(ValueComparator.EQUALS_IGNORE_CASE, Values.create("switzerland"))+ )+ ).toModelValue()).setMeta(new MetaItem(LABEL, Values.create("Origin Switzerland")),- new MetaItem(RULE_STATE_TEMPLATE_FILTER, Values.create(true))+ new MetaItem(RULE_TEMPLATE_FILTER, Values.create(true))));flightPriorityFilters = assetStorageService.merge(flightPriorityFilters);diff --git a/manager/server/src/main/resources/demo/rules/flight/DemoFlightPriorityFilter.drlt b/manager/server/src/main/resources/demo/rules/flight/DemoFlightPriorityFilter.drltindex 7dc2f9e3a..14b16d66b 100644--- a/manager/server/src/main/resources/demo/rules/flight/DemoFlightPriorityFilter.drlt+++ b/manager/server/src/main/resources/demo/rules/flight/DemoFlightPriorityFilter.drlt@@ -1,6 +1,6 @@template header-filterId-assetStateConstraints+filterName+assetStatePatternspackage org.openremote.test.rules.flight;@@ -13,14 +13,14 @@ global org.openremote.model.rules.Assets assets;template "FlightPriorityFilter"-rule "Set priority for flights matching filter @{filterId}"+rule "Set priority for flights matching filter @{filterName}"when- // Flights which are not priority (the $assetState binding is used in the constraints later)+ // Flights which are not priority (the $assetState binding is used in the filter patterns later)$assetState: AssetState(type == AssetType.FLIGHT, attributeName == "priority", valueAsBoolean != true)- // And match any of the filter constraints- @{assetStateConstraints}+ // And match any of the filter patterns+ @{assetStatePatterns}then// Set the flight prioritydiff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.javaindex d6a61d00e..1425207ab 100644--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java@@ -323,7 +323,7 @@ public class AssetAttribute extends Attribute {public boolean isRuleStateTemplateFilter() {return getMetaStream()- .filter(isMetaNameEqualTo(RULE_STATE_TEMPLATE_FILTER))+ .filter(isMetaNameEqualTo(RULE_TEMPLATE_FILTER)).findFirst().map(metaItem -> metaItem.getValueAsBoolean().orElse(false)).orElse(false);diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.javaindex 1989f0801..9aaaabe57 100644--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java@@ -24,7 +24,7 @@ import org.openremote.model.ValidationFailure;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.attribute.MetaItem;import org.openremote.model.rules.Ruleset;-import org.openremote.model.rules.template.AssetStateConstraints;+import org.openremote.model.rules.template.TemplateFilter;import org.openremote.model.util.Pair;import org.openremote.model.value.Value;import org.openremote.model.value.ValueType;@@ -151,11 +151,12 @@ public enum AssetMeta implements HasUniqueResourceName {/*** When {@link Ruleset#templateAssetId} references an asset, use the attribute to customize the template when- * the ruleset is deployed. The attribute name is available in the template as <code>filterId</code>, the- * attribute value is converted into {@link AssetStateConstraints} and available in the template as- * {@link AssetStateConstraints#TEMPLATE_PARAM_NAME}.+ * the ruleset is deployed. The attribute name is available in the template as parameter {@link+ * TemplateFilter#TEMPLATE_PARAM_FILTER_NAME}, the attribute value is converted into {@link TemplateFilter} and+ * available in the template as {@link TemplateFilter#TEMPLATE_PARAM_ASSET_STATE} and+ * {@link TemplateFilter#TEMPLATE_PARAM_ASSET_EVENT}.*/- RULE_STATE_TEMPLATE_FILTER(ASSET_META_NAMESPACE + ":ruleStateTemplateFilter", new Access(true, false, true), ValueType.BOOLEAN),+ RULE_TEMPLATE_FILTER(ASSET_META_NAMESPACE + ":ruleTemplateFilter", new Access(true, false, true), ValueType.BOOLEAN),/*** Enable flag to be used by asset attributes that could require this functionality (e.g. {@link org.openremote.model.asset.agent.ProtocolConfiguration})diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValueConstraint.java b/model/src/main/java/org/openremote/model/attribute/AttributeValueConstraint.javanew file mode 100644index 000000000..9e3bc812d--- /dev/null+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValueConstraint.java@@ -0,0 +1,96 @@+/*+ * 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.attribute;++import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.ValueComparator;+import org.openremote.model.value.Values;++import java.util.Objects;+import java.util.Optional;+import java.util.function.Supplier;++/**+ * Simple binary value comparison operation.+ */+public class AttributeValueConstraint {++ final protected ValueComparator valueComparator;+ final protected Value value;++ public AttributeValueConstraint(ValueComparator valueComparator, Value value) throws IllegalArgumentException {+ Objects.requireNonNull(valueComparator);+ Objects.requireNonNull(value);+ this.valueComparator = valueComparator;+ this.value = value;+ if (!valueComparator.isApplicable(value.getType())) {+ throw new IllegalArgumentException("Comparator " + valueComparator + " can not be applied on: " + value);+ }+ }++ public ValueComparator getValueComparator() {+ return valueComparator;+ }++ public Value getValue() {+ return value;+ }++ public boolean apply(Attribute attribute, Supplier<Boolean> emptyDefault) {+ return attribute.getValue()+ .map(v -> getValueComparator().apply(v, getValue()))+ .orElseGet(emptyDefault);+ }++ public boolean apply(Value v) {+ return getValueComparator().apply(v, getValue());+ }++ public String renderRulesTemplatePattern() {+ return getValueComparator().renderRulesTemplatePattern(getValue());+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "valueComparator=" + valueComparator ++ ", value=" + value ++ '}';+ }++ public ObjectValue toModelValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("valueComparator", valueComparator.name());+ objectValue.put("value", value);+ return objectValue;+ }++ public static Optional<AttributeValueConstraint> fromModelValue(Value value) {+ return Values.getObject(value)+ .filter(v -> v.getString("valueComparator").isPresent())+ .filter(v -> v.getString("value").isPresent())+ .flatMap(objectValue -> objectValue+ .getString("valueComparator")+ .flatMap(ValueComparator::fromString)+ .map(comparator -> new AttributeValueConstraint(comparator, objectValue.get("value").get()))+ );+ }+}diff --git a/model/src/main/java/org/openremote/model/rules/template/AssetStateConstraints.java b/model/src/main/java/org/openremote/model/rules/template/AssetStateConstraints.javadeleted file mode 100644index b99181d15..000000000--- a/model/src/main/java/org/openremote/model/rules/template/AssetStateConstraints.java+++ /dev/null@@ -1,104 +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.rules.template;--import org.openremote.model.value.ArrayValue;-import org.openremote.model.value.ObjectValue;-import org.openremote.model.value.Value;-import org.openremote.model.value.Values;--import java.util.ArrayList;-import java.util.List;-import java.util.Optional;--public class AssetStateConstraints extends TemplateFilter {-- public static final String TEMPLATE_PARAM_NAME = "assetStateConstraints";-- final protected Constraint[] constraints;-- public AssetStateConstraints(String filterId, Constraint... constraints) {- super(filterId);- this.constraints = constraints;- }-- public String getAssetStateConstraints() {- StringBuilder sb = new StringBuilder();- for (Constraint constraint : constraints) {- sb.append("AssetState(id == $assetState.id, ");- sb.append(constraint.render());- sb.append(")").append("\n");- }- return sb.toString();- }-- public ObjectValue toObjectValue() {- ObjectValue objectValue = Values.createObject();- ArrayValue constraintsArray = Values.createArray();- objectValue.put("assetStateConstraints", constraintsArray);- for (Constraint constraint : constraints) {- constraintsArray.add(constraint.toObjectValue());- }- return objectValue;- }-- public static boolean isAssetStateConstraints(Value value) {- return Values.getObject(value)- .flatMap(objectValue -> objectValue.getArray("assetStateConstraints"))- .isPresent();- }-- public static Optional<AssetStateConstraints> fromValue(String filterId, Value value) {- return Values.getObject(value)- .filter(AssetStateConstraints::isAssetStateConstraints)- .flatMap(objectValue -> objectValue.getArray("assetStateConstraints"))- .map(arrayValue -> {- List<Constraint> constraints = new ArrayList<>();- for (int i = 0; i < arrayValue.length(); i++) {-- arrayValue.getObject(i)- .flatMap(AttributeValueConstraint::fromValue)- .ifPresent(constraints::add);-- }- return new AssetStateConstraints(filterId, constraints.toArray(new Constraint[constraints.size()]));- });- }-/*-- public static void main(String[] args) throws Exception {- AssetStateConstraints constraints = new AssetStateConstraints(- new AttributeValueConstraint("foo", ValueComparator.EQUALS, Values.create("foo123"), true)- );-- System.out.println(constraints);-- String json = constraints.toObjectValue().toJson();-- System.err.println(json);-- constraints = Values.parse(json).flatMap(AssetStateConstraints::fromValue).get();-- System.out.println(constraints);--- }-*/-}diff --git a/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraint.java b/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraint.javadeleted file mode 100644index a7f231d9f..000000000--- a/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraint.java+++ /dev/null@@ -1,81 +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.rules.template;--import org.openremote.model.value.ObjectValue;-import org.openremote.model.value.Value;-import org.openremote.model.value.Values;--import java.util.Objects;-import java.util.Optional;--public class AttributeValueConstraint implements Constraint {-- final protected String attributeName;- final protected ValueComparator valueComparator;- final protected Value value;- final protected boolean caseSensitive;-- public AttributeValueConstraint(String attributeName, ValueComparator valueComparator, Value value, boolean caseSensitive) throws IllegalStateException {- Objects.requireNonNull(attributeName);- Objects.requireNonNull(valueComparator);- Objects.requireNonNull(value);- this.attributeName = attributeName;- this.valueComparator = valueComparator;- this.value = value;- this.caseSensitive = caseSensitive;- if (!valueComparator.isValid(value)) {- throw new IllegalArgumentException("Invalid value for comparator " + valueComparator + ": " + value);- }- }-- @Override- public ObjectValue toObjectValue() {- ObjectValue objectValue = Values.createObject();- objectValue.put("type", "attribute-value");- objectValue.put("attributeName", attributeName);- objectValue.put("valueComparator", valueComparator.name());- objectValue.put("caseSensitive", caseSensitive);- objectValue.put("value", value);- return objectValue;- }-- public static Optional<AttributeValueConstraint> fromValue(Value value) {- return Values.getObject(value)- .filter(v -> v.getString("type").filter(s -> s.equals("attribute-value")).map(s -> true).orElse(false))- .flatMap(objectValue -> {- String attributeName =- objectValue.getString("attributeName").orElse(null);- ValueComparator valueComparator =- objectValue.getString("valueComparator").map(ValueComparator::fromString).orElse(null);- boolean caseSensitive = objectValue.getBoolean("caseSensitive").orElse(false);- Value v = objectValue.get("value").orElse(null);- return attributeName != null && valueComparator != null && v != null- ? Optional.of(new AttributeValueConstraint(attributeName, valueComparator, v, caseSensitive))- : Optional.empty();- });- }-- @Override- public String render() {- return "attributeName == \"" + attributeName + "\"" +- ", " + valueComparator.render(value, caseSensitive);- }-}diff --git a/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraintPattern.java b/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraintPattern.javanew file mode 100644index 000000000..6f1d9d137--- /dev/null+++ b/model/src/main/java/org/openremote/model/rules/template/AttributeValueConstraintPattern.java@@ -0,0 +1,88 @@+/*+ * 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.template;++import org.openremote.model.attribute.AttributeValueConstraint;+import org.openremote.model.util.Pair;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Objects;+import java.util.Optional;++public class AttributeValueConstraintPattern implements TemplatePattern {++ public static final String TYPE = "attribute-value-constraint";++ final protected String attributeName;+ final protected AttributeValueConstraint restriction;++ public AttributeValueConstraintPattern(String attributeName, AttributeValueConstraint restriction) {+ Objects.requireNonNull(attributeName);+ Objects.requireNonNull(restriction);+ this.attributeName = attributeName;+ this.restriction = restriction;+ }++ public String getAttributeName() {+ return attributeName;+ }++ public AttributeValueConstraint getRestriction() {+ return restriction;+ }++ @Override+ public String render() {+ return "attributeName == \"" + getAttributeName() + "\"" ++ ", " + getRestriction().renderRulesTemplatePattern();+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "attributeName='" + attributeName + '\'' ++ ", restriction=" + restriction ++ '}';+ }++ @Override+ public ObjectValue toModelValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("type", TYPE);+ objectValue.put("attributeName", attributeName);+ objectValue.put("restriction", restriction.toModelValue());+ return objectValue;+ }++ public static Optional<AttributeValueConstraintPattern> fromModelValue(Value value) {+ return Values.getObject(value)+ .filter(v -> v.getString("type").filter(s -> s.equals(TYPE)).map(s -> true).orElse(false))+ .flatMap(objectValue -> objectValue+ .getString("attributeName")+ .map(attributeName -> new Pair<>(+ attributeName, objectValue.getObject("restriction").flatMap(AttributeValueConstraint::fromModelValue))+ )+ .filter(pair -> pair.value.isPresent())+ .map(pair -> new AttributeValueConstraintPattern(pair.key, pair.value.get()))+ );+ }+}diff --git a/model/src/main/java/org/openremote/model/rules/template/TemplateFilter.java b/model/src/main/java/org/openremote/model/rules/template/TemplateFilter.javaindex c402a14d1..032f074e5 100644--- a/model/src/main/java/org/openremote/model/rules/template/TemplateFilter.java+++ b/model/src/main/java/org/openremote/model/rules/template/TemplateFilter.java@@ -19,15 +19,88 @@*/package org.openremote.model.rules.template;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.Value;+import org.openremote.model.value.Values;++import java.util.Arrays;+import java.util.Optional;+import java.util.stream.Stream;+public class TemplateFilter {- final protected String filterId;+ public static final String TEMPLATE_PARAM_FILTER_NAME = "filterName";+ public static final String TEMPLATE_PARAM_ASSET_STATE = "assetStatePatterns";+ public static final String TEMPLATE_PARAM_ASSET_EVENT = "assetEventPatterns";++ final protected String filterName;+ final protected TemplatePattern[] patterns;++ public TemplateFilter(String filterName, TemplatePattern... patterns) {+ this.filterName = filterName;+ this.patterns = patterns;+ }++ /**+ * Renders {@link #TEMPLATE_PARAM_FILTER_NAME}+ */+ public String getFilterName() {+ return filterName;+ }++ /**+ * Renders {@link #TEMPLATE_PARAM_ASSET_STATE}, uses LHS rule binding <code>$assetState</code>.+ */+ public String getAssetStatePatterns() {+ StringBuilder sb = new StringBuilder();+ for (TemplatePattern templatePattern : patterns) {+ sb.append("AssetState(id == $assetState.id, ");+ sb.append(templatePattern.render());+ sb.append(")").append("\n");+ }+ return sb.toString();+ }++ /**+ * Renders {@link #TEMPLATE_PARAM_ASSET_EVENT}, uses LHS rule binding <code>$assetEvent</code>.+ */+ public String getAssetEventPatterns() {+ StringBuilder sb = new StringBuilder();+ for (TemplatePattern templatePattern : patterns) {+ sb.append("AssetEvent(id == $assetEvent.id, ");+ sb.append(templatePattern.render());+ sb.append(")").append("\n");+ }+ return sb.toString();+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "filterName='" + filterName + '\'' ++ ", patterns=" + Arrays.toString(patterns) ++ '}';+ }- public TemplateFilter(String filterId) {- this.filterId = filterId;+ public Value toModelValue() {+ return Values.createArray().addAll(+ Arrays.stream(patterns)+ .map(TemplatePattern::toModelValue)+ .toArray(Value[]::new)+ );}- public String getFilterId() {- return filterId;+ public static Optional<TemplateFilter> fromModelValue(String filterId, Value value) {+ TemplatePattern[] templatePatterns =+ Values.getArray(value)+ .map(ArrayValue::stream)+ .orElse(Stream.empty())+ .map(AttributeValueConstraintPattern::fromModelValue)+ .filter(Optional::isPresent)+ .map(Optional::get)+ .toArray(TemplatePattern[]::new);+ return templatePatterns.length > 0+ ? Optional.of(new TemplateFilter(filterId, templatePatterns))+ : Optional.empty();}}diff --git a/model/src/main/java/org/openremote/model/rules/template/Constraint.java b/model/src/main/java/org/openremote/model/rules/template/TemplatePattern.javasimilarity index 88%rename from model/src/main/java/org/openremote/model/rules/template/Constraint.javarename to model/src/main/java/org/openremote/model/rules/template/TemplatePattern.javaindex 01714ef52..4aeae545c 100644--- a/model/src/main/java/org/openremote/model/rules/template/Constraint.java+++ b/model/src/main/java/org/openremote/model/rules/template/TemplatePattern.java@@ -19,11 +19,11 @@*/package org.openremote.model.rules.template;-import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Value;-public interface Constraint {+public interface TemplatePattern {- ObjectValue toObjectValue();+ Value toModelValue();String render();}diff --git a/model/src/main/java/org/openremote/model/rules/template/ValueComparator.java b/model/src/main/java/org/openremote/model/rules/template/ValueComparator.javadeleted file mode 100644index 4a9ee994c..000000000--- a/model/src/main/java/org/openremote/model/rules/template/ValueComparator.java+++ /dev/null@@ -1,141 +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.rules.template;--import org.openremote.model.value.Value;-import org.openremote.model.value.ValueType;-import org.openremote.model.value.Values;--import java.util.Locale;-import java.util.Objects;-import java.util.function.BiFunction;--public enum ValueComparator {-- EQUALS((value, caseSensitive) -> {- switch (value.getType()) {- case STRING:- return caseSensitive- ? "valueAsString == \"" + escapeString(Values.getString(value).get()) + "\""- : "(valueAsString.equalsIgnoreCase(\"" + escapeString(Values.getString(value).get()) + "\")";- case NUMBER:- return "valueAsNumber != " + Values.getNumber(value).get();- default:- return "";- }- },- ValueType.STRING, ValueType.NUMBER),- NOT_EQUALS((value, caseSensitive) -> {- switch (value.getType()) {- case STRING:- return caseSensitive- ? "valueAsString != \"" + escapeString(Values.getString(value).get()) + "\""- : "!(valueAsString.equalsIgnoreCase(\"" + escapeString(Values.getString(value).get()) + "\")";- case NUMBER:- return "valueAsNumber != " + Values.getNumber(value).get();- default:- return "";- }- }, ValueType.STRING, ValueType.NUMBER),- IS_TRUE((value, caseSensitive) -> {- switch (value.getType()) {- case BOOLEAN:- return "valueAsBoolean == true";- default:- return "";- }- }, ValueType.BOOLEAN),- IS_FALSE((value, caseSensitive) -> {- switch (value.getType()) {- case BOOLEAN:- return "valueAsBoolean == false";- default:- return "";- }- }, ValueType.BOOLEAN),- GREATER_THAN((value, caseSensitive) -> {- switch (value.getType()) {- case NUMBER:- return "valueAsNumber > " + Values.getNumber(value).get();- default:- return "";- }- }, ValueType.NUMBER),- LESS_THAN((value, caseSensitive) -> {- switch (value.getType()) {- case NUMBER:- return "valueAsNumber < " + Values.getNumber(value).get();- default:- return "";- }- }, ValueType.NUMBER),- GREATER_EQUAL_THAN((value, caseSensitive) -> {- switch (value.getType()) {- case NUMBER:- return "valueAsNumber >= " + Values.getNumber(value).get();- default:- return "";- }- }, ValueType.NUMBER),- LESS_EQUAL_THAN((value, caseSensitive) -> {- switch (value.getType()) {- case NUMBER:- return "valueAsNumber <= " + Values.getNumber(value).get();- default:- return "";- }- }, ValueType.NUMBER);-- final protected ValueType[] applicableTypes;- final protected BiFunction<Value, Boolean, String> renderFunction;-- ValueComparator(BiFunction<Value, Boolean, String> renderFunction, ValueType... applicableTypes) {- this.applicableTypes = applicableTypes;- this.renderFunction = renderFunction;- }-- protected boolean isApplicableType(ValueType valueType) {- for (ValueType applicableType : applicableTypes) {- if (applicableType == valueType)- return true;- }- return false;- }-- static protected String escapeString(String value) {- // Escape double quotes, remove control chars- return value.replaceAll("\"", "\\\\\"").replaceAll("\\p{Cc}", "");- }-- public boolean isValid(Value operand) {- Objects.requireNonNull(operand);- return isApplicableType(operand.getType());- }-- public String render(Value operand, boolean caseSensitive) {- Objects.requireNonNull(operand);- return renderFunction.apply(operand, caseSensitive);- }-- public static ValueComparator fromString(String value) {- return value == null ? null : valueOf(value.toUpperCase(Locale.ROOT));- }--}diff --git a/model/src/main/java/org/openremote/model/value/ArrayValue.java b/model/src/main/java/org/openremote/model/value/ArrayValue.javaindex 82764ee1c..be96527cb 100644--- a/model/src/main/java/org/openremote/model/value/ArrayValue.java+++ b/model/src/main/java/org/openremote/model/value/ArrayValue.java@@ -16,6 +16,7 @@package org.openremote.model.value;import java.util.Optional;+import java.util.stream.Stream;public interface ArrayValue extends Value {@@ -31,8 +32,12 @@ public interface ArrayValue extends Value {Optional<ObjectValue> getObject(int index);+ Stream<Value> stream();+int length();+ boolean isEmpty();+ArrayValue remove(int index);ArrayValue set(int index, Value value);diff --git a/model/src/main/java/org/openremote/model/value/ValueComparator.java b/model/src/main/java/org/openremote/model/value/ValueComparator.javanew file mode 100644index 000000000..92581563f--- /dev/null+++ b/model/src/main/java/org/openremote/model/value/ValueComparator.java@@ -0,0 +1,153 @@+/*+ * 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.value;++import java.util.Locale;+import java.util.Objects;+import java.util.Optional;+import java.util.function.BiFunction;+import java.util.function.Function;++/**+ * Binary operators.+ */+public enum ValueComparator implements BiFunction<Value, Value, Boolean> {++ EQUALS(applyEquals(false, false), renderEquals(false, false), ValueType.STRING, ValueType.NUMBER, ValueType.BOOLEAN),++ NOT_EQUALS(applyEquals(false, true), renderEquals(false, true), ValueType.STRING, ValueType.NUMBER, ValueType.BOOLEAN),++ EQUALS_IGNORE_CASE(applyEquals(true, false), renderEquals(true, false), ValueType.STRING, ValueType.NUMBER, ValueType.BOOLEAN),++ NOT_EQUALS_IGNORE_CASE(applyEquals(true, true), renderEquals(true, true), ValueType.STRING, ValueType.NUMBER, ValueType.BOOLEAN),++ GREATER_THAN(applyNumberComparison((a, b) -> a > b), renderNumberComparison(">"), ValueType.NUMBER),++ GREATER_EQUAL_THAN(applyNumberComparison((a, b) -> a >= b), renderNumberComparison(">="), ValueType.NUMBER),++ LESS_THAN(applyNumberComparison((a, b) -> a < b), renderNumberComparison("<"), ValueType.NUMBER),++ LESS_EQUAL_THAN(applyNumberComparison((a, b) -> a <= b), renderNumberComparison("<="), ValueType.NUMBER);++ final protected ValueType[] applicableTypes;+ final protected BiFunction<Value, Value, Boolean> operation;+ final protected Function<Value, String> templateRenderer;++ ValueComparator(+ BiFunction<Value, Value, Boolean> operation,+ Function<Value, String> templateRenderer,+ ValueType... applicableTypes) {+ this.applicableTypes = applicableTypes;+ this.operation = operation;+ this.templateRenderer = templateRenderer;+ }++ static protected String escapeString(String value) {+ // Escape double quotes, remove control chars+ return value.replaceAll("\"", "\\\\\"").replaceAll("\\p{Cc}", "");+ }++ static protected BiFunction<Value, Value, Boolean> applyEquals(boolean ignoreCase, boolean negate) {+ return (a, b) -> {+ switch (a.getType()) {+ case STRING:+ String s1 = Values.getString(a).orElseThrow(() -> new ValueException("Not a string: " + a));+ String s2 = Values.getString(b).orElseThrow(() -> new ValueException("Not a string: " + b));+ return negate != ignoreCase ? s1.toLowerCase(Locale.ROOT).equals(s2.toLowerCase(Locale.ROOT)) : s1.equals(s2);+ case NUMBER:+ Double n1 = Values.getNumber(a).orElseThrow(() -> new ValueException("Not a number: " + a));+ Double n2 = Values.getNumber(b).orElseThrow(() -> new ValueException("Not a number: " + b));+ return negate != n1.equals(n2);+ case BOOLEAN:+ Boolean b1 = Values.getBoolean(a).orElseThrow(() -> new ValueException("Not a boolean: " + a));+ Boolean b2 = Values.getBoolean(b).orElseThrow(() -> new ValueException("Not a boolean: " + b));+ return negate != b1.equals(b2);+ default:+ return false;+ }+ };+ }++ static protected BiFunction<Value, Value, Boolean> applyNumberComparison(BiFunction<Double, Double, Boolean> comparator) {+ return (a, b) -> {+ Double n1 = Values.getNumber(a).orElseThrow(() -> new ValueException("Not a number: " + a));+ Double n2 = Values.getNumber(b).orElseThrow(() -> new ValueException("Not a number: " + b));+ return comparator.apply(n1, n2);+ };+ }++ static protected Function<Value, String> renderEquals(boolean ignoreCase, boolean negate) {+ return value -> {+ switch (value.getType()) {+ case STRING:+ String s = Values.getString(value).orElseThrow(() -> new ValueException("Not a string: " + value));+ return ignoreCase+ ? (negate ? "!" : "") + "(\"" + escapeString(Values.getString(value).get()) + "\".equalsIgnoreCase(valueAsString))"+ : "valueAsString " + (negate ? "!=" : "==") + " \"" + escapeString(s) + "\"";+ case NUMBER:+ Double n = Values.getNumber(value).orElseThrow(() -> new ValueException("Not a number: " + value));+ return "valueAsNumber " + (negate ? "!=" : "==") + " " + n;+ case BOOLEAN:+ Boolean b = Values.getBoolean(value).orElseThrow(() -> new ValueException("Not a boolean: " + value));+ return "valueAsBoolean " + (negate ? "!=" : "==") + " " + b;+ default:+ return "";+ }+ };+ }++ static protected Function<Value, String> renderNumberComparison(String operator) {+ return value -> {+ switch (value.getType()) {+ case NUMBER:+ return "valueAsNumber " + operator + " " + Values.getNumber(value).get();+ default:+ return "";+ }+ };+ }++ @Override+ public Boolean apply(Value value, Value value2) {+ return operation.apply(value, value2);+ }++ public boolean isApplicable(ValueType valueType) {+ for (ValueType applicableType : applicableTypes) {+ if (applicableType == valueType)+ return true;+ }+ return false;+ }++ public String renderRulesTemplatePattern(Value value) {+ Objects.requireNonNull(value);+ return templateRenderer.apply(value);+ }++ public static Optional<ValueComparator> fromString(String value) {+ try {+ return Optional.of(valueOf(value.toUpperCase(Locale.ROOT)));+ } catch (IllegalArgumentException ex) {+ return Optional.empty();+ }+ }++}diff --git a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.javaindex ded8b6679..76aa01ec4 100644--- a/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java+++ b/model/src/main/java/org/openremote/model/value/impl/ArrayValueImpl.java@@ -19,6 +19,7 @@ import org.openremote.model.value.*;import java.util.ArrayList;import java.util.Optional;+import java.util.stream.Stream;public class ArrayValueImpl extends ValueImpl implements ArrayValue {@@ -69,6 +70,11 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {.map(value -> ((ObjectValue) value));}+ @Override+ public Stream<Value> stream() {+ return values.stream();+ }+@Overridepublic ValueType getType() {return ValueType.ARRAY;@@ -79,6 +85,11 @@ public class ArrayValueImpl extends ValueImpl implements ArrayValue {return values.size();}+ @Override+ public boolean isEmpty() {+ return values.isEmpty();+ }+@Overridepublic ArrayValue remove(int index) {values.remove(index);