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
JSON Rules cleanup (improve code reuse and ensure location predicates can be tracked using existing mechanism)
Rich Turner2b799bf2c969
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.javaindex 6673091ae..8db843f1f 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java@@ -83,7 +83,6 @@ import static org.openremote.model.query.BaseAssetQuery.Access.PRIVATE_READ;import static org.openremote.model.query.BaseAssetQuery.Access.RESTRICTED_READ;import static org.openremote.model.query.BaseAssetQuery.Include.ALL;import static org.openremote.model.query.BaseAssetQuery.Include.ALL_EXCEPT_PATH_AND_ATTRIBUTES;-import static org.openremote.model.query.filter.LocationAttributePredicate.getLocationPredicate;import static org.openremote.model.util.TextUtil.isNullOrEmpty;public class AssetStorageService extends RouteBuilder implements ContainerService {diff --git a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.javaindex 2ce35f197..1d0e62814 100644--- a/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java+++ b/manager/src/main/java/org/openremote/manager/rules/AssetQueryPredicate.java@@ -23,14 +23,17 @@ import com.vividsolutions.jts.geom.Coordinate;import com.vividsolutions.jts.geom.Envelope;import org.geotools.referencing.GeodeticCalculator;import org.openremote.container.timer.TimerService;-import org.openremote.model.attribute.AttributeType;+import org.openremote.manager.asset.AssetStorageService;import org.openremote.model.attribute.Meta;import org.openremote.model.attribute.MetaItem;import org.openremote.model.geo.GeoJSONPoint;import org.openremote.model.query.BaseAssetQuery;import org.openremote.model.query.BaseAssetQuery.NumberType;+import org.openremote.model.query.NewAssetQuery;import org.openremote.model.query.filter.*;import org.openremote.model.rules.AssetState;+import org.openremote.model.rules.json.RuleCondition;+import org.openremote.model.rules.json.RuleOperator;import org.openremote.model.util.Pair;import org.openremote.model.util.TimeUtil;import org.openremote.model.value.Value;@@ -38,11 +41,10 @@ import org.openremote.model.value.Values;import java.text.ParseException;import java.text.SimpleDateFormat;-import java.util.Arrays;-import java.util.Locale;-import java.util.Optional;+import java.util.*;import java.util.function.Predicate;import java.util.function.Supplier;+import java.util.stream.Collectors;import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_EQUALS;import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_THAN;@@ -52,60 +54,91 @@ import static org.openremote.model.query.BaseAssetQuery.Operator.LESS_THAN;*/public class AssetQueryPredicate implements Predicate<AssetState> {- final protected BaseAssetQuery query;+ final protected NewAssetQuery query;final protected TimerService timerService;+ final protected AssetStorageService assetStorageService;- public AssetQueryPredicate(TimerService timerService, BaseAssetQuery query) {+ // TODO: Remove this ctor once asset queries merged+ public AssetQueryPredicate(TimerService timerService, AssetStorageService assetStorageService, BaseAssetQuery query) {this.timerService = timerService;+ this.assetStorageService = assetStorageService;+ this.query = new NewAssetQuery();+ this.query.ids = query.ids != null ? (String[])query.ids.toArray(new String[query.ids.size()]) : null;+ this.query.names = query.name != null ? new StringPredicate[] {query.name} : null;+ this.query.parents = query.parent != null ? new ParentPredicate[] {query.parent} : null;+ this.query.paths = query.path != null ? new PathPredicate[] {query.path} : null;+ this.query.attributes = query.attribute != null ? new RuleCondition<>(RuleOperator.AND, query.attribute, null) : null;+ this.query.types = query.type != null ? new StringPredicate[] {query.type} : null;+ this.query.userIds = query.userId != null ? new String[] {query.userId} : null;+ this.query.tenant = query.tenant;+ this.query.orderBy = query.orderBy;+ this.query.limit = query.limit;+ }++ public AssetQueryPredicate(TimerService timerService, AssetStorageService assetStorageService, NewAssetQuery query) {+ this.timerService = timerService;+ this.assetStorageService = assetStorageService;this.query = query;}@Overridepublic boolean test(AssetState assetState) {- if (query.ids != null && !query.ids.contains(assetState.getId()))- return false;-- if (query.name != null && !asPredicate(query.name).test(assetState.getName()))- return false;-- if (query.parent != null && !asPredicate(query.parent).test(assetState))- return false;+ if (query.ids != null && query.ids.length > 0) {+ if (Arrays.stream(query.ids).noneMatch(id -> assetState.getId().equals(id))) {+ return false;+ }+ }- if (query.path != null && !asPredicate(query.path).test(assetState.getPath()))- return false;+ if (query.names != null && query.names.length > 0) {+ if (Arrays.stream(query.names)+ .map(AssetQueryPredicate::asPredicate)+ .noneMatch(np -> np.test(assetState.getName()))) {+ return false;+ }+ }- if (query.tenant != null && !asPredicate(query.tenant).test(assetState))- return false;+ if (query.parents != null && query.parents.length > 0) {+ if (Arrays.stream(query.parents)+ .map(AssetQueryPredicate::asPredicate)+ .noneMatch(np -> np.test(assetState))) {+ return false;+ }+ }- if (query.userId != null) {- // TODO Would require linked user IDs in AbstractAssetUpdate- throw new UnsupportedOperationException("Restriction by user ID not implemented in rules matching");+ if (query.types != null && query.types.length > 0) {+ if (Arrays.stream(query.types)+ .map(AssetQueryPredicate::asPredicate)+ .noneMatch(np -> np.test(assetState.getTypeString()))) {+ return false;+ }}- if (query.type != null && !asPredicate(query.type).test(assetState.getTypeString()))- return false;- if (query.attribute != null) {- for (AttributePredicate p : query.attribute) {- if (!asPredicate(timerService::getCurrentTimeMillis, p).test(assetState))- return false;+ if (query.paths != null && query.paths.length > 0) {+ if (Arrays.stream(query.paths)+ .map(AssetQueryPredicate::asPredicate)+ .noneMatch(np -> np.test(assetState.getPath()))) {+ return false;}}- if (query.attributeMeta != null) {- for (AttributeMetaPredicate p : query.attributeMeta) {- if (!asPredicate(timerService::getCurrentTimeMillis, p).test(assetState.getMeta())) {- return false;- }+ if (query.tenant != null) {+ if (!AssetQueryPredicate.asPredicate(query.tenant).test(assetState)) {+ return false;}}- if (query.select != null) {- throw new UnsupportedOperationException("Projection with 'select' not supported in rules matching");+ if (query.attributes != null) {+ if (!asPredicate(timerService::getCurrentTimeMillis, query.attributes).test(assetState)) {+ return false;+ }}- if (query.orderBy != null) {- throw new UnsupportedOperationException("Sorting with 'orderBy' not supported in rules matching");+ // Apply user ID predicate last as it is the most expensive+ if (query.userIds != null && query.userIds.length > 0) {+ if (!assetStorageService.isUserAsset(Arrays.asList(query.userIds), assetState.getId())) {+ return false;+ }}return true;@@ -283,12 +316,49 @@ public class AssetQueryPredicate implements Predicate<AssetState> {}public static Predicate<AssetState> asPredicate(Supplier<Long> currentMillisProducer, AttributePredicate predicate) {- return assetState -> {- if (predicate.name != null && !asPredicate(predicate.name).test(assetState.getAttributeName()))- return false;- return asPredicate(currentMillisProducer, predicate.value).test(assetState.getValue().orElse(null));+ Predicate<String> namePredicate = predicate.name != null+ ? asPredicate(predicate.name) : str -> true;++ Predicate<Value> valuePredicate = value -> {+ if (predicate.value == null) {+ return true;+ }+ return asPredicate(currentMillisProducer, predicate.value).test(value);};++ return assetState -> namePredicate.test(assetState.getAttributeName())+ && valuePredicate.test(assetState.getValue().orElse(null));+ }++ public static Predicate<AssetState> asPredicate(Supplier<Long> currentMillisProducer, NewAttributePredicate predicate) {++ Predicate<AssetState> attributePredicate = asPredicate(currentMillisProducer, (AttributePredicate)predicate);++ Predicate<Meta> metaPredicate = meta -> {++ if (predicate.meta == null || predicate.meta.length == 0) {+ return true;+ }++ for (AttributeMetaPredicate p : predicate.meta) {+ if (!AssetQueryPredicate.asPredicate(currentMillisProducer, p).test(meta)) {+ return false;+ }+ }+ return true;+ };++ Predicate<Value> oldValuePredicate = value -> {+ if (predicate.lastValue == null) {+ return true;+ }+ return AssetQueryPredicate.asPredicate(currentMillisProducer, predicate.lastValue).test(value);+ };++ return assetState -> attributePredicate.test(assetState)+ && metaPredicate.test(assetState.getMeta())+ && oldValuePredicate.test(assetState.getOldValue().orElse(null));}public static Predicate<Value> asPredicate(Supplier<Long> currentMillisProducer, ValuePredicate predicate) {@@ -357,6 +427,94 @@ public class AssetQueryPredicate implements Predicate<AssetState> {return meta -> meta.stream().anyMatch(metaItemPredicate);}+ public static Predicate<RulesFacts> asPredicate(TimerService timerService, AssetStorageService assetStorageService, RuleCondition<NewAssetQuery> condition) {++ if ((condition.predicates == null || condition.predicates.length == 0)+ && (condition.conditions == null || condition.conditions.length == 0)) {+ return facts -> true;+ }++ RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;++ List<Predicate<RulesFacts>> assetPredicates = new ArrayList<>();++ if (condition.predicates != null && condition.predicates.length > 0) {+ assetPredicates.addAll(+ Arrays.stream(condition.predicates)+ .map(p ->+ (Predicate<RulesFacts>) facts ->+ facts.matchAssetState(p).findFirst().isPresent())+ .collect(Collectors.toList())+ );+ }++ if (condition.conditions != null && condition.conditions.length > 0) {+ assetPredicates.addAll(+ Arrays.stream(condition.conditions)+ .map(c -> asPredicate(timerService, assetStorageService, c)).collect(Collectors.toList())+ );+ }++ return asPredicate(assetPredicates, operator);+ }++ public static Predicate<AssetState> asPredicate(Supplier<Long> currentMillisProducer, RuleCondition<AttributePredicate> condition) {+ if ((condition.predicates == null || condition.predicates.length == 0)+ && (condition.conditions == null || condition.conditions.length == 0)) {+ return as -> true;+ }++ RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;++ List<Predicate<AssetState>> assetStatePredicates = new ArrayList<>();++ if (condition.predicates != null && condition.predicates.length > 0) {+ assetStatePredicates.addAll(+ Arrays.stream(condition.predicates)+ .map(p -> {+ if (p instanceof NewAttributePredicate) {+ return asPredicate(currentMillisProducer, (NewAttributePredicate)p);+ }+ return asPredicate(currentMillisProducer, p);+ }).collect(Collectors.toList())+ );+ }++ if (condition.conditions != null && condition.conditions.length > 0) {+ assetStatePredicates.addAll(+ Arrays.stream(condition.conditions)+ .map(c -> asPredicate(currentMillisProducer, c)).collect(Collectors.toList())+ );+ }++ return asPredicate(assetStatePredicates, operator);+ }++ protected static <T> Predicate<T> asPredicate(List<Predicate<T>> predicates, RuleOperator operator) {+ return in -> {+ boolean matched = false;++ for (Predicate<T> p : predicates) {++ if (p.test(in)) {+ matched = true;++ if (operator == RuleOperator.OR) {+ break;+ }+ } else {+ matched = false;++ if (operator == RuleOperator.AND) {+ break;+ }+ }+ }++ return matched;+ };+ }+public static Pair<Long, Long> asFromAndTo(long currentMillis, DateTimePredicate dateTimePredicate) {Long from;diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex 35f20d742..a9d897cb0 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -25,21 +25,25 @@ import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.rules.facade.NotificationsFacade;import org.openremote.model.attribute.Meta;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.rules.json.predicate.AssetPredicate;-import org.openremote.model.rules.json.predicate.AttributePredicate;import org.openremote.model.util.TextUtil;import org.openremote.model.value.Value;import java.util.*;-import java.util.function.*;+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;public class JsonRulesBuilder extends RulesBuilder {@@ -84,233 +88,6 @@ public class JsonRulesBuilder extends RulesBuilder {this.scheduledActionConsumer = scheduledActionConsumer;}- protected static Predicate<RulesFacts> asPredicate(TimerService timerService, AssetStorageService assetStorageService, RuleCondition<AssetPredicate> condition) {-- if ((condition.predicates == null || condition.predicates.length == 0)- && (condition.conditions == null || condition.conditions.length == 0)) {- return facts -> true;- }-- RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;-- List<Predicate<RulesFacts>> assetPredicates = new ArrayList<>();-- if (condition.predicates != null && condition.predicates.length > 0) {- assetPredicates.addAll(- Arrays.stream(condition.predicates)- .map(p -> {- Predicate<AssetState> assetStatePredicate = asPredicate(timerService, assetStorageService, p);- return (Predicate<RulesFacts>) facts -> {- List<AssetState> assetStates = new ArrayList<>(facts.getAssetStates());- assetStates.removeIf(as -> assetStatePredicate.negate().test(as));- return !assetStates.isEmpty();- };- }).collect(Collectors.toList())- );- }-- if (condition.conditions != null && condition.conditions.length > 0) {- assetPredicates.addAll(- Arrays.stream(condition.conditions)- .map(c -> asPredicate(timerService, assetStorageService, c)).collect(Collectors.toList())- );- }-- return asPredicate(assetPredicates, operator);- }-- protected static Predicate<AssetState> asPredicate(Supplier<Long> currentMillisProducer, RuleCondition<AttributePredicate> condition) {- if ((condition.predicates == null || condition.predicates.length == 0)- && (condition.conditions == null || condition.conditions.length == 0)) {- return as -> true;- }-- RuleOperator operator = condition.operator == null ? RuleOperator.AND : condition.operator;-- List<Predicate<AssetState>> assetStatePredicates = new ArrayList<>();-- if (condition.predicates != null && condition.predicates.length > 0) {- assetStatePredicates.addAll(- Arrays.stream(condition.predicates)- .map(p -> asPredicate(currentMillisProducer, p)).collect(Collectors.toList())- );- }-- if (condition.conditions != null && condition.conditions.length > 0) {- assetStatePredicates.addAll(- Arrays.stream(condition.conditions)- .map(c -> asPredicate(currentMillisProducer, c)).collect(Collectors.toList())- );- }-- return asPredicate(assetStatePredicates, operator);- }-- public static Predicate<AssetState> asPredicate(TimerService timerService, AssetStorageService assetStorageService, AssetPredicate pred) {-- return assetState -> {- if (pred.ids != null && pred.ids.length > 0) {- if (Arrays.stream(pred.ids).noneMatch(id -> assetState.getId().equals(id))) {- return false;- }- }-- if (pred.names != null && pred.names.length > 0) {- if (Arrays.stream(pred.names)- .map(AssetQueryPredicate::asPredicate)- .noneMatch(np -> np.test(assetState.getName()))) {- return false;- }- }-- if (pred.parents != null && pred.parents.length > 0) {- if (Arrays.stream(pred.parents)- .map(AssetQueryPredicate::asPredicate)- .noneMatch(np -> np.test(assetState))) {- return false;- }- }-- if (pred.types != null && pred.types.length > 0) {- if (Arrays.stream(pred.types)- .map(AssetQueryPredicate::asPredicate)- .noneMatch(np -> np.test(assetState.getTypeString()))) {- return false;- }- }-- if (pred.paths != null && pred.paths.length > 0) {- if (Arrays.stream(pred.paths)- .map(AssetQueryPredicate::asPredicate)- .noneMatch(np -> np.test(assetState.getPath()))) {- return false;- }- }-- if (pred.tenant != null) {- if (!AssetQueryPredicate.asPredicate(pred.tenant).test(assetState)) {- return false;- }- }-- if (pred.attributes != null) {- if (!asPredicate(timerService::getCurrentTimeMillis, pred.attributes).test(assetState)) {- return false;- }- }-- // Apply user ID predicate last as it is the most expensive- if (pred.userIds != null && pred.userIds.length > 0) {- if (!assetStorageService.isUserAsset(Arrays.asList(pred.userIds), assetState.getId())) {- return false;- }- }-- return true;- };- }-- public static Predicate<AssetState> asPredicate(Supplier<Long> currentMillsProducer, AttributePredicate pred) {-- Predicate<String> namePredicate = pred.name != null- ? AssetQueryPredicate.asPredicate(pred.name) : str -> true;-- Predicate<Meta> metaPredicate = meta -> {-- if (pred.meta == null || pred.meta.length == 0) {- return true;- }-- for (AttributeMetaPredicate p : pred.meta) {- if (!AssetQueryPredicate.asPredicate(currentMillsProducer, p).test(meta)) {- return false;- }- }- return true;- };-- Predicate<Value> valuePredicate = value -> {- if (pred.value == null) {- return true;- }- return AssetQueryPredicate.asPredicate(currentMillsProducer, pred.value).test(value);- };-- Predicate<Value> oldValuePredicate = value -> {- if (pred.lastValue == null) {- return true;- }- return AssetQueryPredicate.asPredicate(currentMillsProducer, pred.lastValue).test(value);- };-- return assetState -> namePredicate.test(assetState.getAttributeName())- && metaPredicate.test(assetState.getMeta())- && valuePredicate.test(assetState.getValue().orElse(null))- && oldValuePredicate.test(assetState.getOldValue().orElse(null));- }-- public static Comparator<AssetState> asComparator(AssetPredicate.MatchOrder matchOrder) {-- Function<AssetState, String> keyExtractor = AssetState::getName;- boolean reverse = false;-- switch (matchOrder) {- case NAME_REVERSED:- reverse = true;- case NAME:- keyExtractor = AssetState::getName;- break;- case ATTRIBUTE_REVERSE:- reverse = true;- case ATTRIBUTE:- keyExtractor = AssetState::getAttributeName;- break;- case NAME_AND_ATTRIBUTE_REVERSED:- reverse = true;- case NAME_AND_ATTRIBUTE:- keyExtractor = as -> as.getName() + as.getAttributeName();- break;- case ATTRIBUTE_AND_NAME_REVERSED:- reverse = true;- case ATTRIBUTE_AND_NAME:- keyExtractor = as -> as.getAttributeName() + as.getName();- break;- }-- Comparator<AssetState> comparator = Comparator.comparing(keyExtractor);-- if (reverse) {- comparator = comparator.reversed();- }-- return comparator;- }-- protected static <T> Predicate<T> asPredicate(List<Predicate<T>> predicates, RuleOperator operator) {- return in -> {- boolean matched = false;-- for (Predicate<T> p : predicates) {-- if (p.test(in)) {- matched = true;-- if (operator == RuleOperator.OR) {- break;- }- } else {- matched = false;-- if (operator == RuleOperator.AND) {- break;- }- }- }-- return matched;- };- }-protected static String buildResetFactName(Rule rule, AssetState assetState) {return rule.name + "_" + assetState.getId() + "_" + assetState.getAttributeName();}@@ -324,7 +101,7 @@ public class JsonRulesBuilder extends RulesBuilder {.getResults();}- protected static List<String> getAssetIds(Assets assets, AssetQuery assetQuery) {+ protected static List<String> getAssetIds(Assets assets, org.openremote.model.query.AssetQuery assetQuery) {return assets.query().ids(assetQuery.ids).name(assetQuery.name)@@ -339,10 +116,7 @@ public class JsonRulesBuilder extends RulesBuilder {public JsonRulesBuilder add(Rule rule) {- final Predicate<AssetState> assetStatePredicate = rule.when != null && rule.when.asset != null- ? asPredicate(timerService, assetStorageService, rule.when.asset) : null;-- Condition condition = buildLhsCondition(rule, assetStatePredicate);+ Condition condition = buildLhsCondition(rule);Action action = buildAction(rule);if (condition == null || action == null) {@@ -367,7 +141,7 @@ public class JsonRulesBuilder extends RulesBuilder {}).then(action);- Condition resetCondition = buildResetCondition(rule, assetStatePredicate);+ Condition resetCondition = buildResetCondition(rule);Action resetAction = buildResetAction();if (resetCondition != null && resetAction != null) {@@ -393,7 +167,7 @@ public class JsonRulesBuilder extends RulesBuilder {return this;}- protected Condition buildLhsCondition(Rule rule, Predicate<AssetState> assetStatePredicate) {+ protected Condition buildLhsCondition(Rule rule) {if (rule.when == null || (rule.when.asset == null && rule.when.timer == null)) {return facts -> false;}@@ -402,42 +176,35 @@ public class JsonRulesBuilder extends RulesBuilder {Predicate<RulesFacts> andPredicate = facts -> true;if (rule.when.asset != null) {-+ // Pull out order and limit so they can be applied after filtering already triggered asset states+ BaseAssetQuery.OrderBy orderBy = rule.when.asset.orderBy;+ int limit = rule.when.asset.limit;+ rule.when.asset.orderBy = null;+ rule.when.asset.limit = 0;whenPredicate = facts -> {- List<AssetState> assetStates = new ArrayList<>(facts.getAssetStates());-- assetStates.removeIf(as -> assetStatePredicate.negate().test(as));-- if (assetStates.isEmpty()) {- return false;- }+ Stream<AssetState> assetStates = facts.matchAssetState(rule.when.asset);// Apply reset predicate (to prevent re-running a rule on an asset state before the reset has triggered)- assetStates.removeIf(as -> {+ assetStates = assetStates.filter(as -> {String factName = buildResetFactName(rule, as);- return facts.getOptional(factName).isPresent();+ return !facts.getOptional(factName).isPresent();});- if (assetStates.isEmpty()) {- return false;- }- if (rule.when.asset.matchOrder != null) {- assetStates.sort(asComparator(rule.when.asset.matchOrder));+ if (orderBy != null) {+ assetStates = assetStates.sorted(RulesFacts.asComparator(rule.when.asset.orderBy));}- if (rule.when.asset.matchLimit > 0) {- int limit = Math.min(assetStates.size(), rule.when.asset.matchLimit);- assetStates = assetStates.subList(0, limit);+ if (limit > 0) {+ assetStates = assetStates.limit(limit);}- // Push matched asset states into RHS- facts.bind("assetStates", assetStates);+ List<AssetState> assetStateList = assetStates.collect(Collectors.toList());- if (!assetStates.isEmpty()) {+ if (!assetStateList.isEmpty()) {// Push matched asset states into RHS- facts.bind("assetStates", assetStates);+ facts.bind("assetStates", assetStateList);return true;}@@ -448,10 +215,9 @@ public class JsonRulesBuilder extends RulesBuilder {}if (rule.and != null) {- andPredicate = asPredicate(timerService, assetStorageService, rule.and);+ andPredicate = AssetQueryPredicate.asPredicate(timerService, assetStorageService, rule.and);}-Predicate<RulesFacts> finalWhenPredicate = whenPredicate;Predicate<RulesFacts> finalAndPredicate = andPredicate;@@ -550,7 +316,7 @@ public class JsonRulesBuilder extends RulesBuilder {List<String> finalIds = ids;action = () ->finalIds.forEach(id ->- assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value));+ assetsFacade.dispatch(id, attributeAction.attributeName, attributeAction.value));}}} else if (ruleAction instanceof RuleActionWait) {@@ -572,12 +338,11 @@ public class JsonRulesBuilder extends RulesBuilder {};}- protected Condition buildResetCondition(Rule rule, Predicate<AssetState> assetStatePredicate) {+ protected Condition buildResetCondition(Rule rule) {// Timer only reset is handled in rule action with temporary fact other resets require rule.when.asset to be set// so that we have- if (rule.reset == null || assetStatePredicate == null- || (!rule.reset.triggerNoLongerMatches && !rule.reset.attributeTimestampChange+ if (rule.reset == null || (!rule.reset.triggerNoLongerMatches && !rule.reset.attributeTimestampChange&& !rule.reset.attributeValueChange)) {return null;@@ -589,8 +354,8 @@ public class JsonRulesBuilder extends RulesBuilder {BiPredicate<AssetState, RuleFiredInfo> attributeTimestampPredicate = (assetState, ruleFiredInfo) -> false;BiPredicate<AssetState, RuleFiredInfo> attributeValuePredicate = (assetState, ruleFiredInfo) -> false;- if (reset.triggerNoLongerMatches) {- noLongerMatchesPredicate = assetState -> assetStatePredicate.negate().test(assetState);+ if (reset.triggerNoLongerMatches && rule.when != null && rule.when.asset != null) {+ noLongerMatchesPredicate = new AssetQueryPredicate(timerService, assetStorageService, rule.when.asset).negate();}if (reset.attributeTimestampChange) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 3cc5f903a..b674fba71 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -125,7 +125,7 @@ public class RulesEngine<T extends Ruleset> {this.notificationFacade = new NotificationsFacade<>(id, notificationService);this.assetLocationPredicatesConsumer = assetLocationPredicatesConsumer;- this.facts = new RulesFacts(timerService, assetsFacade, this, RULES_LOG);+ this.facts = new RulesFacts(timerService, assetStorageService, assetsFacade, this, RULES_LOG);engine = new InferenceRulesEngine(// Skip any other rules after the first failed rule (exception thrown in condition or action)new RulesEngineParameters(false, true, false, RulesEngineParameters.DEFAULT_RULE_PRIORITY_THRESHOLD)diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex 2d5f6d5aa..bbeb8553e 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -23,22 +23,26 @@ import org.jeasy.rules.api.Facts;import org.jeasy.rules.api.Rule;import org.jeasy.rules.api.RuleListener;import org.openremote.container.timer.TimerService;+import org.openremote.manager.asset.AssetStorageService;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeExecuteStatus;import org.openremote.model.query.AssetQuery;import org.openremote.model.query.BaseAssetQuery;+import org.openremote.model.query.NewAssetQuery;import org.openremote.model.query.filter.AttributePredicate;import org.openremote.model.query.filter.GeofencePredicate;-import org.openremote.model.query.filter.LocationAttributePredicate;+import org.openremote.model.query.filter.NewAttributePredicate;import org.openremote.model.rules.AssetState;import org.openremote.model.rules.Assets;import org.openremote.model.rules.TemporaryFact;+import org.openremote.model.rules.json.RuleCondition;import org.openremote.model.util.TimeUtil;import org.openremote.model.value.Value;import org.openremote.model.value.Values;import java.time.Duration;import java.util.*;+import java.util.function.Function;import java.util.function.Predicate;import java.util.logging.Level;import java.util.logging.Logger;@@ -46,7 +50,7 @@ import java.util.stream.Collectors;import java.util.stream.Stream;import static org.openremote.model.attribute.AttributeType.LOCATION;-import static org.openremote.model.query.filter.LocationAttributePredicate.getLocationPredicate;+import static org.openremote.model.query.filter.LocationAttributePredicate.getLocationPredicates;public class RulesFacts extends Facts implements RuleListener {@@ -63,6 +67,7 @@ public class RulesFacts extends Facts implements RuleListener {public static final String ANONYMOUS_FACTS = "ANONYMOUS_FACTS";final protected TimerService timerService;+ final protected AssetStorageService assetStorageService;final protected Assets assetsFacade;final protected Object loggingContext;final protected Logger LOG;@@ -73,8 +78,9 @@ public class RulesFacts extends Facts implements RuleListener {protected boolean trackLocationRules;protected Map<String, Set<GeofencePredicate>> assetStateLocationPredicateMap = null;- public RulesFacts(TimerService timerService, Assets assetsFacade, Object loggingContext, Logger logger) {+ public RulesFacts(TimerService timerService, AssetStorageService assetStorageService, Assets assetsFacade, Object loggingContext, Logger logger) {this.timerService = timerService;+ this.assetStorageService = assetStorageService;this.assetsFacade = assetsFacade;this.loggingContext = loggingContext;this.LOG = logger;@@ -431,43 +437,29 @@ public class RulesFacts extends Facts implements RuleListener {return matchAssetState(assetQuery).findFirst();}- public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {-- if (trackLocationRules && assetQuery.attribute != null && assetQuery.attribute.length > 0) {+ public Stream<AssetState> matchAssetState(NewAssetQuery assetQuery) {+ if (trackLocationRules && assetQuery.attributes != null) {+ List<AttributePredicate> attributePredicates = RuleCondition.flatten(Collections.singletonList(assetQuery.attributes));+ storeLocationPredicates(getLocationPredicates(attributePredicates));+ }- GeofencePredicate locationPredicate = getLocationPredicate(Arrays.asList(assetQuery.attribute)).orElse(null);+ Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetStorageService, assetQuery);+ return matchAssetState(p);+ }- if (locationPredicate != null) {- LOG.fine("Location predicate found");- // Collect asset states only where the attribute is location (location predicates only make sense when the location- // attribute is exposed to rules - we don't support RULE_EVENT facts just RULE_STATE- if (assetStateLocationPredicateMap == null) {- Collection<AssetState> locationAssetStates = getAssetStates().stream().filter(assetState -> assetState.getAttributeName().equalsIgnoreCase(LOCATION.getName())).collect(Collectors.toSet());- assetStateLocationPredicateMap = new HashMap<>(locationAssetStates.size());- locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState.getId(), new HashSet<>()));- }+ public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {- assetStateLocationPredicateMap.forEach((assetState, locationPredicates) -> locationPredicates.add(locationPredicate));- }+ if (trackLocationRules && assetQuery.attribute != null && assetQuery.attribute.length > 0) {+ storeLocationPredicates(getLocationPredicates(Arrays.asList(assetQuery.attribute)));}- Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetQuery);+ Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetStorageService, assetQuery);+ return matchAssetState(p);+ }+ public Stream<AssetState> matchAssetState(Predicate<AssetState> p) {// Match against all asset states by defaultStream<AssetState> assetStates = getAssetStates().stream();-- // If the query is by asset ID, look up a smaller stream on asset ID index- Collection<AssetState> assetStatesForId;- if (assetQuery.ids != null && ((assetStatesForId = assetIdIndex.get(assetQuery.ids)) != null)) {- return assetStatesForId.stream().parallel().filter(p);- }-- // If the query is by asset type, look up a smaller stream on asset type index- Collection<AssetState> assetStatesForType;- if (assetQuery.type != null && ((assetStatesForType = assetTypeIndex.get(assetQuery.type.value)) != null)) {- return assetStatesForType.stream().parallel().filter(p);- }-return assetStates.parallel().filter(p);}@@ -480,7 +472,7 @@ public class RulesFacts extends Facts implements RuleListener {}public Stream<TemporaryFact<AssetState>> matchAssetEvent(AssetQuery assetQuery) {- Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetQuery);+ Predicate<AssetState> p = new AssetQueryPredicate(timerService, assetStorageService, assetQuery);return getAssetEvents().stream().parallel().filter(fact -> matchFact(fact, AssetState.class, p).isPresent());}@@ -509,37 +501,6 @@ public class RulesFacts extends Facts implements RuleListener {return updateAssetState(assetId, attributeName, status.asValue());}- protected RulesFacts invalidateAssetStateAndDispatch(String assetId, String attributeName, Value value) {- // Remove the asset state from the facts, it is invalid now- getAssetStates()- .removeIf(assetState -> {- boolean invalid = assetState.getId().equals(assetId) && assetState.getAttributeName().equals(attributeName);- if (invalid) {- if (LOG.isLoggable(Level.FINEST)) {- LOG.finest("Fact change (INTERNAL DELETE): " + assetState + " - on: " + loggingContext);- }- // Maintain index of all asset states for this asset by ID- Collection<AssetState> assetIdIndexCollection = assetIdIndex.get(assetState.getId());- if (assetIdIndexCollection != null) {- assetIdIndexCollection.remove(assetState);- }- // Maintain index of all asset states for this asset by type- Collection<AssetState> assetTypeIndexCollection = assetTypeIndex.get(assetState.getTypeString());- if (assetTypeIndexCollection != null) {- assetTypeIndexCollection.remove(assetState);- }- }- return invalid;- });-- // Dispatch the update to the asset processing service- AttributeEvent attributeEvent = new AttributeEvent(assetId, attributeName, value);- LOG.finest("Dispatching " + attributeEvent + " - on: " + loggingContext);- assetsFacade.dispatch(attributeEvent);-- return this;- }-public void removeExpiredTemporaryFacts() {long currentTimestamp = (long) getClock().getTimestamp();getAssetEvents().removeIf(fact -> {@@ -637,6 +598,83 @@ public class RulesFacts extends Facts implements RuleListener {return haveLog;}+ public static Comparator<AssetState> asComparator(BaseAssetQuery.OrderBy orderBy) {++ Function<AssetState, String> keyExtractor = AssetState::getName;+ boolean reverse = orderBy.descending;++ switch (orderBy.property) {++ case CREATED_ON:+ keyExtractor = assetState -> Long.toString(assetState.getCreatedOn().getTime());+ break;+ case ASSET_TYPE:+ keyExtractor = AssetState::getTypeString;+ break;+ case PARENT_ID:+ keyExtractor = AssetState::getParentId;+ break;+ case REALM_ID:+ keyExtractor = AssetState::getRealmId;+ break;+ }++ Comparator<AssetState> comparator = Comparator.comparing(keyExtractor);++ if (reverse) {+ comparator = comparator.reversed();+ }++ return comparator;+ }++ protected RulesFacts invalidateAssetStateAndDispatch(String assetId, String attributeName, Value value) {+ // Remove the asset state from the facts, it is invalid now+ getAssetStates()+ .removeIf(assetState -> {+ boolean invalid = assetState.getId().equals(assetId) && assetState.getAttributeName().equals(attributeName);+ if (invalid) {+ if (LOG.isLoggable(Level.FINEST)) {+ LOG.finest("Fact change (INTERNAL DELETE): " + assetState + " - on: " + loggingContext);+ }+ // Maintain index of all asset states for this asset by ID+ Collection<AssetState> assetIdIndexCollection = assetIdIndex.get(assetState.getId());+ if (assetIdIndexCollection != null) {+ assetIdIndexCollection.remove(assetState);+ }+ // Maintain index of all asset states for this asset by type+ Collection<AssetState> assetTypeIndexCollection = assetTypeIndex.get(assetState.getTypeString());+ if (assetTypeIndexCollection != null) {+ assetTypeIndexCollection.remove(assetState);+ }+ }+ return invalid;+ });++ // Dispatch the update to the asset processing service+ AttributeEvent attributeEvent = new AttributeEvent(assetId, attributeName, value);+ LOG.finest("Dispatching " + attributeEvent + " - on: " + loggingContext);+ assetsFacade.dispatch(attributeEvent);++ return this;+ }++ protected void storeLocationPredicates(List<GeofencePredicate> foundLocationPredicates) {++ if (foundLocationPredicates != null && !foundLocationPredicates.isEmpty()) {+ LOG.fine("Location predicate found");+ // Collect asset states only where the attribute is location (location predicates only make sense when the location+ // attribute is exposed to rules - we don't support RULE_EVENT facts just RULE_STATE+ if (assetStateLocationPredicateMap == null) {+ Collection<AssetState> locationAssetStates = getAssetStates().stream().filter(assetState -> assetState.getAttributeName().equalsIgnoreCase(LOCATION.getName())).collect(Collectors.toSet());+ assetStateLocationPredicateMap = new HashMap<>(locationAssetStates.size());+ locationAssetStates.forEach(assetState -> assetStateLocationPredicateMap.put(assetState.getId(), new HashSet<>()));+ }++ assetStateLocationPredicateMap.forEach((assetState, locationPredicates) -> locationPredicates.addAll(foundLocationPredicates));+ }+ }+protected void logRule(Rule rule, String msg, boolean logFacts, boolean logVars) {String ruleName = rule.getName();if (ruleName.startsWith("-") && LOG.isLoggable(Level.INFO)) {diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex d960de2e7..5bad4d8c4 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -120,7 +120,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseprotected ClientEventService clientEventService;protected RulesEngine<GlobalRuleset> globalEngine;protected String[] activeTenantIds;- protected BiConsumer<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> locationPredicateRulesConsumer;+ protected AssetLocationPredicateProcessor locationPredicateRulesConsumer;protected Map<RulesEngine, List<RulesEngine.AssetStateLocationPredicates>> engineAssetLocationPredicateMap = new HashMap<>();protected Set<String> assetsWithModifiedLocationPredicates = new HashSet<>();// Keep global list of asset states that have been pushed to any engines@@ -527,7 +527,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AssenotificationService,clientEventService,new RulesEngineId<>(),- this::onEngineLocationRulesChanged+ locationPredicateRulesConsumer);}@@ -565,7 +565,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AssenotificationService,clientEventService,new RulesEngineId<>(realmId),- this::onEngineLocationRulesChanged+ locationPredicateRulesConsumer);});@@ -633,7 +633,7 @@ public class RulesService extends RouteBuilder implements ContainerService, AssenotificationService,clientEventService,new RulesEngineId<>(ruleset.getRealmId(), assetId),- this::onEngineLocationRulesChanged+ locationPredicateRulesConsumer);});diff --git a/model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.java b/model/src/main/java/org/openremote/model/query/NewAssetQuery.javasimilarity index 70%rename from model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.javarename to model/src/main/java/org/openremote/model/query/NewAssetQuery.javaindex bdb92730a..9b3790a90 100644--- a/model/src/main/java/org/openremote/model/rules/json/predicate/AssetPredicate.java+++ b/model/src/main/java/org/openremote/model/query/NewAssetQuery.java@@ -17,12 +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.rules.json.predicate;+package org.openremote.model.query;-import org.openremote.model.query.filter.ParentPredicate;-import org.openremote.model.query.filter.PathPredicate;-import org.openremote.model.query.filter.StringPredicate;-import org.openremote.model.query.filter.TenantPredicate;+import org.openremote.model.query.filter.*;import org.openremote.model.rules.json.RuleCondition;/**@@ -32,24 +29,14 @@ import org.openremote.model.rules.json.RuleCondition;* <p>* The {@link org.openremote.model.asset.Asset}s associated with the returned {@link org.openremote.model.rules.AssetState}s* are then used as the context for any {@link org.openremote.model.rules.json.RuleTriggerReset} to control when the- * {@link AssetPredicate} is allowed to be applied again to the same asset. They can also optionally be used as context+ * {@link NewAssetQuery} is allowed to be applied again to the same asset. They can also optionally be used as context* in the {@link org.openremote.model.rules.json.RuleActionWithTarget.Target}, to apply an action to the matched* {@link org.openremote.model.asset.Asset}s.* <p>* There is an implicit AND between properties and an implicit OR between each value of a property.*/-public class AssetPredicate {-- public enum MatchOrder {- NAME,- NAME_REVERSED,- ATTRIBUTE,- ATTRIBUTE_REVERSE,- NAME_AND_ATTRIBUTE,- NAME_AND_ATTRIBUTE_REVERSED,- ATTRIBUTE_AND_NAME,- ATTRIBUTE_AND_NAME_REVERSED- }+// TODO: Merge with existing AssetQuery+public class NewAssetQuery {public String[] ids;public StringPredicate[] names;@@ -61,13 +48,13 @@ public class AssetPredicate {public RuleCondition<AttributePredicate> attributes;/**- * To be used in combination with {@link #matchLimit} to control the ordering of {@link org.openremote.model.rules.AssetState}s+ * To be used in combination with {@link #limit} to control the ordering of {@link org.openremote.model.rules.AssetState}s* before applying the limit.*/- public MatchOrder matchOrder;+ public BaseAssetQuery.OrderBy orderBy;/*** Means that only this number of matching {@link org.openremote.model.rules.AssetState} will be passed through as the context.*/- public int matchLimit;+ public int limit;}diff --git a/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.javaindex 0ce854217..8e3068ee4 100644--- a/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/LocationAttributePredicate.java@@ -23,7 +23,7 @@ import org.openremote.model.attribute.AttributeType;import org.openremote.model.query.BaseAssetQuery;import java.util.List;-import java.util.Optional;+import java.util.stream.Collectors;import static org.openremote.model.attribute.AttributeType.LOCATION;@@ -33,13 +33,13 @@ public class LocationAttributePredicate extends AttributePredicate {super(new StringPredicate(AttributeType.LOCATION.getName()), geofencePredicate);}- public static Optional<GeofencePredicate> getLocationPredicate(List<AttributePredicate> attributePredicates) {+ public static List<GeofencePredicate> getLocationPredicates(List<AttributePredicate> attributePredicates) {return attributePredicates.stream().filter(attributePredicate -> attributePredicate.name != null&& attributePredicate.name.match == BaseAssetQuery.Match.EXACT&& LOCATION.getName().equals(attributePredicate.name.value)&& attributePredicate.value instanceof GeofencePredicate)- .findFirst()- .map(attributePredicate -> (GeofencePredicate) attributePredicate.value);+ .map(attributePredicate -> (GeofencePredicate) attributePredicate.value)+ .collect(Collectors.toList());}}diff --git a/model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/NewAttributePredicate.javasimilarity index 90%rename from model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.javarename to model/src/main/java/org/openremote/model/query/filter/NewAttributePredicate.javaindex 304e1b16d..47ff70681 100644--- a/model/src/main/java/org/openremote/model/rules/json/predicate/AttributePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/NewAttributePredicate.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.rules.json.predicate;+package org.openremote.model.query.filter;import org.openremote.model.query.filter.AttributeMetaPredicate;import org.openremote.model.query.filter.DateTimePredicate;@@ -28,7 +28,7 @@ import org.openremote.model.query.filter.ValuePredicate;* There is an implicit AND condition between each value*/// TODO: Introduce value converter functionality and merge with existing AttributePredicate-public class AttributePredicate extends org.openremote.model.query.filter.AttributePredicate {+public class NewAttributePredicate extends org.openremote.model.query.filter.AttributePredicate {public AttributeMetaPredicate[] meta;public ValuePredicate lastValue;public DateTimePredicate valueTimestamp;diff --git a/model/src/main/java/org/openremote/model/rules/json/Rule.java b/model/src/main/java/org/openremote/model/rules/json/Rule.javaindex 1d7227123..47ece9ae3 100644--- a/model/src/main/java/org/openremote/model/rules/json/Rule.java+++ b/model/src/main/java/org/openremote/model/rules/json/Rule.java@@ -19,16 +19,16 @@*/package org.openremote.model.rules.json;-import org.openremote.model.rules.json.predicate.AssetPredicate;+import org.openremote.model.query.NewAssetQuery;/*** A declarative rule definition (a.k.a. JSON rules); consists of:* <p>* <h2>LHS</li>* <p>- * {@link #when}* - This can be either a {@link RuleTrigger#timer} for time based rules or an {@link AssetPredicate}+ * {@link #when}* - This can be either a {@link RuleTrigger#timer} for time based rules or an {@link NewAssetQuery}* which will be used to filter {@link org.openremote.model.rules.AssetState}s currently available in the rule engine- * that this rule is loaded into. The {@link AssetPredicate} will evaluate to true when one or more+ * that this rule is loaded into. The {@link NewAssetQuery} will evaluate to true when one or more* {@link org.openremote.model.rules.AssetState}s are returned by applying the filter. The returned* {@link org.openremote.model.rules.AssetState}s are then used as context for the RHS and also the* {@link RuleTriggerReset} (if specified).@@ -55,7 +55,7 @@ public class Rule {public String description;public int priority = Integer.MAX_VALUE-1;public RuleTrigger when;- public RuleCondition<AssetPredicate> and;+ public RuleCondition<NewAssetQuery> and;public RuleAction[] then;public RuleTriggerReset reset;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.javaindex e0a93cb3c..28142e639 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleCondition.java@@ -19,8 +19,21 @@*/package org.openremote.model.rules.json;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+public class RuleCondition<T> {+ public RuleCondition() {+ }++ public RuleCondition(RuleOperator operator, T[] predicates, RuleCondition<T>[] conditions) {+ this.operator = operator;+ this.predicates = predicates;+ this.conditions = conditions;+ }+/*** If not specified then {@link RuleOperator#AND} is assumed.*/@@ -35,4 +48,15 @@ public class RuleCondition<T> {* Nested conditions allow for more complex logic with a mix of operators*/public RuleCondition<T>[] conditions;++ public static <T> List<T> flatten(List<RuleCondition<T>> conditions) {+ List<T> flattened = new ArrayList<>();+ for (RuleCondition<T> ruleCondition : conditions) {+ flattened.addAll(Arrays.asList(ruleCondition.predicates));+ if (ruleCondition.conditions != null) {+ flattened.addAll(flatten(Arrays.asList(ruleCondition.conditions)));+ }+ }+ return flattened;+ }}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java b/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.javaindex fb053becb..ac53f2ca4 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleTrigger.java@@ -19,18 +19,18 @@*/package org.openremote.model.rules.json;-import org.openremote.model.rules.json.predicate.AssetPredicate;+import org.openremote.model.query.NewAssetQuery;/*** There are two types of trigger supported and only one should be specified if both are specified then {@link #asset}* trigger will be used.* <ul>- * <li>{@link #asset} see {@link AssetPredicate}</li>+ * <li>{@link #asset} see {@link NewAssetQuery}</li>* <li>{@link #timer} Allows timer expressions to be specified and thus creating a time based rule (e.g. "1h")</li>* </ul>*/public class RuleTrigger {- public AssetPredicate asset;+ public NewAssetQuery asset;public String timer;}diff --git a/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java b/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.javaindex aac35d46f..ae2a390b3 100644--- a/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java+++ b/model/src/main/java/org/openremote/model/rules/json/RuleTriggerReset.java@@ -19,6 +19,8 @@*/package org.openremote.model.rules.json;+import org.openremote.model.query.NewAssetQuery;+/*** This defines when an {@link org.openremote.model.rules.AssetState} becomes eligible for triggering the rule again once* if has triggered a rule.@@ -33,7 +35,7 @@ public class RuleTriggerReset {public String timer;/**- * When the {@link Rule#when} {@link org.openremote.model.rules.json.predicate.AssetPredicate} evaluates to true.+ * When the {@link Rule#when} {@link NewAssetQuery} evaluates to true.*/public boolean triggerNoLongerMatches;diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovyindex c36ce79b4..aec3cfd91 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy@@ -4,6 +4,7 @@ import groovy.transform.EqualsAndHashCodeimport groovy.transform.ToStringimport org.openremote.container.Containerimport org.openremote.container.timer.TimerService+import org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.rules.RulesClockimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesFacts@@ -51,8 +52,9 @@ class BasicRulesFactsTest extends Specification {given: "some rule facts"assetsFacade = Mock(Assets)def timerService = new TimerService()+ def assetStorageService = new AssetStorageService()timerService.clock = TimerService.Clock.PSEUDO- rulesFacts = new RulesFacts(timerService, assetsFacade, this, RulesEngine.RULES_LOG)+ rulesFacts = new RulesFacts(timerService, assetStorageService, assetsFacade, this, RulesEngine.RULES_LOG)and: "a rules clock"def rulesClock = new RulesClock(0)