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
Tests for rule execution errors, improved locking in AgentService
Christian Bauerf1d698bc4f6d
diff --git a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent/protocol/Protocol.javaindex 5f5ab4977..dff178a73 100644--- a/agent/src/main/java/org/openremote/agent/protocol/Protocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/Protocol.java@@ -112,7 +112,7 @@ import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;* Protocol configuration (logical instance) is modified:* <ol>* <li>{@link #unlinkAttributes}</li>- * <li>{@link #unlinkProtocolConfiguration)}</li>+ * <li>{@link #unlinkProtocolConfiguration}</li>* <li>{@link #linkProtocolConfiguration}</li>* <li>{@link #linkAttributes}</li>* </ol>diff --git a/manager/src/main/java/org/openremote/manager/agent/AgentService.java b/manager/src/main/java/org/openremote/manager/agent/AgentService.javaindex 9d5d5d3bc..3002026d4 100644--- a/manager/src/main/java/org/openremote/manager/agent/AgentService.java+++ b/manager/src/main/java/org/openremote/manager/agent/AgentService.java@@ -54,9 +54,7 @@ import java.util.stream.Stream;import static org.openremote.agent.protocol.Protocol.ACTUATOR_TOPIC;import static org.openremote.agent.protocol.Protocol.SENSOR_QUEUE;-import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;-import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForAssetType;-import static org.openremote.container.persistence.PersistenceEvent.isPersistenceEventForEntityType;+import static org.openremote.container.persistence.PersistenceEvent.*;import static org.openremote.manager.asset.AssetProcessingService.ASSET_QUEUE;import static org.openremote.model.AbstractValueTimestampHolder.VALUE_TIMESTAMP_FIELD_NAME;import static org.openremote.model.asset.AssetAttribute.attributesFromJson;@@ -146,20 +144,14 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse/// For all agents, go through their protocol configurations and find// assets that are linked to them, to create the binding on startupfor (Asset agent : agents) {- agent.getAttributesStream()+ linkProtocolConfigurations(agent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::linkProtocolConfiguration);+ );}}@Overridepublic void stop(Container container) throws Exception {- /* TODO Accessing the database while shutting down is not a good thing, it will hang if the JDBC pool is shutting down- synchronized (protocolConfigurations) {- new ArrayList<>(protocolConfigurations.values())- .forEach(protocolConfigAndConsumer -> unlinkProtocolConfiguration(protocolConfigAndConsumer.key));- }- */}@Override@@ -295,9 +287,9 @@ public class AgentService extends RouteBuilder implements ContainerService, Asseswitch (persistenceEvent.getCause()) {case INSERT:addReplaceAgent(agent);- agent.getAttributesStream()- .filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::linkProtocolConfiguration);+ linkProtocolConfigurations(+ agent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)+ );break;case UPDATE:@@ -328,31 +320,30 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse// Compare protocol configurations by JSON value// Unlink protocols that are in oldConfigs but not in newConfigs- oldProtocolConfigurations+ unlinkProtocolConfigurations(oldProtocolConfigurations.stream().filter(oldProtocolAttribute -> newProtocolConfigurations.stream()- .noneMatch(oldProtocolAttribute::equals- )+ .noneMatch(oldProtocolAttribute::equals))- .forEach(this::unlinkProtocolConfiguration);+ );// Link protocols that are in newConfigs but not in oldConfigs- newProtocolConfigurations+ linkProtocolConfigurations(newProtocolConfigurations.stream().filter(newProtocolAttribute -> oldProtocolConfigurations.stream()- .noneMatch(newProtocolAttribute::equals- )- ).forEach(this::linkProtocolConfiguration);+ .noneMatch(newProtocolAttribute::equals)+ )+ );break;case DELETE:removeAgent(agent);// Unlink any attributes that have an agent link to this agent- agent.getAttributesStream()+ unlinkProtocolConfigurations(agent.getAttributesStream().filter(ProtocolConfiguration::isProtocolConfiguration)- .forEach(this::unlinkProtocolConfiguration);+ );break;}}@@ -439,111 +430,111 @@ public class AgentService extends RouteBuilder implements ContainerService, Asse}}- protected void linkProtocolConfiguration(AssetAttribute protocolConfiguration) {- AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();- Protocol protocol = getProtocol(protocolConfiguration);-- if (protocol == null) {- LOG.warning("Cannot find protocol that attribute is linked to: " + protocolAttributeRef);- return;- }-+ protected void linkProtocolConfigurations(Stream<AssetAttribute> configurations) {synchronized (protocolConfigurations) {- // Create a consumer callback for deployment status updates- Consumer<ConnectionStatus> deploymentStatusConsumer = status ->- publishProtocolConnectionStatus(protocolAttributeRef, status);-- // Store the info- protocolConfigurations.put(- protocolAttributeRef,- new Pair<>(protocolConfiguration, null)- );+ configurations.forEach(configuration -> {+ AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();+ Protocol protocol = getProtocol(configuration);- // Set status to linking- publishProtocolConnectionStatus(protocolAttributeRef, CONNECTING);+ if (protocol == null) {+ LOG.warning("Cannot find protocol that attribute is linked to: " + protocolAttributeRef);+ return;+ }- // Link the protocol configuration to the protocol- try {- protocol.linkProtocolConfiguration(protocolConfiguration, deploymentStatusConsumer);- } catch (Exception e) {- LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration linking", e);- // Set status to error- publishProtocolConnectionStatus(protocolAttributeRef, ERROR_CONFIGURATION);- }+ // Create a consumer callback for deployment status updates+ Consumer<ConnectionStatus> deploymentStatusConsumer = status ->+ publishProtocolConnectionStatus(protocolAttributeRef, status);- // Check protocol status and only continue linking attributes if not in error state- ConnectionStatus connectionStatus = getProtocolConnectionStatus(protocolAttributeRef);- if (connectionStatus == ERROR_CONFIGURATION || connectionStatus == ERROR) {- LOG.warning("Protocol connection status is showing error so not linking attributes: "- + protocolConfiguration);- return;- }- }+ // Store the info+ protocolConfigurations.put(protocolAttributeRef, new Pair<>(configuration, null));- // Get all assets that have attributes that use this protocol configuration- List<ServerAsset> assets = assetStorageService.findAll(- new AssetQuery()- .select(new AssetQuery.Select(AssetQuery.Include.ALL))- .attributeMeta(- new AssetQuery.AttributeRefPredicate(- AssetMeta.AGENT_LINK,- protocolAttributeRef.getEntityId(),- protocolAttributeRef.getAttributeName()- )- )- );+ // Set status to linking+ publishProtocolConnectionStatus(protocolAttributeRef, CONNECTING);- assets.forEach(- asset ->- getGroupedAgentLinkAttributes(- asset.getAttributesStream(),- assetAttribute -> getAgentLink(assetAttribute)- .map(attributeRef -> attributeRef.equals(protocolAttributeRef))- .orElse(false),- attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)- ).forEach(this::linkAttributes)- );- }+ // Link the protocol configuration to the protocol+ try {+ protocol.linkProtocolConfiguration(configuration, deploymentStatusConsumer);+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration linking", e);+ // Set status to error+ publishProtocolConnectionStatus(protocolAttributeRef, ERROR_CONFIGURATION);+ }- protected void unlinkProtocolConfiguration(AssetAttribute protocolConfiguration) {- AttributeRef protocolAttributeRef = protocolConfiguration.getReferenceOrThrow();+ // Check protocol status and only continue linking attributes if not in error state+ ConnectionStatus connectionStatus = getProtocolConnectionStatus(protocolAttributeRef);+ if (connectionStatus == ERROR_CONFIGURATION || connectionStatus == ERROR) {+ LOG.warning("Protocol connection status is showing error so not linking attributes: " + configuration);+ return;+ }- // Get all assets that have attributes that use this protocol configuration- List<ServerAsset> assets = assetStorageService.findAll(- new AssetQuery()- .select(new AssetQuery.Select(AssetQuery.Include.ALL))- .attributeMeta(- new AssetQuery.AttributeRefPredicate(- AssetMeta.AGENT_LINK,- protocolAttributeRef.getEntityId(),- protocolAttributeRef.getAttributeName()- )- )- );+ // Get all assets that have attributes that use this protocol configuration+ List<ServerAsset> assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select(AssetQuery.Include.ALL))+ .attributeMeta(+ new AssetQuery.AttributeRefPredicate(+ AssetMeta.AGENT_LINK,+ protocolAttributeRef.getEntityId(),+ protocolAttributeRef.getAttributeName()+ )+ )+ );- assets.forEach(- asset ->- getGroupedAgentLinkAttributes(- asset.getAttributesStream(),- assetAttribute -> getAgentLink(assetAttribute)- .map(attributeRef -> attributeRef.equals(protocolAttributeRef))- .orElse(false)- ).forEach(this::unlinkAttributes)- );+ assets.forEach(+ asset ->+ getGroupedAgentLinkAttributes(+ asset.getAttributesStream(),+ assetAttribute -> getAgentLink(assetAttribute)+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))+ .orElse(false),+ attribute -> LOG.warning("Linked protocol configuration not found: " + attribute)+ ).forEach(this::linkAttributes)+ );+ });+ }+ }+ protected void unlinkProtocolConfigurations(Stream<AssetAttribute> configurations) {synchronized (protocolConfigurations) {- Protocol protocol = getProtocol(protocolConfiguration);+ configurations.forEach(configuration -> {+ AttributeRef protocolAttributeRef = configuration.getReferenceOrThrow();++ // Get all assets that have attributes that use this protocol configuration+ List<ServerAsset> assets = assetStorageService.findAll(+ new AssetQuery()+ .select(new AssetQuery.Select(AssetQuery.Include.ALL))+ .attributeMeta(+ new AssetQuery.AttributeRefPredicate(+ AssetMeta.AGENT_LINK,+ protocolAttributeRef.getEntityId(),+ protocolAttributeRef.getAttributeName()+ )+ )+ );- // Unlink the protocol configuration from the protocol- try {- protocol.unlinkProtocolConfiguration(protocolConfiguration);- } catch (Exception e) {- LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration unlinking", e);- }+ assets.forEach(+ asset ->+ getGroupedAgentLinkAttributes(+ asset.getAttributesStream(),+ assetAttribute -> getAgentLink(assetAttribute)+ .map(attributeRef -> attributeRef.equals(protocolAttributeRef))+ .orElse(false)+ ).forEach(this::unlinkAttributes)+ );++ Protocol protocol = getProtocol(configuration);++ // Unlink the protocol configuration from the protocol+ try {+ protocol.unlinkProtocolConfiguration(configuration);+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Protocol threw an exception during protocol configuration unlinking", e);+ }- // Set status to disconnected- publishProtocolConnectionStatus(protocolAttributeRef, DISCONNECTED);- protocolConfigurations.remove(protocolAttributeRef);+ // Set status to disconnected+ publishProtocolConnectionStatus(protocolAttributeRef, DISCONNECTED);+ protocolConfigurations.remove(protocolAttributeRef);+ });}}@@ -644,25 +635,27 @@ public class AgentService extends RouteBuilder implements ContainerService, Assereturn false;}- return AgentLink.getAgentLink(attribute)- .map(ref ->- getProtocolConfiguration(ref)- .orElseThrow(() -> new AssetProcessingException(AssetProcessingException.Reason.INVALID_AGENT_LINK))- )- .map(protocolConfiguration -> {- // Its' a send to actuator - push the update to the protocol- attribute.getStateEvent().ifPresent(attributeEvent -> {- LOG.fine("Sending to actuator topic: " + attributeEvent);- messageBrokerService.getProducerTemplate().sendBodyAndHeader(- ACTUATOR_TOPIC,- attributeEvent,- Protocol.ACTUATOR_TOPIC_TARGET_PROTOCOL,- protocolConfiguration.getValueAsString().orElse("")- );- });- return true; // Processing complete, skip other processors- })- .orElse(false); // This is just a non protocol attribute so allow the processing to continue+ synchronized (protocolConfigurations) {+ return AgentLink.getAgentLink(attribute)+ .map(ref ->+ getProtocolConfiguration(ref)+ .orElseThrow(() -> new AssetProcessingException(AssetProcessingException.Reason.INVALID_AGENT_LINK))+ )+ .map(protocolConfiguration -> {+ // Its' a send to actuator - push the update to the protocol+ attribute.getStateEvent().ifPresent(attributeEvent -> {+ LOG.fine("Sending to actuator topic: " + attributeEvent);+ messageBrokerService.getProducerTemplate().sendBodyAndHeader(+ ACTUATOR_TOPIC,+ attributeEvent,+ Protocol.ACTUATOR_TOPIC_TARGET_PROTOCOL,+ protocolConfiguration.getValueAsString().orElse("")+ );+ });+ return true; // Processing complete, skip other processors+ })+ .orElse(false); // This is just a non protocol attribute so allow the processing to continue+ }}/**diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.javaindex 17f0039d7..361bcbb09 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java@@ -28,7 +28,7 @@ import java.util.List;public class RulesBuilder {public interface Condition {- boolean evaluate(RulesFacts facts);+ Object evaluate(RulesFacts facts);}public interface Action {@@ -84,7 +84,19 @@ public class RulesBuilder {.name(builder.name).description(builder.description).priority(builder.priority)- .when(facts -> builder.condition.evaluate((RulesFacts) facts))+ .when(facts -> {+ Object result;+ try {+ result = builder.condition.evaluate((RulesFacts) facts);+ } catch (Exception ex) {+ throw new RuntimeException("Error evaluating condition of rule '" + builder.name + "': " + ex.getMessage(), ex);+ }+ if (result instanceof Boolean) {+ return (boolean)builder.condition.evaluate((RulesFacts) facts);+ } else {+ throw new IllegalArgumentException("Error evaluating condition of rule '" + builder.name + "': result is not boolean but " + result);+ }+ }).then(facts -> builder.action.execute((RulesFacts) facts)).build();rules.add(rule);}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.javaindex 20efb242d..60766ff6a 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java@@ -22,8 +22,13 @@ package org.openremote.manager.rules;import org.jeasy.rules.core.InferenceRulesEngine;import org.jeasy.rules.core.RulesEngineParameters;import org.openremote.container.timer.TimerService;+import org.openremote.manager.asset.AssetProcessingService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.concurrent.ManagerExecutorService;+import org.openremote.manager.notification.NotificationService;+import org.openremote.manager.rules.facade.AssetsFacade;+import org.openremote.manager.rules.facade.UsersFacade;+import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.rules.*;import java.util.*;@@ -48,15 +53,13 @@ public class RulesEngine<T extends Ruleset> {final protected ManagerExecutorService executorService;final protected AssetStorageService assetStorageService;- // Global rules engine has neither realmId nor assetId- final protected String realmId;- final protected String assetId;+ final protected RulesEngineId<T> id;+ final protected Assets assetsFacade;+ final protected Users usersFacade;- protected final Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();+ final protected Map<Long, RulesetDeployment> deployments = new LinkedHashMap<>();final protected RulesFacts facts;final protected InferenceRulesEngine engine;- final protected Assets assetsFacade;- final protected Users usersFacade;protected boolean running;protected ScheduledFuture eventsTimer;@@ -69,36 +72,30 @@ public class RulesEngine<T extends Ruleset> {protected boolean disableTemporaryFactExpiration = false;public RulesEngine(TimerService timerService,+ ManagerIdentityService identityService,ManagerExecutorService executorService,AssetStorageService assetStorageService,- Assets assetsFacade,- Users usersFacade,- String realmId,- String assetId) {+ AssetProcessingService assetProcessingService,+ NotificationService notificationService,+ RulesEngineId<T> id) {this.timerService = timerService;this.executorService = executorService;this.assetStorageService = assetStorageService;- this.realmId = realmId;- this.assetId = assetId;+ this.id = id;+ this.assetsFacade = new AssetsFacade<>(id, assetStorageService, assetProcessingService::sendAttributeEvent);+ this.usersFacade = new UsersFacade<>(id, assetStorageService, notificationService, identityService);this.facts = new RulesFacts(assetsFacade, this, RULES_LOG);engine = new InferenceRulesEngine(- // TODO We skip on the first failed rule, good idea?+ // 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));engine.registerRulesEngineListener(facts);engine.registerRuleListener(facts);-- this.assetsFacade = assetsFacade;- this.usersFacade = usersFacade;- }-- public String getRealmId() {- return realmId;}- public String getAssetId() {- return assetId;+ public RulesEngineId<T> getId() {+ return id;}/**@@ -320,7 +317,7 @@ public class RulesEngine<T extends Ruleset> {deployment.setError(ex);// TODO We always stop on any error, good idea?- // TODO This does not include RHS runtime errors, see RuleFacts.onFailure()+ // TODO We only get here on LHS runtime errors, RHS runtime errors are in RuleFacts.onFailure()stop();// TODO We skip any other deployment when we hit the first error, good idea?@@ -443,8 +440,7 @@ public class RulesEngine<T extends Ruleset> {@Overridepublic String toString() {return getClass().getSimpleName() + "{" +- "realmId='" + realmId + '\'' +- ", assetId='" + assetId + '\'' ++ "id='" + id + '\'' +", running='" + isRunning() + '\'' +", deployments='" + deploymentInfo + '\'' +'}';diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngineId.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngineId.javanew file mode 100644index 000000000..a5f9a969c--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngineId.java@@ -0,0 +1,100 @@+/*+ * Copyright 2018, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.rules;++import org.openremote.model.rules.AssetRuleset;+import org.openremote.model.rules.GlobalRuleset;+import org.openremote.model.rules.Ruleset;+import org.openremote.model.rules.TenantRuleset;++import java.util.Objects;+import java.util.Optional;++/**+ * The scope of a {@link RulesEngine} and, optional, the tenant or asset it belongs to.+ *+ * An engine in {@link org.openremote.model.rules.GlobalRuleset} scope has no {@link #realmId}+ * or {@link #assetId}. An engine {@link org.openremote.model.rules.TenantRuleset} scope has only+ * {@link #realmId}. An engine in {@link org.openremote.model.rules.AssetRuleset} scope has both.+ */+public class RulesEngineId<T extends Ruleset> {++ final protected Class<T> scope;+ final protected String realmId;+ final protected String assetId;++ @SuppressWarnings("unchecked")+ public RulesEngineId() {+ this((Class<T>) GlobalRuleset.class, null, null);+ }++ @SuppressWarnings("unchecked")+ public RulesEngineId(String realmId) {+ this((Class<T>) TenantRuleset.class, realmId, null);+ }++ @SuppressWarnings("unchecked")+ public RulesEngineId(String realmId, String assetId) {+ this((Class<T>) AssetRuleset.class, realmId, assetId);+ }++ protected RulesEngineId(Class<T> scope, String realmId, String assetId) {+ this.scope = scope;+ this.realmId = realmId;+ this.assetId = assetId;+ }++ public Class<T> getScope() {+ return scope;+ }++ public Optional<String> getRealmId() {+ return Optional.ofNullable(realmId);+ }++ public Optional<String> getAssetId() {+ return Optional.ofNullable(assetId);+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ RulesEngineId that = (RulesEngineId) o;+ return scope == that.scope &&+ Objects.equals(realmId, that.realmId) &&+ Objects.equals(assetId, that.assetId);+ }++ @Override+ public int hashCode() {++ return Objects.hash(scope, realmId, assetId);+ }++ @Override+ public String toString() {+ return getClass().getSimpleName() + "{" ++ "scope=" + scope.getSimpleName() ++ ", realmId='" + realmId + '\'' ++ ", assetId='" + assetId + '\'' ++ '}';+ }+}diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.javaindex ba4b760b8..6e5c9647e 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java@@ -292,11 +292,7 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListen@Overridepublic void onFailure(Rule rule, Facts facts, Exception exception) {- LOG.log(- Level.SEVERE,- String.format("*** %s: %s - on %s", "Rule execution error", rule.getName(), loggingContext),- exception- );+ throw new RuntimeException("Error executing action of rule '" + rule.getName() + "': " + exception.getMessage(), exception);}@SuppressWarnings("unchecked")@@ -376,6 +372,10 @@ public class RulesFacts extends Facts implements RuleListener, RulesEngineListenreturn matchAssetEvent(assetQuery).findFirst();}+ public Optional<TemporaryFact<AssetState>> matchLastAssetEvent(AssetQuery assetQuery) {+ return matchAssetEvent(assetQuery).reduce((first, second) -> second);+ }+public Stream<TemporaryFact<AssetState>> matchAssetEvent(AssetQuery assetQuery) {return getAssetEvents().stream().filter(fact -> matchFact(fact, AssetState.class, new AssetQueryPredicate(assetQuery)).isPresent());diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.javaindex cb4a87ca1..e311e83f4 100644--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java@@ -246,9 +246,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse// Remove any asset rules engines for assets in this realmassetEngines.values().stream()- .filter(re -> tenant.getId().equals(re.getRealmId()))+ .filter(re -> re.getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)).forEach(RulesEngine::stop);- assetEngines.entrySet().removeIf(entry -> tenant.getId().equals(entry.getValue().getRealmId()));+ assetEngines.entrySet().removeIf(entry ->+ entry.getValue().getId().getRealmId().map(id -> id.equals(tenant.getId())).orElse(false)+ );} else {// Create tenant rules engines for this tenant if it has any rulesets@@ -442,12 +444,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Asseif (globalEngine == null) {globalEngine = new RulesEngine<>(timerService,+ identityService,executorService,assetStorageService,- new AssetsFacade<>(GlobalRuleset.class, null, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),- new UsersFacade<>(GlobalRuleset.class, null, assetStorageService, notificationService, identityService),- null,- null+ assetProcessingService,+ notificationService,+ new RulesEngineId<>());}@@ -474,12 +476,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Assecreated[0] = true;return new RulesEngine<>(timerService,+ identityService,executorService,assetStorageService,- new AssetsFacade<>(TenantRuleset.class, realmId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),- new UsersFacade<>(TenantRuleset.class, realmId, assetStorageService, notificationService, identityService),- realmId,- null+ assetProcessingService,+ notificationService,+ new RulesEngineId<>(realmId));});@@ -536,12 +538,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Assecreated[0] = true;return new RulesEngine<>(timerService,+ identityService,executorService,assetStorageService,- new AssetsFacade<>(AssetRuleset.class, assetId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),- new UsersFacade<>(AssetRuleset.class, assetId, assetStorageService, notificationService, identityService),- ruleset.getRealmId(),- ruleset.getAssetId()+ assetProcessingService,+ notificationService,+ new RulesEngineId<>(ruleset.getRealmId(), assetId));});diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.javaindex a5f3f4909..0cc593b69 100644--- a/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java+++ b/manager/src/main/java/org/openremote/manager/rules/facade/AssetsFacade.java@@ -21,6 +21,7 @@ package org.openremote.manager.rules.facade;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.asset.ServerAsset;+import org.openremote.manager.rules.RulesEngineId;import org.openremote.model.asset.Asset;import org.openremote.model.asset.BaseAssetQuery;import org.openremote.model.attribute.AttributeEvent;@@ -40,14 +41,12 @@ import static org.openremote.model.asset.AssetQuery.TenantPredicate;*/public class AssetsFacade<T extends Ruleset> extends Assets {- protected final Class<T> rulesetType;- protected final String rulesetId;+ protected final RulesEngineId<T> rulesEngineId;protected final AssetStorageService assetStorageService;protected final Consumer<AttributeEvent> eventConsumer;- public AssetsFacade(Class<T> rulesetType, String rulesetId, AssetStorageService assetStorageService, Consumer<AttributeEvent> eventConsumer) {- this.rulesetType = rulesetType;- this.rulesetId = rulesetId;+ public AssetsFacade(RulesEngineId<T> rulesEngineId, AssetStorageService assetStorageService, Consumer<AttributeEvent> eventConsumer) {+ this.rulesEngineId = rulesEngineId;this.assetStorageService = assetStorageService;this.eventConsumer = eventConsumer;}@@ -68,7 +67,7 @@ public class AssetsFacade<T extends Ruleset> extends Assets {@Overridepublic Assets.RestrictedQuery tenant(TenantPredicate tenantPredicate) {- if (GlobalRuleset.class.isAssignableFrom(rulesetType))+ if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))return super.tenant(tenantPredicate);throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");}@@ -103,13 +102,18 @@ public class AssetsFacade<T extends Ruleset> extends Assets {}};- if (TenantRuleset.class.isAssignableFrom(rulesetType)) {- query.tenant = new TenantPredicate(rulesetId);+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ query.tenant = new TenantPredicate(+ rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))+ );}- if (AssetRuleset.class.isAssignableFrom(rulesetType)) {- ServerAsset restrictedAsset = assetStorageService.find(rulesetId, true);+ if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ ServerAsset restrictedAsset = assetStorageService.find(+ rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId)),+ true+ );if (restrictedAsset == null) {- throw new IllegalStateException("Asset is no longer available for this deployment: " + rulesetId);+ throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);}query.path = new PathPredicate(restrictedAsset.getPath());}diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.javaindex 5749922b6..588e2b165 100644--- a/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java+++ b/manager/src/main/java/org/openremote/manager/rules/facade/UsersFacade.java@@ -22,6 +22,7 @@ package org.openremote.manager.rules.facade;import org.openremote.manager.asset.AssetStorageService;import org.openremote.manager.asset.ServerAsset;import org.openremote.manager.notification.NotificationService;+import org.openremote.manager.rules.RulesEngineId;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.notification.AlertNotification;import org.openremote.model.rules.*;@@ -35,15 +36,13 @@ import java.util.function.Consumer;*/public class UsersFacade<T extends Ruleset> extends Users {- protected final Class<T> rulesetType;- protected final String rulesetId;+ protected final RulesEngineId<T> rulesEngineId;protected final AssetStorageService assetStorageService;protected final NotificationService notificationService;protected final ManagerIdentityService identityService;- public UsersFacade(Class<T> rulesetType, String rulesetId, AssetStorageService assetStorageService, NotificationService notificationService, ManagerIdentityService identityService) {- this.rulesetType = rulesetType;- this.rulesetId = rulesetId;+ public UsersFacade(RulesEngineId<T> rulesEngineId, AssetStorageService assetStorageService, NotificationService notificationService, ManagerIdentityService identityService) {+ this.rulesEngineId = rulesEngineId;this.assetStorageService = assetStorageService;this.notificationService = notificationService;this.identityService = identityService;@@ -54,20 +53,20 @@ public class UsersFacade<T extends Ruleset> extends Users {Users.RestrictedQuery query = new Users.RestrictedQuery() {@Overridepublic Users.RestrictedQuery tenant(UserQuery.TenantPredicate tenantPredicate) {- if (GlobalRuleset.class.isAssignableFrom(rulesetType))+ if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))return super.tenant(tenantPredicate);throw new IllegalArgumentException("Overriding query restriction is not allowed in this rules scope");}@Overridepublic Users.RestrictedQuery asset(UserQuery.AssetPredicate assetPredicate) {- if (GlobalRuleset.class.isAssignableFrom(rulesetType))+ if (GlobalRuleset.class.isAssignableFrom(rulesEngineId.getScope()))return super.asset(assetPredicate);- if (TenantRuleset.class.isAssignableFrom(rulesetType)) {+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {return super.asset(assetPredicate);// TODO: should only be allowed if asset belongs to tenant}- if (AssetRuleset.class.isAssignableFrom(rulesetType)) {+ if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {return super.asset(assetPredicate);// TODO: should only be allowed if restricted asset is descendant of scope's asset}@@ -85,32 +84,45 @@ public class UsersFacade<T extends Ruleset> extends Users {}};- if (TenantRuleset.class.isAssignableFrom(rulesetType)) {- query.tenantPredicate = new UserQuery.TenantPredicate(rulesetId);+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ query.tenantPredicate = new UserQuery.TenantPredicate(+ rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))+ );}- if (AssetRuleset.class.isAssignableFrom(rulesetType)) {- ServerAsset restrictedAsset = assetStorageService.find(rulesetId, true);+ if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ String assetId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId));+ ServerAsset restrictedAsset = assetStorageService.find(assetId, true);if (restrictedAsset == null) {- throw new IllegalStateException("Asset is no longer available for this deployment: " + rulesetId);+ // An asset was deleted in the database, but its ruleset is still deployed. This+ // can happen while the PersistenceEvent of the deletion is not processed and the+ // rules engine fires. This exception marks the ruleset deployment as execution+ // error status, and as soon as the PersistenceEvent is processed, the ruleset+ // deployment is removed and the problem resolved.+ throw new IllegalStateException("Asset is no longer available: " + rulesEngineId);}- query.assetPredicate = new UserQuery.AssetPredicate(rulesetId);+ query.assetPredicate = new UserQuery.AssetPredicate(assetId);}return query;-}@Overridepublic void storeAndNotify(String userId, AlertNotification alert) {- if (TenantRuleset.class.isAssignableFrom(rulesetType)) {- boolean userIsInTenant = identityService.getIdentityProvider().isUserInTenant(userId, rulesetId);+ if (TenantRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ boolean userIsInTenant = identityService.getIdentityProvider().isUserInTenant(+ userId,+ rulesEngineId.getRealmId().orElseThrow(() -> new IllegalArgumentException("Realm ID missing: " + rulesEngineId))+ );if (!userIsInTenant) {- throw new IllegalArgumentException("User not in tenant: " + rulesetId);+ throw new IllegalArgumentException("User not in tenant " + rulesEngineId + ": " + userId);}}- if (AssetRuleset.class.isAssignableFrom(rulesetType)) {- boolean userIsLinkedToAsset = assetStorageService.isUserAsset(userId, rulesetId);+ if (AssetRuleset.class.isAssignableFrom(rulesEngineId.getScope())) {+ boolean userIsLinkedToAsset = assetStorageService.isUserAsset(+ userId,+ rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ID missing: " + rulesEngineId))+ );if (!userIsLinkedToAsset) {- throw new IllegalArgumentException("User not linked to asset: " + rulesetId);+ throw new IllegalArgumentException("User not linked to asset " + rulesEngineId + ": " + userId);}}notificationService.storeAndNotify(userId, alert);diff --git a/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.javaindex ad573292e..37ba8dae1 100644--- a/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java+++ b/model/src/main/java/org/openremote/model/rules/AssetQueryPredicate.java@@ -76,6 +76,15 @@ public class AssetQueryPredicate implements Predicate<AssetState> {// TODO Would require meta items in AbstractAssetUpdatethrow new UnsupportedOperationException("Restriction by attribute meta not implemented in rules matching");}++ if (query.select != null) {+ throw new UnsupportedOperationException("Projection with 'select' not supported in rules matching");+ }++ if (query.orderBy != null) {+ throw new UnsupportedOperationException("Sorting with 'orderBy' not supported in rules matching");+ }+return true;}diff --git a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovynew file mode 100644index 000000000..de74d51b2--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy@@ -0,0 +1,203 @@+package org.openremote.test.failure++import org.openremote.manager.rules.RulesEngine+import org.openremote.manager.rules.RulesService+import org.openremote.manager.rules.RulesetDeployment+import org.openremote.manager.rules.RulesetStorageService+import org.openremote.manager.setup.SetupService+import org.openremote.manager.setup.builtin.KeycloakDemoSetup+import org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.rules.AssetRuleset+import org.openremote.model.rules.Ruleset+import org.openremote.model.rules.TenantRuleset+import org.openremote.test.ManagerContainerTrait+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++class RulesExecutionFailureTest extends Specification implements ManagerContainerTrait {++ def "Rule condition invalid return"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 5, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine apartment2Engine++ and: "some rules"+ Ruleset ruleset = new AssetRuleset(+ "Failure Ruleset",+ managerDemoSetup.apartment2Id,+ getClass().getResource("/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy").text,+ Ruleset.Lang.GROOVY+ )+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engine should have an error (first firing after initial asset state insert)"+ conditions.eventually {+ apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)+ assert apartment2Engine != null+ assert apartment2Engine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR+ assert apartment2Engine.deployments[ruleset.id].error instanceof IllegalArgumentException+ assert apartment2Engine.deployments[ruleset.id].error.message == "Error evaluating condition of rule 'The when condition is illegal, it's returning an Optional instead of a boolean': result is not boolean but Optional.empty"+ assert apartment2Engine.isError()+ assert apartment2Engine.getError() instanceof RuntimeException+ assert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")+ }++ cleanup: "stop the container"+ stopContainer(container)+ }++ def "Rule condition throws exception"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 5, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine apartment2Engine++ and: "some rules"+ Ruleset ruleset = new AssetRuleset(+ "Failure Ruleset",+ managerDemoSetup.apartment2Id,+ getClass().getResource("/org/openremote/test/failure/RulesFailureConditionThrowsException.groovy").text,+ Ruleset.Lang.GROOVY+ )+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engine should have an error (first firing after initial asset state insert)"+ conditions.eventually {+ apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)+ assert apartment2Engine != null+ assert apartment2Engine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR+ assert apartment2Engine.deployments[ruleset.id].error instanceof RuntimeException+ assert apartment2Engine.deployments[ruleset.id].error.message == "Error evaluating condition of rule 'Condition always throws exception': Oops"+ assert apartment2Engine.isError()+ assert apartment2Engine.getError() instanceof RuntimeException+ assert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")+ }++ cleanup: "stop the container"+ stopContainer(container)+ }++ def "Rule action throws exception"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 5, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine apartment2Engine++ and: "some rules"+ Ruleset ruleset = new AssetRuleset(+ "Failure Ruleset",+ managerDemoSetup.apartment2Id,+ getClass().getResource("/org/openremote/test/failure/RulesFailureActionThrowsException.groovy").text,+ Ruleset.Lang.GROOVY+ )+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engine should have an error (first firing after initial asset state insert)"+ conditions.eventually {+ apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)+ assert apartment2Engine != null+ assert apartment2Engine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR+ assert apartment2Engine.deployments[ruleset.id].error instanceof RuntimeException+ assert apartment2Engine.deployments[ruleset.id].error.message == "Error executing action of rule 'Action always throws exception': Oops"+ assert apartment2Engine.isError()+ assert apartment2Engine.getError() instanceof RuntimeException+ assert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")+ }++ cleanup: "stop the container"+ stopContainer(container)+ }++ def "Rule action calls users facade with invalid user ID in asset ruleset"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 10, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine apartment2Engine++ and: "some rules"+ Ruleset ruleset = new AssetRuleset(+ "Failure Ruleset",+ managerDemoSetup.apartment2Id,+ getClass().getResource("/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy").text,+ Ruleset.Lang.GROOVY+ )+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engines to become available and be running"+ conditions.eventually {+ apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)+ assert apartment2Engine != null+ assert apartment2Engine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR+ assert apartment2Engine.deployments[ruleset.id].error instanceof RuntimeException+ assert apartment2Engine.deployments[ruleset.id].error.message ==+ "Error executing action of rule 'Notify non-existent user': User not linked to asset RulesEngineId{scope=AssetRuleset, realmId='" + keycloakDemoSetup.customerATenant.id + "', assetId='" + managerDemoSetup.apartment2Id + "'}: doesnotexist"+ assert apartment2Engine.isError()+ assert apartment2Engine.getError() instanceof RuntimeException+ assert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")+ }++ cleanup: "stop the container"+ stopContainer(container)+ }++ def "Rule action calls users facade with invalid user ID in tenant ruleset"() {++ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 10, delay: 1)+ def serverPort = findEphemeralPort()+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)+ RulesEngine customerAEngine++ and: "some rules"+ Ruleset ruleset = new TenantRuleset(+ "Failure Ruleset",+ keycloakDemoSetup.customerATenant.id,+ getClass().getResource("/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy").text,+ Ruleset.Lang.GROOVY+ )+ ruleset = rulesetStorageService.merge(ruleset)++ expect: "the rule engines to become available and be running"+ conditions.eventually {+ customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)+ assert customerAEngine != null+ assert customerAEngine.deployments[ruleset.id].status == RulesetDeployment.Status.EXECUTION_ERROR+ assert customerAEngine.deployments[ruleset.id].error instanceof RuntimeException+ assert customerAEngine.deployments[ruleset.id].error.message == "Error executing action of rule 'Notify non-existent user': User not in tenant RulesEngineId{scope=TenantRuleset, realmId='" + keycloakDemoSetup.customerATenant.id + "', assetId='null'}: doesnotexist"+ assert customerAEngine.isError()+ assert customerAEngine.getError() instanceof RuntimeException+ assert customerAEngine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")+ }++ cleanup: "stop the container"+ stopContainer(container)+ }+}diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovynew file mode 100644index 000000000..1d1ad97b1--- /dev/null+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureActionNotificationInvalidUser.groovy@@ -0,0 +1,19 @@+package org.openremote.test.rules++import org.openremote.manager.rules.RulesBuilder+import org.openremote.model.notification.AlertNotification+import org.openremote.model.rules.Users++RulesBuilder rules = binding.rules+Users users = binding.users++rules.add()+ .name("Notify non-existent user")+ .when(+ { facts ->+ true+ })+ .then(+ { facts ->+ users.storeAndNotify("doesnotexist", new AlertNotification("Foo", "Bar"))+ })diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureActionThrowsException.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureActionThrowsException.groovynew file mode 100644index 000000000..024eb15c7--- /dev/null+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureActionThrowsException.groovy@@ -0,0 +1,16 @@+package org.openremote.test.failure++import org.openremote.manager.rules.RulesBuilder++RulesBuilder rules = binding.rules++rules.add()+ .name("Action always throws exception")+ .when(+ { facts ->+ true+ })+ .then(+ { facts ->+ throw new RuntimeException("Oops")+ })diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovynew file mode 100644index 000000000..bd55c8a2e--- /dev/null+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionInvalidReturn.groovy@@ -0,0 +1,17 @@+package org.openremote.test.failure++import org.openremote.manager.rules.RulesBuilder+import org.openremote.model.asset.AssetQuery++RulesBuilder rules = binding.rules++rules.add()+ .name("The when condition is illegal, it's returning an Optional instead of a boolean")+ .when(+ { facts ->+ facts.matchLastAssetEvent(new AssetQuery())+ })+ .then(+ { facts ->+ // Never called+ })diff --git a/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionThrowsException.groovy b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionThrowsException.groovynew file mode 100644index 000000000..b7cc32617--- /dev/null+++ b/test/src/test/resources/org/openremote/test/failure/RulesFailureConditionThrowsException.groovy@@ -0,0 +1,16 @@+package org.openremote.test.failure++import org.openremote.manager.rules.RulesBuilder++RulesBuilder rules = binding.rules++rules.add()+ .name("Condition always throws exception")+ .when(+ { facts ->+ throw new RuntimeException("Oops")+ })+ .then(+ { facts ->+ // Never called+ })