Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Removed drools, implemented rules engine with j-easy/easy-rules

Christian Bauer21737a3e5837
diff --git a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
index d8a46293e..3886a7472 100644
--- a/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
+++ b/agent/src/main/java/org/openremote/agent/protocol/macro/MacroProtocol.java
@@ -84,15 +84,7 @@ public class MacroProtocol extends AbstractProtocol {
synchronized (executions) {
executions.put(attributeRef, this);
}
-
- // Update the command Status of this attribute - We use a timestamp slightly in the past otherwise
- // it is possible for COMPLETED status update below to have the same timestamp and to then be rejected
- // by the asset processing service
- updateLinkedAttribute(new AttributeState(
- attributeRef,
- AttributeExecuteStatus.RUNNING.asValue()),
- timerService.getCurrentTimeMillis()-10
- );
+ updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.RUNNING.asValue()));
run();
}
@@ -103,8 +95,6 @@ public class MacroProtocol extends AbstractProtocol {
synchronized (executions) {
executions.remove(attributeRef);
}
-
- // Update the command Status of this attribute
updateLinkedAttribute(new AttributeState(attributeRef, AttributeExecuteStatus.CANCELLED.asValue()));
}
@@ -145,7 +135,7 @@ public class MacroProtocol extends AbstractProtocol {
Integer delayMillis = actions.get(iteration).getDelayMilliseconds();
// Schedule the next iteration
- scheduledFuture = executorService.schedule(this::run, delayMillis > 0 ? delayMillis: 0);
+ scheduledFuture = executorService.schedule(this::run, delayMillis > 0 ? delayMillis : 0);
}
}
diff --git a/client/build.gradle b/client/build.gradle
index 7519bf4a0..80e9fd79c 100644
--- a/client/build.gradle
+++ b/client/build.gradle
@@ -20,6 +20,7 @@ dependencies {
compile "com.google.elemental2:elemental2-promise:$elemental2Version"
compile "org.jboss.gwt.elemento:elemento-core:$elementoCoreVersion"
+ // TODO Built from https://github.com/richturner/gwt-jackson
compile files(['lib/gwt-jackson-0.14.3-SNAPSHOT.jar'])
//compile "com.github.nmorel.gwtjackson:gwt-jackson:$gwtJacksonVersion"
diff --git a/client/lib/gwt-jackson-0.14.3-SNAPSHOT.jar b/client/lib/gwt-jackson-0.14.3-SNAPSHOT.jar
index 75b47d45a..6d33fb140 100644
Binary files a/client/lib/gwt-jackson-0.14.3-SNAPSHOT.jar and b/client/lib/gwt-jackson-0.14.3-SNAPSHOT.jar differ
diff --git a/client/src/main/java/org/openremote/app/client/i18n/ManagerMessages.java b/client/src/main/java/org/openremote/app/client/i18n/ManagerMessages.java
index 3042d6378..42ff9d590 100644
--- a/client/src/main/java/org/openremote/app/client/i18n/ManagerMessages.java
+++ b/client/src/main/java/org/openremote/app/client/i18n/ManagerMessages.java
@@ -516,4 +516,8 @@ public interface ManagerMessages extends Messages {
String shareLink();
String noAppsFound();
+
+ String language();
+
+ String confirmationRulesLangChange();
}
diff --git a/client/src/main/java/org/openremote/app/client/rules/AbstractRulesEditorActivity.java b/client/src/main/java/org/openremote/app/client/rules/AbstractRulesEditorActivity.java
index acd523963..5765cb9ee 100644
--- a/client/src/main/java/org/openremote/app/client/rules/AbstractRulesEditorActivity.java
+++ b/client/src/main/java/org/openremote/app/client/rules/AbstractRulesEditorActivity.java
@@ -122,7 +122,7 @@ public abstract class AbstractRulesEditorActivity<T extends Ruleset, PLACE exten
protected void startCreate() {
ruleset = newRuleset();
- ruleset.setRules(environment.getMessages().rules() + "...");
+ ruleset.setRules(ruleset.getLang().getEmptyRulesExample());
clearViewMessages();
writeToView();
writeTemplateAssetToView();
@@ -201,8 +201,29 @@ public abstract class AbstractRulesEditorActivity<T extends Ruleset, PLACE exten
}
}
+ @Override
+ public void onLanguageChange(Ruleset.Lang lang) {
+ if (!view.getRules().equals(ruleset.getLang().getEmptyRulesExample())) {
+ view.showConfirmation(
+ environment.getMessages().confirmation(),
+ environment.getMessages().confirmationRulesLangChange(),
+ () -> {
+ ruleset.setLang(lang);
+ ruleset.setRules(lang.getEmptyRulesExample());
+ view.setRules(ruleset.getRules());
+ },
+ () -> view.setLang(ruleset.getLang())
+ );
+ } else {
+ ruleset.setLang(lang);
+ ruleset.setRules(lang.getEmptyRulesExample());
+ view.setRules(ruleset.getRules());
+ }
+ }
+
protected void writeToView() {
view.setName(ruleset.getName());
+ view.setLang(ruleset.getLang());
view.setRulesetEnabled(ruleset.isEnabled());
view.setRules(ruleset.getRules());
view.enableCreate(rulesetId == null);
@@ -221,6 +242,7 @@ public abstract class AbstractRulesEditorActivity<T extends Ruleset, PLACE exten
protected void readFromView() {
ruleset.setName(view.getName());
ruleset.setEnabled(view.getRulesetEnabled());
+ ruleset.setLang(view.getLang());
ruleset.setRules(view.getRules());
if (templateAsset != null) {
ruleset.setTemplateAssetId(templateAsset.getId());
diff --git a/client/src/main/java/org/openremote/app/client/rules/RulesEditor.java b/client/src/main/java/org/openremote/app/client/rules/RulesEditor.java
index 5fc7b190e..d24605db1 100644
--- a/client/src/main/java/org/openremote/app/client/rules/RulesEditor.java
+++ b/client/src/main/java/org/openremote/app/client/rules/RulesEditor.java
@@ -22,6 +22,7 @@ package org.openremote.app.client.rules;
import org.openremote.app.client.assets.browser.AssetTreeNode;
import org.openremote.app.client.assets.browser.BrowserTreeNode;
import org.openremote.app.client.widget.FormView;
+import org.openremote.model.rules.Ruleset;
public interface RulesEditor extends RulesView, FormView {
@@ -35,6 +36,8 @@ public interface RulesEditor extends RulesView, FormView {
void cancel();
void onTemplateAssetSelection(BrowserTreeNode browserTreeNode);
+
+ void onLanguageChange(Ruleset.Lang lang);
}
void setPresenter(Presenter presenter);
@@ -47,6 +50,10 @@ public interface RulesEditor extends RulesView, FormView {
void setNameError(boolean error);
+ void setLang(Ruleset.Lang lang);
+
+ Ruleset.Lang getLang();
+
void setRulesetEnabled(Boolean enabled);
boolean getRulesetEnabled();
diff --git a/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.java b/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.java
index fdb600dec..e44798b1d 100644
--- a/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.java
+++ b/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.java
@@ -26,6 +26,7 @@ import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HTMLPanel;
+import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Provider;
import elemental.client.Browser;
import elemental.html.AnchorElement;
@@ -37,8 +38,10 @@ import org.openremote.app.client.app.dialog.Confirmation;
import org.openremote.app.client.assets.browser.AssetBrowser;
import org.openremote.app.client.assets.browser.AssetSelector;
import org.openremote.app.client.assets.browser.AssetTreeNode;
+import org.openremote.model.rules.Ruleset;
import javax.inject.Inject;
+import java.util.Optional;
import java.util.logging.Logger;
public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
@@ -59,15 +62,16 @@ public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
@UiField
FormInputText nameInput;
@UiField
-
- FormButton rulesFileDownload;
- @UiField
- FileUploadLabelled rulesFileUpload;
+ FormListBox languageListBox;
@UiField
FormGroup optionsGroup;
@UiField
FormCheckBox enabledCheckBox;
+ @UiField
+ FormButton rulesFileDownload;
+ @UiField
+ FileUploadLabelled rulesFileUpload;
@UiField(provided = true)
AssetSelector templateAssetSelector;
@@ -125,10 +129,20 @@ public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
RulesEditorImpl.UI ui = GWT.create(RulesEditorImpl.UI.class);
initWidget(ui.createAndBindUi(this));
+ for (Ruleset.Lang lang : Ruleset.Lang.values()) {
+ languageListBox.addItem(lang.toString());
+ }
+
+ languageListBox.addChangeHandler(event -> {
+ if (presenter != null) {
+ presenter.onLanguageChange(getLang());
+ }
+ });
+
rulesFileDownload.addClickHandler(event -> {
AnchorElement downloadAnchor = (AnchorElement) Browser.getDocument().createElement("a");
downloadAnchor.setDownload(
- getName() != null && getName().length() > 0 ? getName() + ".drl.txt" : "OpenRemote-Rules.drl.txt"
+ (getName() != null && getName().length() > 0 ? getName() : "OpenRemote-Rules") + getLang().getFileExtension()
);
downloadAnchor.setHref(Browser.encodeURI("data:text/plain," + getRules()));
Browser.getDocument().getBody().appendChild(downloadAnchor);
@@ -142,9 +156,14 @@ public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
if (files.length() != 1)
return;
Blob file = (Blob) files.get(0);
- if (file.getType().matches("text.*") || rulesFileUpload.getFileUpload().getFilename().endsWith(".drl")) {
+ Optional<Ruleset.Lang> lang = Ruleset.Lang.valueOfFileName(rulesFileUpload.getFileUpload().getFilename());
+ if (lang.isPresent()) {
+ // TODO Does this work? file.getType().matches("text.*")
final FileReader reader = Browser.getWindow().newFileReader();
- reader.setOnloadend(evt -> setRules(reader.getResult().toString()));
+ reader.setOnloadend(evt -> {
+ setLang(lang.get());
+ setRules(reader.getResult().toString());
+ });
reader.readAsText(file, "UTF-8");
} else {
if (!rulesFileUpload.getElement().hasClassName("error")) {
@@ -195,6 +214,16 @@ public class RulesEditorImpl extends FormViewImpl implements RulesEditor {
return nameInput.getValue().length() > 0 ? nameInput.getValue() : null;
}
+ @Override
+ public void setLang(Ruleset.Lang lang) {
+ languageListBox.selectItem(lang.toString());
+ }
+
+ @Override
+ public Ruleset.Lang getLang() {
+ return Ruleset.Lang.valueOf(languageListBox.getSelectedValue());
+ }
+
@Override
public void setNameError(boolean error) {
nameGroup.setError(error);
diff --git a/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.ui.xml b/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.ui.xml
index ad13807dc..c7fee524e 100644
--- a/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.ui.xml
+++ b/client/src/main/java/org/openremote/app/client/rules/RulesEditorImpl.ui.xml
@@ -20,8 +20,7 @@
}
.rulesTextArea {
- margin: 0 !important;
- padding: 0 !important;
+ padding: 4px 0 0 0;
}
</ui:style>
@@ -61,6 +60,11 @@
<w:FormInputText ui:field="nameInput" addStyleNames="flex"/>
</w:FormField>
</w:field>
+ <w:actions>
+ <w:FormGroupActions>
+ <w:FormListBox ui:field="languageListBox"/>
+ </w:FormGroupActions>
+ </w:actions>
</w:FormGroup>
<w:FormGroup ui:field="optionsGroup">
diff --git a/client/src/main/java/org/openremote/app/client/rules/RulesetTable.java b/client/src/main/java/org/openremote/app/client/rules/RulesetTable.java
index 526d0d3d5..b4c186cb3 100644
--- a/client/src/main/java/org/openremote/app/client/rules/RulesetTable.java
+++ b/client/src/main/java/org/openremote/app/client/rules/RulesetTable.java
@@ -40,6 +40,8 @@ public class RulesetTable<R extends Ruleset> extends FormTable<R> {
public interface Style extends CssResource {
String nameColumn();
+ String langColumn();
+
String enabledColumn();
String templateColumn();
@@ -84,6 +86,18 @@ public class RulesetTable<R extends Ruleset> extends FormTable<R> {
}
};
+ final protected TextColumn<R> langColumn = new TextColumn<R>() {
+ @Override
+ public String getValue(R ruleset) {
+ return ruleset.getLang().toString();
+ }
+
+ @Override
+ public String getCellStyleNames(Cell.Context context, R object) {
+ return "nowrap";
+ }
+ };
+
final protected Column<R, String> enabledColumn = new Column<R, String>(new IconCell()) {
@Override
public String getValue(R ruleset) {
@@ -123,6 +137,10 @@ public class RulesetTable<R extends Ruleset> extends FormTable<R> {
addColumnStyleName(i++, style.lastModifiedColumn());
lastModifiedColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
+ addColumn(langColumn, createHeader(managerMessages.language()));
+ addColumnStyleName(i++, style.langColumn());
+ langColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_LEFT);
+
addColumn(enabledColumn, createHeader(managerMessages.enabled()));
addColumnStyleName(i++, style.enabledColumn());
enabledColumn.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
diff --git a/client/src/main/java/org/openremote/app/client/rules/asset/AssetRulesListImpl.ui.xml b/client/src/main/java/org/openremote/app/client/rules/asset/AssetRulesListImpl.ui.xml
index dc2b51bce..a7f3e5ae7 100644
--- a/client/src/main/java/org/openremote/app/client/rules/asset/AssetRulesListImpl.ui.xml
+++ b/client/src/main/java/org/openremote/app/client/rules/asset/AssetRulesListImpl.ui.xml
@@ -22,6 +22,9 @@
.lastModifiedColumn {
}
+ .langColumn {
+ }
+
.enabledColumn {
}
diff --git a/client/src/main/java/org/openremote/app/client/rules/global/GlobalRulesListImpl.ui.xml b/client/src/main/java/org/openremote/app/client/rules/global/GlobalRulesListImpl.ui.xml
index e28650edd..a196a2a14 100644
--- a/client/src/main/java/org/openremote/app/client/rules/global/GlobalRulesListImpl.ui.xml
+++ b/client/src/main/java/org/openremote/app/client/rules/global/GlobalRulesListImpl.ui.xml
@@ -26,6 +26,9 @@
.lastModifiedColumn {
}
+ .langColumn {
+ }
+
.enabledColumn {
}
diff --git a/client/src/main/java/org/openremote/app/client/rules/tenant/TenantRulesListImpl.ui.xml b/client/src/main/java/org/openremote/app/client/rules/tenant/TenantRulesListImpl.ui.xml
index 50ad8a0ff..00a1a06d5 100644
--- a/client/src/main/java/org/openremote/app/client/rules/tenant/TenantRulesListImpl.ui.xml
+++ b/client/src/main/java/org/openremote/app/client/rules/tenant/TenantRulesListImpl.ui.xml
@@ -26,6 +26,9 @@
.lastModifiedColumn {
}
+ .langColumn {
+ }
+
.enabledColumn {
}
diff --git a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
index 57b44b5d2..a1bfe35cb 100644
--- a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
+++ b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties
@@ -137,14 +137,14 @@ rulesetName=Ruleset name
editGlobalRules=Edit global rules
manageTenantAssets=Manage tenant assets
manageAssetRulesets=Manage asset rulesets
-uploadRulesFile=Upload DRL file
+uploadRulesFile=Upload rules file
updateRuleset=Save ruleset
createRuleset=Create ruleset
deleteRuleset=Delete ruleset
rulesetCreated=Ruleset created: {0}
rulesetDeleted=Ruleset deleted: {0}
rulesetUpdated=Ruleset saved: {0}
-downloadRulesFile=Download DRL file
+downloadRulesFile=Download rules file
editTenantRuleset=Edit tenant ruleset
editAssetRuleset=Edit asset ruleset
attributeWriteSent=Attribute write sent to server: {0}
@@ -409,3 +409,5 @@ tenant=Tenant
publicAccess=Public read access
shareLink=Share link
noAppsFound=No apps found
+language=Language
+confirmationRulesLangChange=Are you sure you want to switch rules language and replace existing rules?
diff --git a/container/build.gradle b/container/build.gradle
index 64965113b..8befe2c60 100644
--- a/container/build.gradle
+++ b/container/build.gradle
@@ -6,6 +6,7 @@ dependencies {
compile resolveProject(":model")
compile "org.codehaus.groovy:groovy:$groovyVersion"
+ compile "org.kohsuke:groovy-sandbox:$groovySandboxVersion"
compile "org.slf4j:slf4j-api:$slf4jVersion"
compile "org.slf4j:slf4j-jdk14:$slf4jVersion"
diff --git a/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java b/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java
index d500be994..003a65fa8 100644
--- a/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java
+++ b/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java
@@ -24,6 +24,7 @@ import java.util.concurrent.*;
import static org.openremote.container.concurrent.ContainerThreads.DEFAULT_REJECTED_EXECUTION_HANDLER;
import static org.openremote.container.concurrent.ContainerThreads.logExceptionCause;
+// TODO Unused
public class ContainerExecutor extends ThreadPoolExecutor {
/**
diff --git a/gradle.properties b/gradle.properties
index 516aa815b..31f671f7f 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -18,7 +18,8 @@ elemental2Version = 1.0.0-RC1
jsinteropBaseVersion = 1.0.0-RC1
gwtJacksonVersion = 0.14.2
jacksonVersion = 2.8.6
-groovyVersion = 2.4.12
+groovyVersion = 2.4.13
+groovySandboxVersion = 1.15
sqliteVersion = 3.20.0
hibernateVersion = 5.2.12.Final
hibernateValidatorVersion = 5.3.6.Final
@@ -30,7 +31,7 @@ objenesisVersion = 2.2
camelVersion = 2.19.0
tyrusVersion = 1.10
sunriseSunsetCalculatorVersion = 1.2
-droolsVersion = 7.5.0.Final
+easyRulesVersion = 3.1.0
quartzVersion= 2.2.3
calimeroVersion = 2.4-SNAPSHOT
clingVersion = 2.1.1
diff --git a/manager/build.gradle b/manager/build.gradle
index c0907d8fb..b2c9a6a62 100644
--- a/manager/build.gradle
+++ b/manager/build.gradle
@@ -10,13 +10,6 @@ dependencies {
compile resolveProject(":agent")
compile resolveProject(":model")
- compile("org.drools:drools-compiler:$droolsVersion") {
- exclude group: "com.thoughtworks.xstream"
- }
- compile("org.drools:drools-decisiontables:$droolsVersion") {
- exclude group: "org.apache.poi"
- }
-
compile "org.xerial:sqlite-jdbc:$sqliteVersion"
}
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
index 75cb97153..5e1c3cf77 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetAttributeLinkingService.java
@@ -142,7 +142,7 @@ public class AssetAttributeLinkingService implements ContainerService, Consumer<
// Convert the value as required
Pair<Boolean, Value> sendConvertedValue = convertValueForLinkedAttribute(
- assetState.getValue(),
+ assetState.getValue().orElse(null),
attributeLink.get(),
assetStorageService
);
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
index 30d3964c9..1ecb232da 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java
@@ -106,14 +106,13 @@ import static org.openremote.model.attribute.AttributeEvent.Source.INTERNAL;
* Checks if attribute is {@link AssetAttribute#isRuleState} or {@link AssetAttribute#isRuleEvent}, and if
* so the message is passed through the rule engines that are in scope for the asset.
* <p>
- * For {@link AssetState} messages, the rules service keeps the facts and thus the state of each rules
- * knowledge session in sync with the asset state changes that occur. If an asset attribute value changes,
- * the {@link AssetState} in each rules session will be updated to reflect the change.
+ * For {@link AssetState} messages, the rules service keeps the facts and thus the state of rule facts
+ * are in sync with the asset state changes that occur. If an asset attribute value changes,
+ * the {@link AssetState} in the rules engines will be updated to reflect the change.
* <p>
* For {@link AssetEvent} messages (obtained by converting the {@link AssetState}), they are inserted in the rules
- * sessions in scope and expired automatically either by a) the rules session if no time-pattern can possibly match
- * the event source timestamp anymore or b) by the rules service if the event lifetime set in
- * {@link RulesService#RULE_EVENT_EXPIRES} is reached or c) by the rules service if the event lifetime set in the
+ * engines in scope and expired automatically if the event lifetime set in
+ * {@link RulesService#RULE_EVENT_EXPIRES} is reached, or by the rules service if the event lifetime set in the
* attribute {@link AssetMeta#RULE_EVENT_EXPIRES} is reached.
* <h2>Asset Storage Service processing logic</h2>
* <p>
@@ -323,7 +322,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSer
if (assetState.getProcessingStatus() != AssetState.ProcessingStatus.COMPLETED)
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
clientEventService.publishEvent(new AttributeEvent(
- assetState.getId(), assetState.getAttributeName(), assetState.getValue(), timerService.getCurrentTimeMillis()
+ assetState.getId(), assetState.getAttributeName(), assetState.getValue().orElse(null), timerService.getCurrentTimeMillis()
));
}
LOG.fine("<<< Processing complete: " + assetState);
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
index d53907868..1be67240f 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetResourceImpl.java
@@ -445,11 +445,11 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
query.select.filterAccess(Access.RESTRICTED_READ);
}
- Tenant tenant = query.tenantPredicate != null
- ? !isNullOrEmpty(query.tenantPredicate.realmId)
- ? identityService.getIdentityProvider().getTenantForRealmId(query.tenantPredicate.realmId)
- : !isNullOrEmpty(query.tenantPredicate.realm)
- ? identityService.getIdentityProvider().getTenantForRealm(query.tenantPredicate.realm)
+ Tenant tenant = query.tenant != null
+ ? !isNullOrEmpty(query.tenant.realmId)
+ ? identityService.getIdentityProvider().getTenantForRealmId(query.tenant.realmId)
+ : !isNullOrEmpty(query.tenant.realm)
+ ? identityService.getIdentityProvider().getTenantForRealm(query.tenant.realm)
: getAuthenticatedTenant()
: getAuthenticatedTenant();
@@ -462,7 +462,7 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// This replicates behaviour of old getRoot and getChildren methods
- if (!isSuperUser() || query.parentPredicate == null || query.parentPredicate.noParent) {
+ if (!isSuperUser() || query.parent == null || query.parent.noParent) {
query.tenant(new TenantPredicate(tenant.getId()));
}
@@ -484,10 +484,10 @@ public class AssetResourceImpl extends ManagerWebResource implements AssetResour
}
// Force realm to be request realm
- if (query.tenantPredicate == null) {
+ if (query.tenant == null) {
query.tenant(new TenantPredicate().realm(requestRealm));
} else {
- query.tenantPredicate.realm = requestRealm;
+ query.tenant.realm = requestRealm;
}
// Force public access filter on query
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index cf89878d8..84ee88328 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -711,7 +711,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTE_NAMES &&
query.select.include != AssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;
- if ((!recursive || level == 3) && (includeRealmInfo || query.tenantPredicate != null)) {
+ if ((!recursive || level == 3) && (includeRealmInfo || query.tenant != null)) {
sb.append("join PUBLIC.REALM R on R.ID = A.REALM_ID ");
sb.append("join PUBLIC.REALM_ATTRIBUTE RA on RA.REALM_ID = R.ID and RA.NAME = 'displayName' ");
}
@@ -721,7 +721,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
if (level == 1) {
- if (query.parentPredicate != null && !query.parentPredicate.noParent) {
+ if (query.parent != null && !query.parent.noParent) {
sb.append("cross join ASSET P ");
} else {
sb.append("left outer join ASSET P on A.PARENT_ID = P.ID ");
@@ -782,45 +782,45 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, query.id));
}
- if (level == 1 && query.namePredicate != null) {
- sb.append(query.namePredicate.caseSensitive ? " and A.NAME " : " and upper(A.NAME)");
- sb.append(query.namePredicate.match == AssetQuery.Match.EXACT ? " = ?" : " like ?");
+ if (level == 1 && query.name != null) {
+ sb.append(query.name.caseSensitive ? " and A.NAME " : " and upper(A.NAME)");
+ sb.append(query.name.match == AssetQuery.Match.EXACT ? " = ?" : " like ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.namePredicate.prepareValue()));
+ binders.add(st -> st.setString(pos, query.name.prepareValue()));
}
- if (query.parentPredicate != null) {
+ if (query.parent != null) {
// Can only restrict recursive query parent by asset type
- if (level == 1 && query.parentPredicate.id != null) {
+ if (level == 1 && query.parent.id != null) {
sb.append(" and p.ID = a.PARENT_ID");
sb.append(" and A.PARENT_ID = ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.parentPredicate.id));
- } else if (query.parentPredicate.type != null) {
+ binders.add(st -> st.setString(pos, query.parent.id));
+ } else if (query.parent.type != null) {
sb.append(" and p.ID = a.PARENT_ID");
sb.append(" and P.ASSET_TYPE = ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.parentPredicate.type));
- } else if (level == 1 && query.parentPredicate.noParent) {
+ binders.add(st -> st.setString(pos, query.parent.type));
+ } else if (level == 1 && query.parent.noParent) {
sb.append(" and A.PARENT_ID is null");
}
}
- if (level == 1 && query.pathPredicate != null && query.pathPredicate.hasPath()) {
+ if (level == 1 && query.path != null && query.path.hasPath()) {
sb.append(" and ? <@ get_asset_tree_path(A.ID)");
final int pos = binders.size() + 1;
- binders.add(st -> st.setArray(pos, st.getConnection().createArrayOf("text", query.pathPredicate.path)));
+ binders.add(st -> st.setArray(pos, st.getConnection().createArrayOf("text", query.path.path)));
}
if (!recursive || level == 3) {
- if (query.tenantPredicate != null && query.tenantPredicate.realmId != null) {
+ if (query.tenant != null && query.tenant.realmId != null) {
sb.append(" and R.ID = ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.tenantPredicate.realmId));
- } else if (query.tenantPredicate != null && query.tenantPredicate.realm != null) {
+ binders.add(st -> st.setString(pos, query.tenant.realmId));
+ } else if (query.tenant != null && query.tenant.realm != null) {
sb.append(" and R.NAME = ?");
final int pos = binders.size() + 1;
- binders.add(st -> st.setString(pos, query.tenantPredicate.realm));
+ binders.add(st -> st.setString(pos, query.tenant.realm));
}
if (query.userId != null) {
@@ -840,8 +840,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
binders.add(st -> st.setString(pos, query.type.prepareValue()));
}
- if (query.attributeMetaPredicates != null) {
- for (AttributeMetaPredicate attributeMetaPredicate : query.attributeMetaPredicates) {
+ if (query.attributeMeta != null) {
+ for (AttributeMetaPredicate attributeMetaPredicate : query.attributeMeta) {
String attributeMetaFilter = buildAttributeMetaFilter(attributeMetaPredicate, binders);
if (attributeMetaFilter.length() > 0) {
@@ -855,8 +855,8 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
}
}
- if (query.attributePredicates != null) {
- for (AssetQuery.AttributePredicate attributePredicate : query.attributePredicates) {
+ if (query.attribute != null) {
+ for (AssetQuery.AttributePredicate attributePredicate : query.attribute) {
StringBuilder attributeFilterBuilder = new StringBuilder();
attributeFilterBuilder.append(buildAttributeFilter(attributePredicate, binders));
@@ -898,7 +898,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.BooleanPredicate) {
AssetQuery.BooleanPredicate booleanPredicate = (AssetQuery.BooleanPredicate) attributeMetaPredicate.itemValuePredicate;
attributeMetaBuilder.append(" and AM.VALUE #> '{value}' = to_jsonb(")
- .append(booleanPredicate.predicate)
+ .append(booleanPredicate.value)
.append(")");
} else if (attributeMetaPredicate.itemValuePredicate instanceof AssetQuery.StringArrayPredicate) {
AssetQuery.StringArrayPredicate stringArrayPredicate = (AssetQuery.StringArrayPredicate) attributeMetaPredicate.itemValuePredicate;
@@ -943,7 +943,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributePredicate.value instanceof AssetQuery.BooleanPredicate) {
AssetQuery.BooleanPredicate booleanPredicate = (AssetQuery.BooleanPredicate) attributePredicate.value;
attributeBuilder.append(" and AX.VALUE #> '{value}' = to_jsonb(")
- .append(booleanPredicate.predicate)
+ .append(booleanPredicate.value)
.append(")");
} else if (attributePredicate.value instanceof AssetQuery.StringArrayPredicate) {
AssetQuery.StringArrayPredicate stringArrayPredicate = (AssetQuery.StringArrayPredicate) attributePredicate.value;
@@ -968,17 +968,17 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
final int formatPos = binders.size() + 1;
binders.add(st -> st.setString(formatPos, dateTimePredicate.dateFormat));
- switch (dateTimePredicate.operatorMatch) {
- case EXACT:
+ switch (dateTimePredicate.operator) {
+ case EQUALS:
attributeBuilder.append(" = to_timestamp(?, ?)");
break;
- case GREATER_THEN:
+ case GREATER_THAN:
attributeBuilder.append(" > to_timestamp(?, ?)");
break;
case GREATER_EQUALS:
attributeBuilder.append(" >= to_timestamp(?, ?)");
break;
- case LESS_THEN:
+ case LESS_THAN:
attributeBuilder.append(" < to_timestamp(?, ?)");
break;
case LESS_EQUALS:
@@ -995,18 +995,18 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
} else if (attributePredicate.value instanceof AssetQuery.NumberPredicate) {
AssetQuery.NumberPredicate numberPredicate = (AssetQuery.NumberPredicate) attributePredicate.value;
attributeBuilder.append(" and (AX.VALUE #>> '{value}')::numeric");
- switch (numberPredicate.operatorMatch) {
- case EXACT:
+ switch (numberPredicate.operator) {
+ case EQUALS:
default:
attributeBuilder.append(" = ?");
break;
- case GREATER_THEN:
+ case GREATER_THAN:
attributeBuilder.append(" > ?");
break;
case GREATER_EQUALS:
attributeBuilder.append(" >= ?");
break;
- case LESS_THEN:
+ case LESS_THAN:
attributeBuilder.append(" < ?");
break;
case LESS_EQUALS:
@@ -1022,14 +1022,14 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
case DOUBLE:
default:
binders.add(st -> st.setDouble(pos, numberPredicate.value));
- if (numberPredicate.operatorMatch == OperatorMatch.BETWEEN) {
+ if (numberPredicate.operator == Operator.BETWEEN) {
final int pos2 = binders.size() + 1;
binders.add(st -> st.setDouble(pos, numberPredicate.rangeValue));
}
break;
case INTEGER:
binders.add(st -> st.setInt(pos, (int) numberPredicate.value));
- if (numberPredicate.operatorMatch == OperatorMatch.BETWEEN) {
+ if (numberPredicate.operator == Operator.BETWEEN) {
final int pos2 = binders.size() + 1;
binders.add(st -> st.setInt(pos2, (int) numberPredicate.rangeValue));
}
diff --git a/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java b/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
index e293d8b22..0dabfef88 100644
--- a/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
+++ b/manager/src/main/java/org/openremote/manager/concurrent/ManagerExecutorService.java
@@ -21,7 +21,6 @@ package org.openremote.manager.concurrent;
import org.openremote.agent.protocol.ProtocolExecutorService;
import org.openremote.container.Container;
-import org.openremote.container.concurrent.ContainerExecutor;
import org.openremote.container.concurrent.ContainerScheduledExecutor;
import java.util.Collection;
@@ -32,30 +31,18 @@ import static org.openremote.container.util.MapAccess.getInteger;
public class ManagerExecutorService implements ProtocolExecutorService {
- /**
- * Threads used by rules engines, each rule engine runs in a separate thread and blocks it.
- * The pool size limits the number of rules engines that can exist.
- */
- public static final String RULES_THREADS_MAX = "RULES_THREADS_MAX";
- public static final int RULES_THREADS_MAX_DEFAULT = Integer.MAX_VALUE;
-
/**
* Threads used by scheduled, usually short-lived and non-blocking tasks, such as protocols
* polling a remote service at regular interval, or the internal checks for expired client
- * subscriptions on the event bus.
+ * subscriptions on the event bus. Also used by the rules engine.
*/
public static final String SCHEDULED_TASKS_THREADS_MAX = "SCHEDULED_TASKS_THREADS_MAX";
public static final int SCHEDULED_TASKS_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 2);
- protected ExecutorService rulesExecutor;
protected ScheduledExecutorService scheduledTasksExecutor;
@Override
public void init(Container container) throws Exception {
- int rulesThreadsMax =
- getInteger(container.getConfig(), RULES_THREADS_MAX, RULES_THREADS_MAX_DEFAULT);
- rulesExecutor = new ContainerExecutor("Rules engine", 0, rulesThreadsMax, 60, -1);
-
int scheduledTasksThreadsMax =
getInteger(container.getConfig(), SCHEDULED_TASKS_THREADS_MAX, SCHEDULED_TASKS_THREADS_MAX_DEFAULT);
scheduledTasksExecutor = new ContainerScheduledExecutor("Scheduled task", scheduledTasksThreadsMax);
@@ -67,14 +54,9 @@ public class ManagerExecutorService implements ProtocolExecutorService {
@Override
public void stop(Container container) throws Exception {
- rulesExecutor.shutdownNow();
scheduledTasksExecutor.shutdown();
}
- public ExecutorService getRulesExecutor() {
- return rulesExecutor;
- }
-
@Override
public ScheduledFuture schedule(Runnable runnable, long delayMillis) {
return scheduledTasksExecutor.schedule(runnable, delayMillis, TimeUnit.MILLISECONDS);
diff --git a/manager/src/main/java/org/openremote/manager/rules/RuleExecutionLogger.java b/manager/src/main/java/org/openremote/manager/rules/RuleExecutionLogger.java
deleted file mode 100644
index febf1de28..000000000
--- a/manager/src/main/java/org/openremote/manager/rules/RuleExecutionLogger.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright 2017, OpenRemote Inc.
- *
- * See the CONTRIBUTORS.txt file in the distribution for a
- * full listing of individual contributors.
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License as
- * published by the Free Software Foundation, either version 3 of the
- * License, or (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
- */
-package org.openremote.manager.rules;
-
-import org.kie.api.definition.rule.Rule;
-import org.kie.api.event.rule.BeforeMatchFiredEvent;
-import org.kie.api.event.rule.DefaultAgendaEventListener;
-import org.kie.api.runtime.rule.Match;
-
-import java.util.List;
-import java.util.function.Supplier;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * This class logs Drools rule execution. It is intended to assist the user in debugging Drools behavior.
- */
-public class RuleExecutionLogger extends DefaultAgendaEventListener {
-
- final protected Supplier<String> contextSupplier;
- final protected Logger LOG;
-
- public RuleExecutionLogger(Supplier<String> contextSupplier, Logger LOG) {
- this.contextSupplier = contextSupplier;
- this.LOG = LOG;
- }
-
- @Override
- public void beforeMatchFired(BeforeMatchFiredEvent event) {
- final Rule rule = event.getMatch().getRule();
- String ruleName = rule.getName();
-
- String rulePackage = rule.getPackageName();
- ruleName = "\"" + ruleName + "\" // (package " + rulePackage + ")";
-
- Match matchEvent = event.getMatch();
- List<String> declarationIDs = matchEvent.getDeclarationIds();
- List<Object> antecedents = matchEvent.getObjects();
-
- String declarationLog = "";
- for (String declarationID : declarationIDs) {
- Object declarationValue = matchEvent.getDeclarationValue(declarationID);
- String declarationValueString = this.declarationValueToString(declarationValue);
- /* TODO Update for v3
- if (declarationValue instanceof Sensor || declarationValue instanceof SensorState) {
- declarationLog = String.format("%s\t\tDeclaration: \"%s\"\n\t\tValue:\n\t\t\t%s\n", declarationLog, declarationID, declarationValueString);
- } else {
- declarationLog = String.format("%s\t\tDeclaration: \"%s: %s\"\n", declarationLog, declarationID, declarationValueString);
- }
- */
- declarationLog = String.format("%s\t\tDeclaration: \"%s: %s\"\n", declarationLog, declarationID, declarationValueString);
- }
-
- String objectLog = "";
- for (Object antecedent : antecedents) {
- String theClass = antecedent.getClass().getSimpleName();
- String theValue = this.antecedentValueToString(antecedent);
- objectLog = String.format("%s\t\tClass: \"%s\"\n\t\tFields: \n\t\t\t%s\n", objectLog, theClass, theValue);
- }
-
- if (ruleName.startsWith("\"--")) {
- LOG.log(Level.INFO,
- String.format("*** On %s\n*** Rule fired %s" +
- "\tDeclarations \n---------------------------------\n%s\n" +
- "\tLHS objects(antecedents)\n---------------------------------\n%s", contextSupplier.get(), ruleName, declarationLog, objectLog)
- );
- } else if (ruleName.startsWith("\"-")) {
- LOG.log(Level.INFO,
- String.format("*** On %s\n *** Rule fired %s", contextSupplier.get(), ruleName)
- );
- }
- }
-
- /**
- * This method converts a declarationValue into a string.
- * The need for this method would be obviated if all our facts descended from
- * a Fact class with a method to return the most salient value of a fact.
- *
- * @param antecedent - An object referenced by a drools LHS
- */
- private String antecedentValueToString(Object antecedent) {
- String theValue = null;
- if (antecedent != null) {
- theValue = antecedent.toString();
- }
-
- /* TODO Update for v3
- if (antecedent instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
- {
- Sensor theSensor = (Sensor) antecedent;
- String sensorName = theSensor.getSensorDefinition().getName();
- theValue = String.format("Sensor: %s\n", sensorName);
-
- theValue = String.format("%s\t\tSensor Properties\n", theValue);
- Map<String, String> sensorValues = theSensor.getSensorDefinition().getProperties();
-
- for (Map.Entry<String, String> entry : sensorValues.entrySet()) {
- String entryName = entry.getKey();
- String entryValue = entry.getValue();
- theValue = String.format("%sName: \t\"%s\"\n\t\t\tValue: \t\"%s\"", theValue, entryName, entryValue);
- }
- }
- if (antecedent instanceof SensorState) {
- SensorState theSensorState = (SensorState) antecedent;
- String sensorName = theSensorState.getSensorName();
- String stateValue = theSensorState.getValue().toString(); //assumes all values can directly cast to String
- theValue = String.format("Sensor name: \t\"%s\"\n\t\t\tState value: \t\"%s\"", sensorName, stateValue);
- }
- */
-
- return theValue;
- }
-
- /**
- * This method converts a declarationValue into a string.
- * The need for this method would be obviated if all our facts descended from
- * a Fact class with a method to return the unique identifier as a string.
- *
- * @param declarationValue - The object associated with a drools LHS declaration
- */
- private String declarationValueToString(Object declarationValue) {
- String convertedDeclarationValue = null;
- if (declarationValue != null) {
- convertedDeclarationValue = declarationValue.toString();
- }
-
- /* TODO Update for v3
- if (declarationValue instanceof Sensor) //may be unnecessary if we never have raw sensor objects in WM
- {
- convertedDeclarationValue = ((Sensor) declarationValue).getSensorDefinition().getName();
- }
- if (declarationValue instanceof SensorState) {
- String sensorName = ((SensorState) declarationValue).getSensorName();
- String sensorValue = ((SensorState) declarationValue).getValue().toString();
- convertedDeclarationValue = String.format("Sensor Name: \"%s\"\n\t\t\tSensor Value: \"%s\"", sensorName, sensorValue);
- }
- */
-
- return convertedDeclarationValue;
- }
-}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java
new file mode 100644
index 000000000..17f0039d7
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesBuilder.java
@@ -0,0 +1,94 @@
+/*
+ * 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.jeasy.rules.api.Rule;
+import org.jeasy.rules.core.RuleBuilder;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class RulesBuilder {
+
+ public interface Condition {
+ boolean evaluate(RulesFacts facts);
+ }
+
+ public interface Action {
+ void execute(RulesFacts facts);
+ }
+
+ public static class Builder {
+ protected String name = org.jeasy.rules.api.Rule.DEFAULT_NAME;
+ protected String description = org.jeasy.rules.api.Rule.DEFAULT_DESCRIPTION;
+ protected int priority = org.jeasy.rules.api.Rule.DEFAULT_PRIORITY;
+ protected Condition condition = facts -> false;
+ protected Action action = facts -> {
+ };
+
+ public Builder name(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public Builder description(String description) {
+ this.description = description;
+ return this;
+ }
+
+ public Builder priority(int priority) {
+ this.priority = priority;
+ return this;
+ }
+
+ public Builder when(Condition condition) {
+ this.condition = condition;
+ return this;
+ }
+
+ public Builder then(Action action) {
+ this.action = action;
+ return this;
+ }
+ }
+
+ final protected List<Builder> builders = new ArrayList<>();
+
+ public Builder add() {
+ Builder builder = new Builder();
+ builders.add(builder);
+ return builder;
+ }
+
+ public Rule[] build() {
+ List<Rule> rules = new ArrayList<>();
+ for (Builder builder : builders) {
+ Rule rule = new RuleBuilder()
+ .name(builder.name)
+ .description(builder.description)
+ .priority(builder.priority)
+ .when(facts -> builder.condition.evaluate((RulesFacts) facts))
+ .then(facts -> builder.action.execute((RulesFacts) facts)).build();
+ rules.add(rule);
+ }
+ return rules.toArray(new Rule[rules.size()]);
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesClock.java b/manager/src/main/java/org/openremote/manager/rules/RulesClock.java
new file mode 100644
index 000000000..6a4b037fd
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesClock.java
@@ -0,0 +1,68 @@
+/*
+ * 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.container.timer.TimerService;
+import org.openremote.model.rules.TemporaryFact;
+import org.openremote.model.util.TimeUtil;
+
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.util.function.Predicate;
+
+/**
+ * A fact that is present in any {@link RulesFacts}.
+ */
+public class RulesClock {
+
+ final public double timestamp;
+ final public LocalDateTime time;
+
+ public RulesClock(TimerService timerService) {
+ this(timerService.getCurrentTimeMillis());
+ }
+
+ public RulesClock(double timestamp) {
+ this.timestamp = timestamp;
+ time = LocalDateTime.ofInstant(Instant.ofEpochMilli((long) this.timestamp), ZoneId.systemDefault());
+ }
+
+ public double getTimestamp() {
+ return timestamp;
+ }
+
+ public LocalDateTime getTime() {
+ return time;
+ }
+
+ public <T extends TemporaryFact> Predicate<T> last(String timeWindow) {
+ double timeWindowStart = getTimestamp() - TimeUtil.parseTimeString(timeWindow);
+ return fact -> timeWindowStart <= fact.getTimestamp();
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "timestamp=" + timestamp +
+ ", time=" + time +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
index 6176d6428..80c2be42c 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesEngine.java
@@ -19,425 +19,258 @@
*/
package org.openremote.manager.rules;
-import org.drools.core.ClassObjectFilter;
-import org.drools.core.common.InternalWorkingMemory;
-import org.drools.core.time.InternalSchedulerService;
-import org.drools.core.time.JobContext;
-import org.drools.core.time.JobHandle;
-import org.drools.core.time.impl.*;
-import org.drools.template.ObjectDataCompiler;
-import org.kie.api.KieServices;
-import org.kie.api.builder.KieBuilder;
-import org.kie.api.builder.KieFileSystem;
-import org.kie.api.builder.Message;
-import org.kie.api.builder.ReleaseId;
-import org.kie.api.builder.model.KieBaseModel;
-import org.kie.api.builder.model.KieModuleModel;
-import org.kie.api.builder.model.KieSessionModel;
-import org.kie.api.conf.EqualityBehaviorOption;
-import org.kie.api.conf.EventProcessingOption;
-import org.kie.api.event.rule.*;
-import org.kie.api.runtime.KieContainer;
-import org.kie.api.runtime.KieSession;
-import org.kie.api.runtime.KieSessionConfiguration;
-import org.kie.api.runtime.conf.ClockTypeOption;
-import org.kie.api.runtime.rule.FactHandle;
-import org.kie.api.time.SessionClock;
+import org.jeasy.rules.core.InferenceRulesEngine;
+import org.jeasy.rules.core.RulesEngineParameters;
import org.openremote.container.timer.TimerService;
-import org.openremote.container.util.Util;
import org.openremote.manager.asset.AssetStorageService;
-import org.openremote.manager.asset.ServerAsset;
import org.openremote.manager.concurrent.ManagerExecutorService;
import org.openremote.model.asset.AssetEvent;
import org.openremote.model.asset.AssetState;
-import org.openremote.model.attribute.AttributeType;
import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Ruleset;
import org.openremote.model.rules.Users;
-import org.openremote.model.rules.template.TemplateFilter;
-import org.openremote.model.util.Pair;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.nio.charset.StandardCharsets;
import java.util.*;
-import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
-import java.util.function.Consumer;
-import java.util.function.Function;
-import java.util.function.Supplier;
import java.util.logging.Level;
import java.util.logging.Logger;
-import java.util.stream.Collectors;
-import static org.openremote.model.attribute.Attribute.isAttributeTypeEqualTo;
+import static org.openremote.manager.rules.RulesetDeployment.Status.*;
public class RulesEngine<T extends Ruleset> {
public static final Logger LOG = Logger.getLogger(RulesEngine.class.getName());
- // Separate logger for stats
- public static final Logger STATS_LOG = Logger.getLogger("org.openremote.rules.RulesEngineStats");
-
- // Separate logger for rules, available global in session
+ // Separate logger for execution of rules
public static final Logger RULES_LOG = Logger.getLogger("org.openremote.rules.Rules");
- private static Long counter = 1L;
-
- static final protected Util UTIL = new Util();
+ // Separate logger for periodic stats printer
+ public static final Logger STATS_LOG = Logger.getLogger("org.openremote.rules.RulesEngineStats");
final protected TimerService timerService;
final protected ManagerExecutorService executorService;
final protected AssetStorageService assetStorageService;
- final protected Supplier<Assets> assetsFacadeSupplier;
- final protected Supplier<Users> usersFacadeSupplier;
- final protected String id;//If globalRuleSet then null if tenantRuleSet then realmId if assetRuleSet then assetId
- final protected Function<RulesEngine, AgendaEventListener> rulesEngineListeners;
- final protected Consumer<Throwable> errorListener;
-
- protected final Map<Long, T> rulesets = new LinkedHashMap<>();
- protected String rulesetsDebug;
- protected KieSession knowledgeSession;
- protected KieServices kieServices;
- protected KieFileSystem kfs;
- // We need to be able to reference the KieModule dynamically generated for this engine
- // from the singleton KieRepository to do this we need a pom.xml file with a release ID - crazy drools!!
- protected ReleaseId releaseId;
- protected Future runningFuture;
- protected Throwable error;
- final protected Map<AssetState, FactHandle> assetStates = new HashMap<>();
- // This consumer is useful in testing, as we can't have a reliable event fact
- // count from Drools session (events are expired automatically))
- protected Consumer<AssetEvent> assetEventsConsumer;
+
+ // Global rules engine has neither realmId nor assetId
+ final protected String realmId;
+ final protected String assetId;
+
+ protected final 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;
protected ScheduledFuture statsTimer;
+ // Only used to optimize toString(), contains the details of this engine
+ protected String deploymentInfo;
+
+ // Only used in tests to prevent scheduled firing of engine
+ protected boolean disableTemporaryFactExpiration = false;
+
public RulesEngine(TimerService timerService,
ManagerExecutorService executorService,
AssetStorageService assetStorageService,
- Supplier<Assets> assetsFacadeSupplier,
- Supplier<Users> usersFacadeSupplier,
- String id,
- Function<RulesEngine, AgendaEventListener> rulesEngineListeners,
- Consumer<Throwable> errorListener) {
+ Assets assetsFacade,
+ Users usersFacade,
+ String realmId,
+ String assetId) {
this.timerService = timerService;
this.executorService = executorService;
this.assetStorageService = assetStorageService;
- this.assetsFacadeSupplier = assetsFacadeSupplier;
- this.usersFacadeSupplier = usersFacadeSupplier;
- this.id = id;
- this.rulesEngineListeners = rulesEngineListeners;
- this.errorListener = errorListener;
- }
+ this.realmId = realmId;
+ this.assetId = assetId;
- protected synchronized static Long getNextCounter() {
- return counter++;
- }
-
- public synchronized Ruleset[] getAllRulesets() {
- return rulesets.values().stream().toArray(Ruleset[]::new);
- }
-
- public String getId() {
- return id;
- }
-
- public boolean isRunning() {
- return runningFuture != null;
- }
+ this.facts = new RulesFacts(assetsFacade, this, RULES_LOG);
+ engine = new InferenceRulesEngine(
+ // TODO We skip on the first failed rule, good idea?
+ new RulesEngineParameters(false, true, false, RulesEngineParameters.DEFAULT_RULE_PRIORITY_THRESHOLD)
+ );
+ engine.registerRulesEngineListener(facts);
+ engine.registerRuleListener(facts);
- public boolean isError() {
- return error != null;
+ this.assetsFacade = assetsFacade;
+ this.usersFacade = usersFacade;
}
- public Throwable getError() {
- return error;
+ public String getRealmId() {
+ return realmId;
}
- protected void setError(Throwable error) {
- this.error = error;
- if (errorListener != null)
- errorListener.accept(error);
+ public String getAssetId() {
+ return assetId;
}
- public KieSession getKnowledgeSession() {
- return knowledgeSession;
+ /**
+ * @return a shallow copy of the asset state facts.
+ */
+ public Set<AssetState> getAssetStates() {
+ synchronized (deployments) {
+ return new HashSet<>(facts.getAssetStates());
+ }
}
- public SessionClock getSessionClock() {
- KieSession session = knowledgeSession;
- if (session != null) {
- return session.getSessionClock();
+ /**
+ * @return a shallow copy of the asset event facts.
+ */
+ public List<AssetEvent> getAssetEvents() {
+ synchronized (deployments) {
+ return new ArrayList<>(facts.getAssetEvents());
}
-
- return null;
}
- public synchronized boolean isEmpty() {
- return rulesets.isEmpty();
+ public boolean isRunning() {
+ synchronized (deployments) {
+ return running;
+ }
}
- public void setAssetEventsConsumer(Consumer<AssetEvent> assetEventsConsumer) {
- this.assetEventsConsumer = assetEventsConsumer;
+ public boolean isError() {
+ synchronized (deployments) {
+ for (RulesetDeployment deployment : deployments.values()) {
+ if (deployment.status == COMPILATION_ERROR || deployment.getStatus() == EXECUTION_ERROR) {
+ return true;
+ }
+ }
+ return false;
+ }
}
- protected void setGlobal(String identifier, Object object) {
- try {
- knowledgeSession.setGlobal(identifier, object);
- } catch (Throwable t) {
- // Ignore, Drools complains if the DRL doesn't declare the global, but it works
+ public Throwable getError() {
+ synchronized (deployments) {
+ List<RulesetDeployment> deploymentsWithCompilationError = new ArrayList<>();
+ List<RulesetDeployment> deploymentsWithExecutionError = new ArrayList<>();
+ for (RulesetDeployment deployment : deployments.values()) {
+ if (deployment.getStatus() == COMPILATION_ERROR) {
+ deploymentsWithCompilationError.add(deployment);
+ } else if (deployment.getStatus() == EXECUTION_ERROR) {
+ deploymentsWithExecutionError.add(deployment);
+ }
+ }
+ if (deploymentsWithCompilationError.size() > 0 || deploymentsWithExecutionError.size() > 0) {
+ return new RuntimeException(
+ "Ruleset deployments have errors, failed compilation: "
+ + deploymentsWithCompilationError.size()
+ + ", failed execution: "
+ + deploymentsWithExecutionError.size()
+ );
+ }
+ return null;
}
}
/**
- * Adds the ruleset to the engine by first stopping the engine and
- * then deploying new rules and then restarting the engine.
- * <p>
- * If engine is in an error state (one of the rulesets failed to deploy)
- * then the engine will not restart, inspect then with {@link #isRunning()}
- * and {@link #isError()}.
+ * @return <code>true</code> if all rulesets are {@link RulesetDeployment.Status#DEPLOYED} and this engine can be started.
*/
- public synchronized void addRuleset(T ruleset, boolean forceUpdate) {
+ public boolean isDeployed() {
+ synchronized (deployments) {
+ return deployments.values().stream().allMatch(rd -> rd.getStatus() == DEPLOYED);
+ }
+ }
+
+ public void addRuleset(T ruleset) {
if (ruleset == null || ruleset.getRules() == null || ruleset.getRules().isEmpty()) {
// Assume it's a success if deploying an empty ruleset
LOG.finest("Ruleset is empty so no rules to deploy");
return;
}
- if (kfs == null) {
- initialiseEngine();
- }
-
- T existingRuleset = rulesets.get(ruleset.getId());
+ synchronized (deployments) {
+ RulesetDeployment deployment = deployments.get(ruleset.getId());
- if (!forceUpdate && existingRuleset != null && existingRuleset.getVersion() == ruleset.getVersion()) {
- LOG.fine("Ruleset version already deployed so ignoring");
- return;
- }
-
- if (isRunning()) {
stop();
- }
-
- // Check if ruleset is already deployed (maybe an older version)
- if (existingRuleset != null) {
- // Remove this old rules file
- kfs.delete("src/main/resources/" + ruleset.getId());
- //noinspection SuspiciousMethodCalls
- rulesets.remove(existingRuleset);
- updateRulesetsDebug();
- }
- LOG.info("Adding ruleset: " + ruleset);
-
- boolean addSuccessful = false;
- setError(null);
-
- try {
- // If the ruleset references a template asset, compile it as a template
- String drl = ruleset.getTemplateAssetId() != null
- ? compileTemplate(ruleset.getTemplateAssetId(), ruleset.getRules())
- : ruleset.getRules();
-
- LOG.finest("Final ruleset DRL: " + drl);
+ // Check if ruleset is already deployed (maybe an older version)
+ if (deployment != null) {
+ LOG.info("Removing ruleset deployment: " + ruleset);
+ deployments.remove(ruleset.getId());
+ updateDeploymentInfo();
+ }
- // ID will be unique within the scope of a rules engine as ruleset will all be of same type
- kfs.write("src/main/resources/" + ruleset.getId() + ".drl", drl);
+ deployment = new RulesetDeployment(ruleset.getId(), ruleset.getName(), ruleset.getVersion());
- // Unload the rules string from the ruleset we don't need it anymore and don't want it using memory
- ruleset.setRules(null);
- KieBuilder kieBuilder = kieServices.newKieBuilder(kfs).buildAll();
+ boolean compilationSuccessful = deployment.registerRules(ruleset, assetsFacade, usersFacade);
- if (kieBuilder.getResults().hasMessages(Message.Level.ERROR)) {
- Collection<Message> errors = kieBuilder.getResults().getMessages(Message.Level.ERROR);
- LOG.severe("Error in ruleset: " + ruleset);
- for (Message error : errors) {
- LOG.severe(error.getText());
+ if (!compilationSuccessful) {
+ // If any other ruleset is DEPLOYED in this scope, demote to READY
+ for (RulesetDeployment rd : deployments.values()) {
+ if (rd.getStatus() == DEPLOYED) {
+ rd.setStatus(READY);
+ }
}
- LOG.fine(drl);
- // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any
- kfs.delete("src/main/resources/" + ruleset.getId());
- } else {
- addSuccessful = true;
}
- } catch (Exception e) {
- LOG.log(Level.SEVERE, "Error in ruleset: " + ruleset, e);
- setError(e);
- // If compilation failed, remove rules from FileSystem so it won't fail on next pass here if any
- kfs.delete("src/main/resources/" + ruleset.getId());
- }
-
- if (!addSuccessful) {
- setError(new RuntimeException("Ruleset contains an error: " + ruleset));
-
- // Update status of each ruleset
- rulesets.forEach((id, rd) -> {
- if (rd.getDeploymentStatus() == Ruleset.DeploymentStatus.DEPLOYED) {
- rd.setDeploymentStatus(Ruleset.DeploymentStatus.READY);
- }
- });
- }
- // Add new ruleset
- ruleset.setDeploymentStatus(addSuccessful ? Ruleset.DeploymentStatus.DEPLOYED : Ruleset.DeploymentStatus.FAILED);
- rulesets.put(ruleset.getId(), ruleset);
- updateRulesetsDebug();
+ // Add new ruleset and set its status to either DEPLOYED or COMPILATION_ERROR
+ deployment.setStatus(compilationSuccessful ? DEPLOYED : COMPILATION_ERROR);
+ deployments.put(ruleset.getId(), deployment);
+ updateDeploymentInfo();
- if (addSuccessful) {
start();
}
}
- protected synchronized void removeRuleset(Ruleset ruleset) {
- if (kfs == null) {
- return;
- }
-
- T matchedRuleset = rulesets.get(ruleset.getId());
- if (matchedRuleset == null) {
- LOG.finer("Ruleset cannot be retracted as it was never deployed: " + ruleset);
- return;
- }
+ /**
+ * @return <code>true</code> if this rules engine has no deployments.
+ */
+ public boolean removeRuleset(Ruleset ruleset) {
+ synchronized (deployments) {
+ if (!deployments.containsKey(ruleset.getId())) {
+ LOG.finer("Ruleset cannot be retracted as it was never deployed: " + ruleset);
+ return deployments.size() == 0;
+ }
- if (isRunning()) {
stop();
- }
-
- // Remove this old rules file
- kfs.delete("src/main/resources/" + ruleset.getId());
- rulesets.remove(ruleset.getId());
- updateRulesetsDebug();
-
- // Update status of each ruleset
- boolean anyFailed = rulesets
- .values()
- .stream()
- .anyMatch(rd -> rd.getDeploymentStatus() == Ruleset.DeploymentStatus.FAILED);
-
- if (!anyFailed) {
- setError(null);
- rulesets.forEach((id, rd) -> {
- if (rd.getDeploymentStatus() == Ruleset.DeploymentStatus.READY) {
- rd.setDeploymentStatus(Ruleset.DeploymentStatus.DEPLOYED);
- }
- });
- }
-
- if (!isError() && !isEmpty()) {
- start();
- }
- }
-
- protected void initialiseEngine() {
- // Initialise
- kieServices = KieServices.Factory.get();
- KieModuleModel kieModuleModel = kieServices.newKieModuleModel();
-
- String versionId = getNextCounter().toString();
- releaseId = kieServices.newReleaseId("org.openremote", "openremote-kiemodule", versionId);
- KieBaseModel kieBaseModel = kieModuleModel.newKieBaseModel("OpenRemoteKModule");
-
- kieBaseModel
- .setDefault(true)
- .setEqualsBehavior(EqualityBehaviorOption.EQUALITY)
- .setEventProcessingMode(EventProcessingOption.STREAM)
- .newKieSessionModel("ksession1")
- .setDefault(true)
- .setType(KieSessionModel.KieSessionType.STATEFUL);
- kfs = kieServices.newKieFileSystem();
- kfs.generateAndWritePomXML(releaseId);
- kfs.writeKModuleXML(kieModuleModel.toXML());
-
- LOG.info("Initialised rules for deployment '" + getId() + "':" + kieBaseModel.toString());
- }
-
- protected synchronized void start() {
- if (isRunning()) {
- return;
- }
-
- if (isError()) {
- LOG.fine("Cannot start rules engine as an error occurred during initialisation");
- return;
- }
- if (isEmpty()) {
- LOG.finest("No rulesets loaded so nothing to start");
- return;
- }
-
- LOG.info("Starting: " + this);
+ deployments.remove(ruleset.getId());
+ updateDeploymentInfo();
- // Note each rule engine has its' own KieModule which are stored in a singleton register by drools
- // we need to ensure we get the right module here otherwise we could be using the wrong rules
- KieContainer kieContainer = kieServices.newKieContainer(releaseId);
+ // If there are no deployments with COMPILATION_ERROR, promote all which are READY to DEPLOYED
+ boolean anyDeploymentsHaveCompilationError = deployments
+ .values()
+ .stream()
+ .anyMatch(rd -> rd.getStatus() == COMPILATION_ERROR);
- KieSessionConfiguration kieSessionConfiguration = kieServices.newKieSessionConfiguration();
+ if (!anyDeploymentsHaveCompilationError) {
+ deployments.values().forEach(rd -> {
+ if (rd.getStatus() == READY) {
+ rd.setStatus(DEPLOYED);
+ }
+ });
+ }
- // Which clock to use ("pseudo" for testing, "realtime" otherwise)
- switch (timerService.getClock()) {
- case PSEUDO:
- kieSessionConfiguration.setOption(ClockTypeOption.get("pseudo"));
- break;
- default:
- kieSessionConfiguration.setOption(ClockTypeOption.get("realtime"));
+ if (deployments.size() > 0) {
+ start();
+ return false;
+ } else {
+ return true;
+ }
}
+ }
- try {
- knowledgeSession = kieContainer.newKieSession(kieSessionConfiguration);
-
- // If the pseudo clock is enabled (we run a test environment?) then set current
- // time on startup of session, as real time is used in offset calculations for
- // automatic event expiration in Drools (probably a design mistake)
- if (timerService.getClock() == TimerService.Clock.PSEUDO) {
- ((PseudoClockScheduler) knowledgeSession.getSessionClock())
- .setStartupTime(timerService.getCurrentTimeMillis());
+ public void start() {
+ synchronized (deployments) {
+ if (isRunning()) {
+ return;
}
- setGlobal("assets", assetsFacadeSupplier.get());
- setGlobal("users", usersFacadeSupplier.get());
- setGlobal("LOG", RULES_LOG);
-
- // TODO Still need this UTIL?
- setGlobal("util", UTIL);
-
- knowledgeSession.addEventListener(new RuleExecutionLogger(this::toString, RULES_LOG));
-
- AgendaEventListener eventListener = rulesEngineListeners != null ? rulesEngineListeners.apply(this) : null;
- if (eventListener != null) {
- knowledgeSession.addEventListener(eventListener);
+ if (!isDeployed()) {
+ LOG.fine("Cannot start rules engine, not all rulesets are status " + DEPLOYED);
+ return;
}
- knowledgeSession.addEventListener(new RuleRuntimeEventListener() {
- @Override
- public void objectInserted(ObjectInsertedEvent event) {
- RULES_LOG.finest("+++ On " + RulesEngine.this + ", fact inserted: " + event.getObject());
- }
-
- @Override
- public void objectUpdated(ObjectUpdatedEvent event) {
- RULES_LOG.finest("^^^ On " + RulesEngine.this + ", fact updated: " + event.getObject());
- }
-
- @Override
- public void objectDeleted(ObjectDeletedEvent event) {
- RULES_LOG.finest("--- On " + RulesEngine.this + ", fact deleted: " + event.getOldObject());
- }
- });
-
- // Start engine in active mode
- fireUntilHalt();
-
- // Insert initial asset states
- try {
- insertInitialAssetStates();
- } catch (Exception ex) {
- // This is called in a background timer thread, we must log here or the exception is swallowed
- LOG.log(Level.SEVERE, "On " + this + ", inserting initial asset states failed", ex);
- setError(ex);
- stop();
+ if (deployments.size() == 0) {
+ LOG.finest("No rulesets so nothing to start");
+ return;
}
+ LOG.info("Starting: " + this);
+ running = true;
+ fire();
+
// Start a background stats printer if INFO level logging is enabled
if (STATS_LOG.isLoggable(Level.INFO) || STATS_LOG.isLoggable(Level.FINEST)) {
if (STATS_LOG.isLoggable(Level.FINEST)) {
@@ -447,287 +280,165 @@ public class RulesEngine<T extends Ruleset> {
}
statsTimer = executorService.scheduleAtFixedRate(this::printSessionStats, 3, 30, TimeUnit.SECONDS);
}
- } catch (Exception ex) {
- LOG.log(Level.SEVERE, "On " + this + ", creating the knowledge session failed", ex);
- setError(ex);
- stop();
}
}
- protected synchronized void fireUntilHalt() {
- // Block a background thread
- runningFuture = executorService.getRulesExecutor().submit(() -> {
- boolean stoppedOnError = false;
- try {
- if (knowledgeSession != null) {
- knowledgeSession.fireUntilHalt();
- } else {
- LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", can't fire until halt, no knowledge session exists");
- }
- } catch (Exception ex) {
- // Errors in rule RHS
- LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules", ex);
- stoppedOnError = true;
- } finally {
- if (stoppedOnError) {
- // TODO This should be configurable, RHS should not throw exception in production?
- // Keep running if stopped firing because of a RHS error
- runningFuture.cancel(true);
- runningFuture = null;
- fireUntilHalt();
- }
- }
- });
- }
-
- protected synchronized void stop() {
- if (!isRunning()) {
- return;
- }
- LOG.info("Stopping: " + this);
+ public void fire() {
+ // Submit a task that fires the engine for all deployments
+ executorService.submit(() -> {
+ synchronized (deployments) {
- // Clear out fact handles because the session they belong to is gone
- synchronized (assetStates) {
- for (AssetState assetState : new HashSet<>(assetStates.keySet())) {
- if (assetStates.get(assetState) != null) {
- assetStates.put(assetState, null);
+ if (!running) {
+ return;
}
- }
- }
- if (knowledgeSession != null) {
- try {
- knowledgeSession.halt();
- knowledgeSession.dispose();
- knowledgeSession = null;
- LOG.fine("On " + this + ", knowledge session disposed");
-
- } finally {
- if (statsTimer != null) {
- statsTimer.cancel(true);
- statsTimer = null;
+ // Set the current clock
+ RulesClock clock = new RulesClock(timerService);
+ facts.setClock(clock);
+
+ // Remove any expired temporary facts
+ facts.removeExpiredTemporaryFacts();
+
+ // If we still have temporary facts and there is no firing scheduled
+ if (facts.hasTemporaryFacts() && eventsTimer == null && !disableTemporaryFactExpiration) {
+ // Schedule firing again so temporary facts can be expired
+ eventsTimer = executorService.schedule(
+ this::fire, AssetEvent.GUARANTEED_MIN_EXPIRATION_MILLIS, TimeUnit.MILLISECONDS
+ );
+ } else if (eventsTimer != null) {
+ // If we don't have temporary facts but there is a scheduled firing, cancel it
+ eventsTimer.cancel(true);
+ eventsTimer = null;
}
- runningFuture.cancel(true);
- runningFuture = null;
- }
- }
- }
- protected synchronized void insertInitialAssetStates() {
- synchronized (assetStates) {
- LOG.info("On " + this + ", inserting initial asset states: " + assetStates.size());
- for (AssetState assetState : new HashSet<>(assetStates.keySet())) {
- updateAssetState(assetState, true);
- }
- }
- }
+ for (RulesetDeployment deployment : deployments.values()) {
+ try {
+ RULES_LOG.fine("Firing rules @" + clock + " of: " + deployment);
- protected synchronized void updateAssetState(AssetState assetState) {
- updateAssetState(assetState, false);
- }
+ /* TODO Not sure if this is useful, it's too much info in most cases
+ // If full detail logging is enabled
+ if (RULES_LOG.isLoggable(Level.FINEST)) {
+ // Log asset states and events before firing (note that this will log at INFO)
+ facts.logFacts(RULES_LOG);
+ }
+ */
- protected synchronized void updateAssetState(AssetState assetState, boolean initialImport) {
- synchronized (assetStates) {
+ engine.fire(deployment.getRules(), facts);
- // Check if fact already exists using equals(), this will deduplicate asset state writes
- if (!initialImport && assetStates.containsKey(assetState)) {
- RULES_LOG.finest("On " + this + ", update is the same as existing, ignoring: " + assetState);
- return;
- }
+ } catch (Exception ex) {
+ LOG.log(Level.SEVERE, "On " + RulesEngine.this + ", error firing rules of: " + deployment, ex);
- RULES_LOG.finest("On " + this + ", updating: " + assetState);
+ deployment.setStatus(EXECUTION_ERROR);
+ deployment.setError(ex);
- // Do we have to remove an old fact first
- FactHandle oldFactHandle = null;
- if (!initialImport) {
- // Get the old asset state
- AssetState oldAssetState = assetStates.keySet()
- .stream()
- .filter(au -> au.attributeRefsEqual(assetState))
- .findFirst()
- .orElse(null);
+ // TODO We always stop on any error, good idea?
+ // TODO This does not include RHS runtime errors, see RuleFacts.onFailure()
+ stop();
- // Remove the old asset state and get its fact handle, so the fact can be removed too
- oldFactHandle = oldAssetState != null ? assetStates.remove(oldAssetState) : null;
+ // TODO We skip any other deployment when we hit the first error, good idea?
+ break;
+ }
+ }
}
+ });
+ }
+ public void stop() {
+ synchronized (deployments) {
if (!isRunning()) {
- RULES_LOG.finest("On " + this + ", engine is in error state or not running, storing for later update: " + assetState);
- assetStates.put(assetState, null);
return;
}
-
- deleteAndInsertInKnowledgeSession(oldFactHandle, assetState, factHandle -> {
- // Store the new asset state and the fact handle
- synchronized (assetStates) {
- assetStates.put(assetState, factHandle);
- }
- });
- }
- }
-
- protected synchronized void deleteAndInsertInKnowledgeSession(FactHandle oldFactHandle,
- AssetState assetState,
- Consumer<FactHandle> factHandleConsumer) {
- // Atomically delete the old fact and insert a new fact, this adds to asynchronous work queue of rules engine thread
- knowledgeSession.submit(session -> {
- if (oldFactHandle != null) {
- session.delete(oldFactHandle);
+ LOG.info("Stopping: " + this);
+ if (eventsTimer != null) {
+ eventsTimer.cancel(true);
+ eventsTimer = null;
}
- FactHandle factHandle = session.insert(assetState);
- if (factHandleConsumer != null) {
- factHandleConsumer.accept(factHandle);
+ if (statsTimer != null) {
+ statsTimer.cancel(true);
+ statsTimer = null;
}
- });
+ running = false;
+ }
}
- protected synchronized void retractAssetState(AssetState assetState) {
- synchronized (assetStates) {
- RULES_LOG.finest("On " + this + ", retracting: " + assetState);
- // If there already is a fact in working memory for this attribute then delete it
- AssetState update = assetStates.keySet()
- .stream()
- .filter(au -> au.attributeRefsEqual(assetState))
- .findFirst()
- .orElse(null);
-
- // Always remove from asset states
- FactHandle factHandle = update != null ? assetStates.remove(update) : null;
-
- if (factHandle != null) {
- if (isRunning()) {
- try {
- // ... retract it from working memory ...
- knowledgeSession.delete(factHandle);
- } catch (Exception e) {
- RULES_LOG.warning("On " + this + ", failed to retract fact: " + update);
- }
- }
+ public void updateFact(AssetState assetState, boolean fireImmediately) {
+ synchronized (deployments) {
+ RULES_LOG.finest("Fact change (UPDATE): " + assetState + " - on: " + this);
+ facts.getAssetStates().remove(assetState);
+ facts.getAssetStates().add(assetState);
+ if (fireImmediately) {
+ fire();
}
}
}
- protected synchronized void insertAssetEvent(long expirationOffset, AssetEvent assetEvent) {
- if (!isRunning()) {
- RULES_LOG.fine("On " + this + ", engine is in error state or not running, ignoring: " + assetEvent);
- return;
- }
- FactHandle factHandle = knowledgeSession.insert(assetEvent);
- if (factHandle != null) {
- scheduleExpiration(assetEvent, factHandle, expirationOffset);
- }
- if (assetEventsConsumer != null) {
- assetEventsConsumer.accept(assetEvent);
+ public void removeFact(AssetState assetState) {
+ synchronized (deployments) {
+ RULES_LOG.finest("Fact change (DELETE): " + assetState + " - on: " + this);
+ synchronized (deployments) {
+ facts.getAssetStates().remove(assetState);
+ fire();
+ }
}
}
- /**
- * Use the internal scheduling of Drools to expire events, so we can coordinate with the internal clock.
- * Yes, this is a hack.
- */
- protected void scheduleExpiration(AssetEvent assetEvent, FactHandle factHandle, long expirationOffset) {
- if (!isRunning())
- return;
- InternalSchedulerService sessionScheduler = knowledgeSession.getSessionClock();
- JobHandle jobHandle = new JDKTimerService.JDKJobHandle(assetEvent.getId().hashCode());
- class AssetEventExpireJobContext implements JobContext {
- public JobHandle handle;
-
- @Override
- public void setJobHandle(JobHandle jobHandle) {
- this.handle = jobHandle;
- }
-
- @Override
- public JobHandle getJobHandle() {
- return handle;
- }
-
- @Override
- public InternalWorkingMemory getWorkingMemory() {
- return null;
- }
+ public void insertFact(AssetEvent assetEvent) {
+ synchronized (deployments) {
+ RULES_LOG.finest("Fact change (INSERT): " + assetEvent + " - on: " + this);
+ facts.getAssetEvents().add(assetEvent);
+ fire();
}
- TimerJobInstance timerJobInstance = new DefaultTimerJobInstance(
- ctx -> {
- RULES_LOG.finest("On " + RulesEngine.this + ", fact expired, deleting: " + assetEvent);
- synchronized (RulesEngine.this) {
- knowledgeSession.delete(factHandle);
- }
- },
- new AssetEventExpireJobContext(),
- new PointInTimeTrigger(knowledgeSession.getSessionClock().getCurrentTime() + expirationOffset, null, null),
- jobHandle,
- sessionScheduler
- );
- sessionScheduler.internalSchedule(timerJobInstance);
-
}
- protected String compileTemplate(String templateAssetId, String rules) {
- ServerAsset templateAsset = assetStorageService.find(templateAssetId, true);
+ /* TODO
+ protected String compileTemplate(String templateAssetId, String rules) {
+ ServerAsset templateAsset = assetStorageService.find(templateAssetId, true);
- if (templateAsset == null)
- throw new IllegalStateException("Template asset not found: " + templateAssetId);
+ if (templateAsset == null)
+ throw new IllegalStateException("Template asset not found: " + templateAssetId);
- List<TemplateFilter> filters = templateAsset.getAttributesStream()
- .filter(isAttributeTypeEqualTo(AttributeType.RULES_TEMPLATE_FILTER))
- .map(attribute -> new Pair<>(attribute.getName(), attribute.getValue()))
- .filter(pair -> pair.key.isPresent() && pair.value.isPresent())
- .map(pair -> new Pair<>(pair.key.get(), pair.value.get()))
- .map(pair -> TemplateFilter.fromModelValue(pair.key, pair.value))
- .filter(Optional::isPresent)
- .map(Optional::get)
- .collect(Collectors.toList());
+ List<TemplateFilter> filters = templateAsset.getAttributesStream()
+ .filter(isAttributeTypeEqualTo(AttributeType.RULES_TEMPLATE_FILTER))
+ .map(attribute -> new Pair<>(attribute.getName(), attribute.getValue()))
+ .filter(pair -> pair.key.isPresent() && pair.value.isPresent())
+ .map(pair -> new Pair<>(pair.key.get(), pair.value.get()))
+ .map(pair -> TemplateFilter.fromModelValue(pair.key, pair.value))
+ .filter(Optional::isPresent)
+ .map(Optional::get)
+ .collect(Collectors.toList());
- LOG.fine("Rendering rules template with filters: " + filters);
+ LOG.fine("Rendering rules template with filters: " + filters);
- ObjectDataCompiler converter = new ObjectDataCompiler();
- InputStream is = new ByteArrayInputStream(rules.getBytes(StandardCharsets.UTF_8));
- return converter.compile(filters, is);
- }
+ ObjectDataCompiler converter = new ObjectDataCompiler();
+ InputStream is = new ByteArrayInputStream(rules.getBytes(StandardCharsets.UTF_8));
+ return converter.compile(filters, is);
+ }
+ */
- protected synchronized void updateRulesetsDebug() {
- rulesetsDebug = Arrays.toString(rulesets.values().stream().map(rd ->
- rd.getClass().getSimpleName()
- + " - "
- + rd.getName()
- + ": "
- + rd.getDeploymentStatus()).toArray(String[]::new)
+ protected void updateDeploymentInfo() {
+ deploymentInfo = Arrays.toString(
+ deployments.values().stream()
+ .map(RulesetDeployment::toString)
+ .toArray(String[]::new)
);
}
- protected synchronized void printSessionStats() {
- if (knowledgeSession == null) {
- return;
- }
- Collection<?> assetStateFacts = knowledgeSession.getObjects(new ClassObjectFilter(AssetState.class));
- Collection<?> assetEventFacts = knowledgeSession.getObjects(new ClassObjectFilter(AssetEvent.class));
- Collection<?> customFacts = knowledgeSession.getObjects(object ->
- !AssetState.class.isAssignableFrom(object.getClass()) && !AssetEvent.class.isAssignableFrom(object.getClass())
- );
- long total = assetStateFacts.size() + assetEventFacts.size() + customFacts.size();
- STATS_LOG.info("On " + this + ", in memory facts are Total: " + total
- + ", AssetState: " + assetStateFacts.size()
- + ", AssetEvent: " + assetEventFacts.size()
- + ", Custom: " + customFacts.size());
-
- /* TODO Remove internal debug
- STATS_LOG.info("On " + this + ", managed are: "
- + "AssetState (no fact handle): " + assetStates.entrySet().stream().filter(entry -> entry.getValue() == null).count()
- + ", AssetState (with fact handle): " + assetStates.entrySet().stream().filter(entry -> entry.getValue() != null).count());
- */
-
- // Additional details if FINEST is enabled
- if (STATS_LOG.isLoggable(Level.FINEST)) {
- for (Object assetStateFact : assetStateFacts) {
- STATS_LOG.finest("On " + this + ", fact: " + assetStateFact);
- }
- for (Object assetEventFact : assetEventFacts) {
- STATS_LOG.finest("On " + this + ", fact: " + assetEventFact);
- }
- for (Object customFact : customFacts) {
- STATS_LOG.finest("On " + this + ", fact: " + customFact);
+ protected void printSessionStats() {
+ synchronized (deployments) {
+ Collection<AssetState> assetStateFacts = facts.getAssetStates();
+ Collection<AssetEvent> assetEventFacts = facts.getAssetEvents();
+ Map<String, Object> namedFacts = facts.getNamedFacts();
+ Collection<Object> anonFacts = facts.getAnonymousFacts();
+ long total = assetStateFacts.size() + assetEventFacts.size() + namedFacts.size() + anonFacts.size();
+ STATS_LOG.info("On " + this + ", in memory facts are Total: " + total
+ + ", AssetState: " + assetStateFacts.size()
+ + ", AssetEvent: " + assetEventFacts.size()
+ + ", Named: " + namedFacts.size()
+ + ", Anonymous: " + anonFacts.size());
+
+ // Additional details if FINEST is enabled
+ if (STATS_LOG.isLoggable(Level.FINEST)) {
+ facts.logFacts(STATS_LOG);
}
}
}
@@ -735,10 +446,10 @@ public class RulesEngine<T extends Ruleset> {
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "id='" + id + '\'' +
+ "realmId='" + realmId + '\'' +
+ ", assetId='" + assetId + '\'' +
", running='" + isRunning() + '\'' +
- ", error='" + error + '\'' +
- ", rulesets='" + rulesetsDebug + '\'' +
+ ", deployments='" + deploymentInfo + '\'' +
'}';
}
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
new file mode 100644
index 000000000..351825df0
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesFacts.java
@@ -0,0 +1,481 @@
+/*
+ * 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.jeasy.rules.api.*;
+import org.openremote.model.asset.AssetEvent;
+import org.openremote.model.asset.AssetQuery;
+import org.openremote.model.asset.AssetState;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.rules.Assets;
+import org.openremote.model.rules.TemporaryFact;
+import org.openremote.model.util.TimeUtil;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
+
+import java.util.*;
+import java.util.function.Predicate;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+public class RulesFacts extends Facts implements RuleListener, RulesEngineListener {
+
+ // Loop detection
+ // TODO Better way than tracking rule trigger count? Max trigger could be a configurable multiple of facts count?
+ public static final int MAX_RULES_TRIGGERED_PER_EXECUTION = 100;
+
+ public static final String CLOCK = "INTERNAL_CLOCK";
+ public static final String ASSET_STATES = "INTERNAL_ASSET_STATES";
+ public static final String ASSET_EVENTS = "INTERNAL_ASSET_EVENTS";
+ public static final String EXECUTION_VARS = "INTERNAL_EXECUTION_VAR";
+ public static final String ANONYMOUS_FACTS = "ANONYMOUS_FACTS";
+
+ final protected Assets assetsFacade;
+ final protected Object loggingContext;
+ final protected Logger LOG;
+
+ public RulesClock clock;
+
+ protected int triggerCount;
+
+ public RulesFacts(Assets assetsFacade, Object loggingContext, Logger logger) {
+ this.assetsFacade = assetsFacade;
+ this.loggingContext = loggingContext;
+ this.LOG = logger;
+
+ asMap().put(ASSET_STATES, new HashSet<AssetState>());
+ asMap().put(ASSET_EVENTS, new ArrayList<AssetEvent>());
+ asMap().put(EXECUTION_VARS, new HashMap<String, Object>());
+ asMap().put(ANONYMOUS_FACTS, new HashSet<>());
+ }
+
+ public void setClock(RulesClock clock) {
+ this.clock = clock;
+ asMap().put(CLOCK, clock);
+ }
+
+ public RulesClock getClock() {
+ return clock;
+ }
+
+ @SuppressWarnings("unchecked")
+ public Set<AssetState> getAssetStates() {
+ return (Set<AssetState>) get(ASSET_STATES);
+ }
+
+ @SuppressWarnings("unchecked")
+ public List<AssetEvent> getAssetEvents() {
+ return (List<AssetEvent>) get(ASSET_EVENTS);
+ }
+
+ @SuppressWarnings("unchecked")
+ public Set<Object> getAnonymousFacts() {
+ return (Set<Object>) get(ANONYMOUS_FACTS);
+ }
+
+ public Map<String, Object> getNamedFacts() {
+ return asMap().entrySet().stream().filter(entry ->
+ !entry.getKey().equals(CLOCK)
+ && !entry.getKey().equals(ASSET_STATES)
+ && !entry.getKey().equals(ASSET_EVENTS)
+ && !entry.getKey().equals(EXECUTION_VARS)
+ && !entry.getKey().equals(ANONYMOUS_FACTS)
+ ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+ }
+
+ public Stream<Object> getAllFacts() {
+ return
+ Stream.concat(
+ getNamedFacts().values().stream(),
+ Stream.concat(
+ getAnonymousFacts().stream(),
+ Stream.concat(
+ getAssetStates().stream(),
+ getAssetEvents().stream()
+ )
+ )
+ );
+ }
+
+ @SuppressWarnings("unchecked")
+ public Map<String, Object> getVars() {
+ return (Map<String, Object>) get(EXECUTION_VARS);
+ }
+
+ public RulesFacts bind(String var, Object value) {
+ getVars().put(var, value);
+ return this;
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> T bound(String var) {
+ return (T) getVars().get(var);
+ }
+
+ @Override
+ public RulesFacts put(String name, Object fact) {
+ switch (name) {
+ case ANONYMOUS_FACTS:
+ case ASSET_EVENTS:
+ case ASSET_STATES:
+ case EXECUTION_VARS:
+ case CLOCK:
+ throw new IllegalArgumentException("Reserved internal fact name: " + name);
+ }
+ super.put(name, fact);
+ return this;
+ }
+
+ public RulesFacts put(Object o) {
+ getAnonymousFacts().remove(o);
+ getAnonymousFacts().add(o);
+ return this;
+ }
+
+ public RulesFacts putTemporary(String expires, Object value) {
+ return putTemporary(TimeUtil.parseTimeString(expires), value);
+ }
+
+ public RulesFacts putTemporary(double expires, Object value) {
+ return putTemporary((long) expires, value);
+ }
+
+ public RulesFacts putTemporary(long expires, Object value) {
+ getAnonymousFacts().add(new TemporaryFactImpl<>((long) getClock().getTimestamp(), expires, value));
+ return this;
+ }
+
+ public RulesFacts putTemporary(String name, String expires, Object value) {
+ return putTemporary(name, TimeUtil.parseTimeString(expires), value);
+ }
+
+ public RulesFacts putTemporary(String name, double expires, Object value) {
+ return putTemporary(name, (long) expires, value);
+ }
+
+ public RulesFacts putTemporary(String name, long expires, Object value) {
+ put(name, new TemporaryFactImpl<>((long) getClock().getTimestamp(), expires, value));
+ return this;
+ }
+
+ public boolean hasTemporaryFacts() {
+ return getAssetEvents().size() > 0
+ || getNamedFacts().entrySet().stream().anyMatch(entry -> entry.getValue() instanceof TemporaryFact)
+ || getAnonymousFacts().stream().anyMatch(fact -> fact instanceof TemporaryFact);
+ }
+
+ @Override
+ public RulesFacts remove(String name) {
+ super.remove(name);
+ return this;
+ }
+
+ public RulesFacts remove(Object fact) {
+ getAnonymousFacts().removeIf(anonFact -> {
+ if (anonFact instanceof TemporaryFactImpl) {
+ anonFact = ((TemporaryFactImpl) anonFact).getFact();
+ }
+ return anonFact.equals(fact);
+ });
+ return this;
+ }
+
+ @Override
+ public void beforeEvaluate(Rules rules, Facts facts) {
+ triggerCount = 0;
+ }
+
+ @Override
+ public void afterExecute(Rules rules, Facts facts) {
+ LOG.fine("Rules triggered: " + triggerCount);
+ triggerCount = 0;
+ }
+
+ @Override
+ public boolean beforeEvaluate(Rule rule, Facts facts) {
+ // Clear bound variables so each rule can make its own bindings to
+ // transport values between LHS and RHS
+ getVars().clear();
+
+ logRule(rule, "Rule candidate", true, false);
+
+ return true;
+ }
+
+ @Override
+ public void afterEvaluate(Rule rule, Facts facts, boolean evaluationResult) {
+ if (evaluationResult) {
+ triggerCount++;
+ if (triggerCount >= MAX_RULES_TRIGGERED_PER_EXECUTION) {
+ throw new IllegalStateException(
+ "Possible rules loop detected, exceeded max trigger count of "
+ + MAX_RULES_TRIGGERED_PER_EXECUTION
+ + " on " + loggingContext + " for rule: " + rule.getName()
+ );
+ }
+ }
+ }
+
+ @Override
+ public void beforeExecute(Rule rule, Facts facts) {
+ logRule(rule, "Rule triggered", false, true);
+ }
+
+ @Override
+ public void onSuccess(Rule rule, Facts facts) {
+ logRule(rule, "Rule executed", true, false);
+ }
+
+ @Override
+ public 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
+ );
+ }
+
+ @SuppressWarnings("unchecked")
+ protected <T> Optional<T> matchFact(Object fact, Class<T> factType, Predicate<T> predicate) {
+ if (fact == null)
+ return Optional.empty();
+ if (fact instanceof TemporaryFactImpl) {
+ TemporaryFactImpl temporaryFact = (TemporaryFactImpl) fact;
+ fact = temporaryFact.getFact();
+ }
+ Optional<T> result = Optional.empty();
+ if (!factType.isAssignableFrom(fact.getClass())) {
+ result = Optional.empty();
+ } else if (predicate.test((T) fact)) {
+ result = Optional.of((T) fact);
+ }
+ return result;
+ }
+
+ public <T> Optional<T> matchFirst(String name) {
+ return matchFirst(name, fact -> true);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> Optional<T> matchFirst(String name, Predicate<T> predicate) {
+ return matchFirst(name, (Class<T>) Object.class, predicate);
+ }
+
+ public <T> Optional<T> matchFirst(String name, Class<T> factType, Predicate<T> predicate) {
+ return matchFact(get(name), factType, predicate);
+ }
+
+ public <T> Optional<T> matchFirst(Predicate<T> predicate) {
+ return match(predicate).findFirst();
+ }
+
+ public <T> Optional<T> matchFirst(Class<T> factType) {
+ return match(factType).findFirst();
+ }
+
+ public <T> Optional<T> matchFirst(Class<T> factType, Predicate<T> predicate) {
+ return match(factType, predicate).findFirst();
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> Stream<T> match(Predicate<T> predicate) {
+ return match((Class<T>) Object.class, predicate);
+ }
+
+ public <T> Stream<T> match(Class<T> factType) {
+ return match(factType, fact -> true);
+ }
+
+ @SuppressWarnings("unchecked")
+ public <T> Stream<T> match(Class<T> factType, Predicate<T> predicate) {
+ return getAllFacts()
+ .filter(fact -> matchFact(fact, factType, predicate).isPresent())
+ .map(fact -> {
+ if (fact instanceof TemporaryFactImpl) {
+ return ((TemporaryFactImpl) fact).getFact();
+ }
+ return fact;
+ })
+ .map(fact -> (T) fact);
+ }
+
+ public Optional<AssetState> matchFirstAssetState(AssetQuery assetQuery) {
+ return matchAssetState(assetQuery).findFirst();
+ }
+
+ public Stream<AssetState> matchAssetState(AssetQuery assetQuery) {
+ return getAssetStates().stream().filter(fact -> matchFact(fact, AssetState.class, assetQuery::test).isPresent());
+ }
+
+ public Optional<AssetEvent> matchFirstAssetEvent(AssetQuery assetQuery) {
+ return matchAssetEvent(assetQuery).findFirst();
+ }
+
+ public Stream<AssetEvent> matchAssetEvent(AssetQuery assetQuery) {
+ return getAssetEvents().stream().filter(fact -> matchFact(fact, AssetEvent.class, assetQuery::test).isPresent());
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName, Value value) {
+ return invalidateAssetStateAndDispatch(assetId, attributeName, value);
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName) {
+ return invalidateAssetStateAndDispatch(assetId, attributeName, null);
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName, String value) {
+ return updateAssetState(assetId, attributeName, Values.create(value));
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName, double value) {
+ return updateAssetState(assetId, attributeName, Values.create(value));
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName, boolean value) {
+ return updateAssetState(assetId, attributeName, Values.create(value));
+ }
+
+ public RulesFacts updateAssetState(String assetId, String attributeName, AttributeExecuteStatus status) {
+ 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) {
+ LOG.finest("Fact change (INTERNAL DELETE): " + assetState + " - on: " + loggingContext);
+ }
+ 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 RulesFacts removeExpiredTemporaryFacts() {
+ long currentTimestamp = (long) getClock().getTimestamp();
+ getAssetEvents().removeIf(event -> event.isExpired(currentTimestamp));
+ asMap().entrySet().removeIf(entry ->
+ !entry.getKey().equals(CLOCK)
+ && !entry.getKey().equals(ASSET_STATES)
+ && !entry.getKey().equals(ASSET_EVENTS)
+ && !entry.getKey().equals(EXECUTION_VARS)
+ && !entry.getKey().equals(ANONYMOUS_FACTS)
+ && (entry.getValue() instanceof TemporaryFact && ((TemporaryFact) entry.getValue()).isExpired(currentTimestamp))
+ );
+ getAnonymousFacts().removeIf(fact -> {
+ if (fact instanceof TemporaryFact) {
+ TemporaryFact temporaryFact = (TemporaryFact) fact;
+ return temporaryFact.isExpired((long) getClock().getTimestamp());
+ }
+ return false;
+ });
+ return this;
+ }
+
+ public boolean logFacts(Logger logger) {
+ boolean haveLog = false;
+ if (getAllFacts().count() > 0) {
+ logger.info("--------------------------------- CLOCK ---------------------------------");
+ LOG.info(getClock().toString());
+ haveLog = true;
+ }
+
+ List<AssetState> sortedAssetStates = new ArrayList<>(getAssetStates());
+ sortedAssetStates.sort(Comparator.naturalOrder());
+ if (sortedAssetStates.size() > 0) {
+ logger.info("--------------------------------- ASSET STATES (" + sortedAssetStates.size() + ") ---------------------------------");
+ for (AssetState assetState : sortedAssetStates) {
+ logger.info(assetState.toString());
+ }
+ haveLog = true;
+ }
+ List<AssetEvent> sortedAssetEvents = new ArrayList<>(getAssetEvents());
+ if (sortedAssetEvents.size() > 0) {
+ logger.info("--------------------------------- ASSET EVENTS (" + sortedAssetEvents.size() + ") ---------------------------------");
+ sortedAssetEvents.sort(Comparator.naturalOrder());
+ for (AssetEvent assetEvent : sortedAssetEvents) {
+ logger.info(assetEvent.toString());
+ }
+ haveLog = true;
+ }
+ Map<String, Object> namedFacts = getNamedFacts();
+ List<String> names = new ArrayList<>(namedFacts.keySet());
+ names.sort(Comparator.naturalOrder());
+ if (names.size() > 0) {
+ logger.info("--------------------------------- NAMED FACTS (" + names.size() + ") ---------------------------------");
+ for (String name: names) {
+ logger.info(String.format("%s => %s", name, namedFacts.get(name)));
+ }
+ haveLog = true;
+ }
+ if (getAnonymousFacts().size() > 0) {
+ logger.info("--------------------------------- ANONYMOUS FACTS (" + getAnonymousFacts().size() + ") ---------------------------------");
+ for (Object o : getAnonymousFacts()) {
+ logger.info(String.format("%s", o));
+ }
+ haveLog = true;
+ }
+ return haveLog;
+ }
+
+ public boolean logVars(Logger logger) {
+ boolean haveLog = false;
+ List<String> sortedVars = new ArrayList<>(getVars().keySet());
+ sortedVars.sort(Comparator.naturalOrder());
+ if (sortedVars.size() > 0) {
+ logger.info("--------------------------------- BOUND VARIABLES (" + sortedVars.size() + ") ---------------------------------");
+ for (String var : sortedVars) {
+ logger.info(String.format("%s => %s", var, getVars().get(var)));
+ }
+ haveLog = true;
+ }
+ return haveLog;
+ }
+
+ protected void logRule(Rule rule, String msg, boolean logFacts, boolean logVars) {
+ String ruleName = rule.getName();
+ if (ruleName.startsWith("-") && LOG.isLoggable(Level.INFO)) {
+ LOG.log(Level.INFO,
+ String.format("*** %s: %s - on %s", msg, ruleName, loggingContext)
+ );
+ }
+ if (ruleName.startsWith("--") && LOG.isLoggable(Level.INFO)) {
+ boolean haveLog = false;
+ if (logFacts)
+ haveLog = logFacts(LOG);
+ if (logVars)
+ haveLog = haveLog || logVars(LOG);
+ if (haveLog) {
+ LOG.info("------------------------------------------------------------------------------");
+ }
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesProvider.java b/manager/src/main/java/org/openremote/manager/rules/RulesProvider.java
deleted file mode 100644
index 7a5de9205..000000000
--- a/manager/src/main/java/org/openremote/manager/rules/RulesProvider.java
+++ /dev/null
@@ -1,14 +0,0 @@
-package org.openremote.manager.rules;
-
-import org.kie.api.KieServices;
-import org.kie.api.io.Resource;
-import org.kie.api.runtime.conf.ClockTypeOption;
-
-import java.util.stream.Stream;
-
-public interface RulesProvider {
-
- Stream<Resource> getResources(KieServices kieServices);
-
- ClockTypeOption getClockType();
-}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 05452398a..d8c487584 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -20,8 +20,6 @@
package org.openremote.manager.rules;
import org.apache.camel.builder.RouteBuilder;
-import org.drools.core.base.evaluators.TimeIntervalParser;
-import org.kie.api.event.rule.AgendaEventListener;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.message.MessageBrokerSetupService;
@@ -36,7 +34,6 @@ 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.security.Tenant;
import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeType;
@@ -44,17 +41,18 @@ 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 org.openremote.model.security.Tenant;
import org.openremote.model.util.Pair;
import org.openremote.model.value.ObjectValue;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Consumer;
-import java.util.function.Function;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
+import static java.util.logging.Level.FINEST;
import static org.openremote.container.persistence.PersistenceEvent.PERSISTENCE_TOPIC;
import static org.openremote.container.util.MapAccess.getString;
import static org.openremote.manager.asset.AssetRoute.isPersistenceEventForEntityType;
@@ -63,7 +61,7 @@ import static org.openremote.model.asset.AssetAttribute.attributesFromJson;
import static org.openremote.model.asset.AssetAttribute.getAddedOrModifiedAttributes;
/**
- * Responsible for creating Drools knowledge sessions for the rulesets
+ * Responsible for creating {@link RulesEngine}s for the rulesets
* and processing {@link AssetState} and {@link AssetEvent} messages.
* <p>
* Each message is processed in the following order:
@@ -82,8 +80,6 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
public static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";
public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";
- public static final String ID_GLOBAL_RULES_ENGINE = "GLOBAL";
-
protected TimerService timerService;
protected ManagerExecutorService executorService;
protected PersistenceService persistenceService;
@@ -92,18 +88,16 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected AssetStorageService assetStorageService;
protected NotificationService notificationService;
protected AssetProcessingService assetProcessingService;
+
protected RulesEngine<GlobalRuleset> globalEngine;
protected final Map<String, RulesEngine<TenantRuleset>> tenantEngines = new HashMap<>();
protected final Map<String, RulesEngine<AssetRuleset>> assetEngines = new HashMap<>();
protected String[] activeTenantIds;
- // For tests
- protected Function<RulesEngine, AgendaEventListener> rulesEngineListeners;
-
// Keep global list of asset states that have been pushed to any engines
// The objects are already in memory inside the rule engines but keeping them
// here means we can quickly insert facts into newly started engines
- protected List<AssetState> assetStates = new ArrayList<>();
+ protected Set<AssetState> assetStates = new HashSet<>();
protected String configEventExpires;
@@ -185,7 +179,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
AssetState assetState = new AssetState(asset, ruleAttribute, AttributeEvent.Source.INTERNAL);
// Set the status to completed already so rules cannot interfere with this initial insert
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
- updateAssetState(assetState, true);
+ updateAssetState(assetState, true, true);
});
});
}
@@ -193,12 +187,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void stop(Container container) throws Exception {
synchronized (assetEngines) {
- assetEngines.forEach((assetId, deployment) -> deployment.stop());
+ assetEngines.forEach((assetId, rulesEngine) -> rulesEngine.stop());
assetEngines.clear();
}
synchronized (tenantEngines) {
- tenantEngines.forEach((realm, deployment) -> deployment.stop());
+ tenantEngines.forEach((realm, rulesEngine) -> rulesEngine.stop());
tenantEngines.clear();
}
@@ -211,11 +205,23 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void accept(AssetState assetState) {
// We might process two facts for a single attribute update, if that is what the user wants
+
+ // First as asset state
if (assetState.getAttribute().isRuleState()) {
- updateAssetState(assetState, false);
+ updateAssetState(
+ assetState,
+ false, // Don't skip the error check on the rules engines
+ !assetState.getAttribute().isRuleEvent() // If it's not a rule event, fire immediately
+ );
}
- if (assetState.getAttribute().isRuleEvent()) {
- process(new AssetEvent(assetState));
+
+ // Then as asset event (if there wasn't an error), this will also fire the rules engines
+ if (assetState.getProcessingStatus() == AssetState.ProcessingStatus.CONTINUE
+ && assetState.getAttribute().isRuleEvent()) {
+ process(new AssetEvent(
+ assetState,
+ assetState.getAttribute().getRuleEventExpires().orElse(configEventExpires)
+ ));
}
}
@@ -231,30 +237,26 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
if (wasEnabled) {
- // Remove tenant deployment for this tenant if it exists
- RulesEngine<TenantRuleset> tenantDeployment = tenantEngines.get(tenant.getId());
- if (tenantDeployment != null) {
- // Use a copy of the list to avoid concurrent modification problems in retract
- new ArrayList<>(Arrays.asList(tenantDeployment.getAllRulesets()))
- .stream().map(rs -> (TenantRuleset) rs)
- .forEach(this::undeployTenantRuleset);
+ // Remove tenant rules engine for this tenant if it exists
+ RulesEngine<TenantRuleset> tenantRulesEngine = tenantEngines.get(tenant.getId());
+ if (tenantRulesEngine != null) {
+ tenantRulesEngine.stop();
+ tenantEngines.remove(tenant.getId());
}
- // Remove any asset deployments for assets in this realm
- // Use a copy of the list to avoid concurrent modification problems in retract
- new ArrayList<>(assetEngines.values()).stream().flatMap(
- assetRulesEngine -> Arrays.stream(assetRulesEngine.getAllRulesets())
- ).map(rs -> (AssetRuleset) rs)
- .filter(ruleset -> ruleset.getRealmId().equals(tenant.getId()))
- .forEach(this::undeployAssetRuleset);
+ // Remove any asset rules engines for assets in this realm
+ assetEngines.values().stream()
+ .filter(re -> tenant.getId().equals(re.getRealmId()))
+ .forEach(RulesEngine::stop);
+ assetEngines.entrySet().removeIf(entry -> tenant.getId().equals(entry.getValue().getRealmId()));
} else {
- // Create tenant deployment for this tenant if it has any rulesets
+ // Create tenant rules engines for this tenant if it has any rulesets
rulesetStorageService
.findEnabledTenantRulesets(tenant.getId())
.forEach(this::deployTenantRuleset);
- // Create any asset deployments for assets in this realm that have rulesets
+ // Create any asset rules engines for assets in this realm that have rulesets
deployAssetRulesets(rulesetStorageService.findEnabledAssetRulesets(tenant.getId()));
}
}
@@ -284,7 +286,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Set the status to completed already so rules cannot interfere with this initial insert
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), inserting fact: " + assetState);
- updateAssetState(assetState, true);
+ updateAssetState(assetState, true, true);
});
break;
@@ -330,7 +332,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Set the status to completed already so rules cannot interfere with this initial insert
assetState.setProcessingStatus(AssetState.ProcessingStatus.COMPLETED);
LOG.fine("Asset was persisted (" + persistenceEvent.getCause() + "), updating: " + assetState);
- updateAssetState(assetState, true);
+ updateAssetState(assetState, true, true);
});
break;
@@ -374,19 +376,13 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
if (!oldTemplateFilterAttributes.isEmpty() || !newTemplateFilterAttributes.isEmpty()) {
rulesetStorageService.findTemplatedAssetRulesets(asset.getRealmId(), asset.getId())
- .forEach(assetRuleset -> {
- processRulesetChange(assetRuleset, persistenceEvent.getCause());
- });
+ .forEach(assetRuleset -> processRulesetChange(assetRuleset, persistenceEvent.getCause()));
rulesetStorageService.findTemplatedTenantRulesets(asset.getRealmId(), asset.getId())
- .forEach(tenantRuleset -> {
- processRulesetChange(tenantRuleset, persistenceEvent.getCause());
- });
+ .forEach(tenantRuleset -> processRulesetChange(tenantRuleset, persistenceEvent.getCause()));
rulesetStorageService.findTemplatedGlobalRulesets(asset.getId())
- .forEach(globalRuleset -> {
- processRulesetChange(globalRuleset, persistenceEvent.getCause());
- });
+ .forEach(globalRuleset -> processRulesetChange(globalRuleset, persistenceEvent.getCause()));
}
}
}
@@ -405,20 +401,22 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
RulesEngine newEngine = deployGlobalRuleset((GlobalRuleset) ruleset);
if (newEngine != null) {
- // Push all existing facts into the engine, this is an initial import of state
- assetStates.forEach(assetState -> newEngine.updateAssetState(assetState, true));
+ // Push all existing facts into the engine, this is an initial import of state so fire delayed
+ assetStates.forEach(assetState -> newEngine.updateFact(assetState, false));
+ newEngine.fire();
}
} else if (ruleset instanceof TenantRuleset) {
RulesEngine newEngine = deployTenantRuleset((TenantRuleset) ruleset);
if (newEngine != null) {
- // Push all existing facts into the engine, this is an initial import of state
+ // Push all existing facts into the engine, this is an initial import of state so fire delayed
assetStates.forEach(assetState -> {
if (assetState.getRealmId().equals(((TenantRuleset) ruleset).getRealmId())) {
- newEngine.updateAssetState(assetState, true);
+ newEngine.updateFact(assetState, false);
}
});
+ newEngine.fire();
}
} else if (ruleset instanceof AssetRuleset) {
@@ -427,10 +425,11 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
AssetRuleset assetRuleset = rulesetStorageService.findEnabledAssetRuleset(ruleset.getId());
RulesEngine newEngine = deployAssetRuleset(assetRuleset);
if (newEngine != null) {
- // Push all existing facts for this asset (and it's children into the engine)
+ // Push all existing facts for this asset (and it's children into the engine), this is an
+ // initial import of state so fire delayed
getAssetStatesInScope(((AssetRuleset) ruleset).getAssetId())
- .forEach(assetState -> newEngine.updateAssetState(assetState, true));
-
+ .forEach(assetState -> newEngine.updateFact(assetState, false));
+ newEngine.fire();
}
}
}
@@ -449,19 +448,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
timerService,
executorService,
assetStorageService,
- () -> new AssetsFacade<>(GlobalRuleset.class, null, assetStorageService, event -> {
- assetProcessingService.sendAttributeEvent(event);
- }),
- () -> new UsersFacade<>(GlobalRuleset.class, null, assetStorageService, notificationService, identityService),
- ID_GLOBAL_RULES_ENGINE,
- rulesEngineListeners,
- error -> {
- // TODO Dispatch RulesetStatusEvent
- }
+ new AssetsFacade<>(GlobalRuleset.class, null, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),
+ new UsersFacade<>(GlobalRuleset.class, null, assetStorageService, notificationService, identityService),
+ null,
+ null
);
}
- globalEngine.addRuleset(ruleset, true);
+ globalEngine.addRuleset(ruleset);
return created ? globalEngine : null;
}
@@ -470,9 +464,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
return;
}
- globalEngine.removeRuleset(ruleset);
-
- if (globalEngine.isEmpty()) {
+ if (globalEngine.removeRuleset(ruleset)) {
globalEngine = null;
}
}
@@ -480,38 +472,33 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected synchronized RulesEngine<TenantRuleset> deployTenantRuleset(TenantRuleset ruleset) {
final boolean[] created = {false};
- // Look for existing deployment for this tenant
- RulesEngine<TenantRuleset> deployment = tenantEngines
+ // Look for existing rules engines for this tenant
+ RulesEngine<TenantRuleset> tenentRulesEngine = tenantEngines
.computeIfAbsent(ruleset.getRealmId(), (realmId) -> {
created[0] = true;
return new RulesEngine<>(
timerService,
executorService,
assetStorageService,
- () -> new AssetsFacade<>(TenantRuleset.class, realmId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),
- () -> new UsersFacade<>(TenantRuleset.class, realmId, assetStorageService, notificationService, identityService),
+ new AssetsFacade<>(TenantRuleset.class, realmId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),
+ new UsersFacade<>(TenantRuleset.class, realmId, assetStorageService, notificationService, identityService),
realmId,
- rulesEngineListeners,
- error -> {
- // TODO Dispatch RulesetStatusEvent
- }
+ null
);
});
- deployment.addRuleset(ruleset, true);
+ tenentRulesEngine.addRuleset(ruleset);
- return created[0] ? deployment : null;
+ return created[0] ? tenentRulesEngine : null;
}
protected synchronized void undeployTenantRuleset(TenantRuleset ruleset) {
- RulesEngine<TenantRuleset> deployment = tenantEngines.get(ruleset.getRealmId());
- if (deployment == null) {
+ RulesEngine<TenantRuleset> rulesEngine = tenantEngines.get(ruleset.getRealmId());
+ if (rulesEngine == null) {
return;
}
- deployment.removeRuleset(ruleset);
-
- if (deployment.isEmpty()) {
+ if (rulesEngine.removeRuleset(ruleset)) {
tenantEngines.remove(ruleset.getRealmId());
}
}
@@ -547,73 +534,68 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
protected synchronized RulesEngine<AssetRuleset> deployAssetRuleset(AssetRuleset ruleset) {
final boolean[] created = {false};
- // Look for existing deployment for this asset
- RulesEngine<AssetRuleset> deployment = assetEngines
+ // Look for existing rules engine for this asset
+ RulesEngine<AssetRuleset> assetRulesEngine = assetEngines
.computeIfAbsent(ruleset.getAssetId(), (assetId) -> {
created[0] = true;
return new RulesEngine<>(
timerService,
executorService,
assetStorageService,
- () -> new AssetsFacade<>(AssetRuleset.class, assetId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),
- () -> new UsersFacade<>(AssetRuleset.class, assetId, assetStorageService, notificationService, identityService),
- assetId,
- rulesEngineListeners,
- error -> {
- // TODO Dispatch RulesetStatusEvent
- }
+ new AssetsFacade<>(AssetRuleset.class, assetId, assetStorageService, event -> assetProcessingService.sendAttributeEvent(event)),
+ new UsersFacade<>(AssetRuleset.class, assetId, assetStorageService, notificationService, identityService),
+ ruleset.getRealmId(),
+ ruleset.getAssetId()
);
});
- deployment.addRuleset(ruleset, true);
- return created[0] ? deployment : null;
+ assetRulesEngine.addRuleset(ruleset);
+ return created[0] ? assetRulesEngine : null;
}
protected synchronized void undeployAssetRuleset(AssetRuleset ruleset) {
- RulesEngine<AssetRuleset> deployment = assetEngines.get(ruleset.getAssetId());
- if (deployment == null) {
+ RulesEngine<AssetRuleset> assetRulesEngine = assetEngines.get(ruleset.getAssetId());
+ if (assetRulesEngine == null) {
return;
}
- deployment.removeRuleset(ruleset);
-
- if (deployment.isEmpty()) {
+ if (assetRulesEngine.removeRuleset(ruleset)) {
assetEngines.remove(ruleset.getAssetId());
}
}
protected synchronized void process(AssetEvent assetEvent) {
- // TODO: implement rules processing error state handling
-
// Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetEvent.getRealmId(), assetEvent.getPathFromRoot());
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetEvent.getRealmId(), assetEvent.getPath());
- // Check that all engines in the scope are not in ERROR state
+ // Check that all engines in the scope are available
if (rulesEngines.stream().anyMatch(RulesEngine::isError)) {
- LOG.severe("At least one rule engine is in an error state so cannot process event:" + assetEvent);
+ LOG.severe("At least one rules engine is in an error state, skipping: " + assetEvent);
+ if (LOG.isLoggable(FINEST)) {
+ for (RulesEngine rulesEngine : rulesEngines) {
+ if (rulesEngine.isError()) {
+ LOG.log(FINEST, "Rules engine error state: " + rulesEngine, rulesEngine.getError());
+ }
+ }
+ }
return;
}
- // Pass through each engine and try and insert the fact
- for (RulesEngine deployment : rulesEngines) {
-
- // Any exceptions in rule RHS will bubble up and the engine would be marked as in ERROR so future
- // updates will be blocked
- String eventExpires = assetEvent.getExpires().orElse(configEventExpires);
- long expirationOffset = TimeIntervalParser.parseSingle(eventExpires);
-
- deployment.insertAssetEvent(expirationOffset, assetEvent);
+ // Pass through each engine
+ for (RulesEngine rulesEngine : rulesEngines) {
+ rulesEngine.insertFact(assetEvent);
}
}
- protected synchronized void updateAssetState(AssetState assetState, boolean skipStatusCheck) {
+ protected synchronized void updateAssetState(AssetState assetState, boolean skipStatusCheck, boolean fireImmediately) {
// TODO: implement rules processing error state handling
// Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPathFromRoot());
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
if (!skipStatusCheck) {
- // Check that all engines in the scope are not in ERROR state
+ // Check that all engines in the scope are available
+ // TODO This is not very useful without locking the engines until we are done with the udpate
for (RulesEngine rulesEngine : rulesEngines) {
if (rulesEngine.isError()) {
assetState.setProcessingStatus(AssetState.ProcessingStatus.ERROR);
@@ -623,46 +605,41 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
}
- // Remove any stale fact that has equality with this new one or the attribute ref matches
- // (this is what rules deployment does also)
- if (!assetStates.remove(assetState)) {
- assetStates.removeIf(storedAssetState -> storedAssetState.attributeRefsEqual(assetState));
- }
- // Insert the new fact
+ // Remove asset state with same attribute ref as new state, add new state
+ assetStates.remove(assetState);
assetStates.add(assetState);
- // Pass through each engine and try and insert the fact
- for (RulesEngine deployment : rulesEngines) {
- deployment.updateAssetState(assetState);
+ // Pass through each rules engine
+ for (RulesEngine rulesEngine : rulesEngines) {
+ rulesEngine.updateFact(assetState, fireImmediately);
}
}
protected void retractAssetState(AssetState assetState) {
// Get the chain of rule engines that we need to pass through
- List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPathFromRoot());
+ List<RulesEngine> rulesEngines = getEnginesInScope(assetState.getRealmId(), assetState.getPath());
- if (!assetStates.remove(assetState)) {
- assetStates.removeIf(storedAssetState -> storedAssetState.attributeRefsEqual(assetState));
- }
+ // Remove asset state with same attribute ref
+ assetStates.remove(assetState);
if (rulesEngines.size() == 0) {
LOG.fine("Ignoring as there are no matching rules engines: " + assetState);
}
- // Pass through each engine and retract this fact
- for (RulesEngine deployment : rulesEngines) {
- deployment.retractAssetState(assetState);
+ // Pass through each rules engine
+ for (RulesEngine rulesEngine : rulesEngines) {
+ rulesEngine.removeFact(assetState);
}
}
protected List<AssetState> getAssetStatesInScope(String assetId) {
return assetStates
.stream()
- .filter(assetState -> Arrays.asList(assetState.getPathFromRoot()).contains(assetId))
+ .filter(assetState -> Arrays.asList(assetState.getPath()).contains(assetId))
.collect(Collectors.toList());
}
- protected List<RulesEngine> getEnginesInScope(String assetRealmId, String[] assetPath) {
+ protected List<RulesEngine> getEnginesInScope(String realmId, String[] assetPath) {
List<RulesEngine> rulesEngines = new ArrayList<>();
// Add global engine (if it exists)
@@ -671,18 +648,17 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
}
// Add tenant engine (if it exists)
- RulesEngine tenantDeployment = tenantEngines.get(assetRealmId);
+ RulesEngine tenantRulesEngine = tenantEngines.get(realmId);
- if (tenantDeployment != null) {
- rulesEngines.add(tenantDeployment);
+ if (tenantRulesEngine != null) {
+ rulesEngines.add(tenantRulesEngine);
}
- // Add asset engines
- // Iterate through asset hierarchy using asset IDs from getPath
+ // Add asset engines, iterate through asset hierarchy using asset IDs from asset path
for (String assetId : assetPath) {
- RulesEngine assetDeployment = assetEngines.get(assetId);
- if (assetDeployment != null) {
- rulesEngines.add(assetDeployment);
+ RulesEngine assetRulesEngine = assetEngines.get(assetId);
+ if (assetRulesEngine != null) {
+ rulesEngines.add(assetRulesEngine);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
new file mode 100644
index 000000000..3fbb835b7
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetDeployment.java
@@ -0,0 +1,355 @@
+/*
+ * 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 groovy.lang.Binding;
+import groovy.lang.GroovyShell;
+import groovy.lang.Script;
+import jdk.nashorn.api.scripting.ScriptObjectMirror;
+import org.codehaus.groovy.control.CompilerConfiguration;
+import org.jeasy.rules.api.Action;
+import org.jeasy.rules.api.Condition;
+import org.jeasy.rules.api.Rule;
+import org.jeasy.rules.api.Rules;
+import org.jeasy.rules.core.RuleBuilder;
+import org.kohsuke.groovy.sandbox.GroovyValueFilter;
+import org.kohsuke.groovy.sandbox.SandboxTransformer;
+import org.openremote.model.rules.Assets;
+import org.openremote.model.rules.Ruleset;
+import org.openremote.model.rules.Users;
+
+import javax.script.*;
+import java.util.Collection;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public class RulesetDeployment {
+
+ public static final int DEFAULT_RULE_PRIORITY = 1000;
+
+ public enum Status {
+ /**
+ * Ruleset compiled successfully but is not running, due to failure of other rulesets in same scope.
+ */
+ READY,
+
+ /**
+ * Ruleset has been compiled and can be executed.
+ */
+ DEPLOYED,
+
+ /**
+ * Ruleset did not compile successfully and can not be executed.
+ */
+ COMPILATION_ERROR,
+
+ /**
+ * Ruleset was executed but there was a runtime error.
+ */
+ EXECUTION_ERROR
+ }
+
+ /**
+ * An interface that looks like a JavaScript browser console, for simplified logging.
+ */
+ public static class JsConsole {
+
+ final protected Logger logger;
+
+ public JsConsole(Logger logger) {
+ this.logger = logger;
+ }
+
+ public void debug(Object o) {
+ logger.fine(o != null ? o.toString() : "null");
+ }
+
+ public void log(Object o) {
+ logger.info(o != null ? o.toString() : "null");
+ }
+
+ public void warn(Object o) {
+ logger.warning(o != null ? o.toString() : "null");
+ }
+
+ public void error(Object o) {
+ logger.severe(o != null ? o.toString() : "null");
+ }
+ }
+
+ // TODO Finish groovy sandbox
+ static class GroovyDenyAllFilter extends GroovyValueFilter {
+ @Override
+ public Object filterReceiver(Object receiver) {
+ throw new SecurityException("Not allowed: " + receiver);
+ }
+ }
+
+ // Share one JS script engine manager, it's thread-safe
+ static final protected ScriptEngineManager scriptEngineManager;
+
+ static final protected GroovyShell groovyShell;
+
+ static {
+ scriptEngineManager = new ScriptEngineManager();
+
+ // LOG and console wrapper can be in global scope for all script engines
+ scriptEngineManager.put("LOG", RulesEngine.RULES_LOG);
+ scriptEngineManager.put("console", new JsConsole(RulesEngine.RULES_LOG));
+
+ groovyShell = new GroovyShell(
+ new CompilerConfiguration().addCompilationCustomizers(new SandboxTransformer())
+ );
+ }
+
+ final protected long id;
+ final protected String name;
+ final protected long version;
+ final protected Rules rules = new Rules();
+ protected Status status;
+ protected Throwable error;
+
+ public RulesetDeployment(long id, String name, long version) {
+ this.id = id;
+ this.name = name;
+ this.version = version;
+ }
+
+ public long getId() {
+ return id;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public long getVersion() {
+ return version;
+ }
+
+ public Rules getRules() {
+ return rules;
+ }
+
+ public boolean registerRules(Ruleset ruleset, Assets assetsFacade, Users usersFacade) {
+ RulesEngine.LOG.info("Evaluating ruleset deployment: " + ruleset);
+ switch (ruleset.getLang()) {
+ case JAVASCRIPT:
+ return registerRulesJavascript(ruleset, assetsFacade, usersFacade);
+ case GROOVY:
+ return registerRulesGroovy(ruleset, assetsFacade, usersFacade);
+ }
+ return false;
+ }
+
+ public boolean registerRulesJavascript(Ruleset ruleset, Assets assetsFacade, Users usersFacade) {
+ // TODO https://github.com/pfisterer/scripting-sandbox/blob/master/src/main/java/de/farberg/scripting/sandbox/ScriptingSandbox.java
+ ScriptEngine scriptEngine = scriptEngineManager.getEngineByName("nashorn");
+ ScriptContext newContext = new SimpleScriptContext();
+ newContext.setBindings(scriptEngine.createBindings(), ScriptContext.ENGINE_SCOPE);
+ Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
+
+ engineScope.put("assets", assetsFacade);
+ engineScope.put("users", usersFacade);
+
+ String script = ruleset.getRules();
+
+ // Default header/imports for all rules scripts
+ script = "load(\"nashorn:mozilla_compat.js\");\n" + // This provides importPackage
+ "\n" +
+ "importPackage(\n" +
+ " \"java.util.stream\",\n" +
+ " \"org.openremote.model.asset\",\n" +
+ " \"org.openremote.model.attribute\",\n" +
+ " \"org.openremote.model.value\"\n" +
+ ");\n" +
+ "var Match = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Match\");\n" +
+ "var Operator = Java.type(\"org.openremote.model.asset.BaseAssetQuery$Operator\");\n" +
+ "var NumberType = Java.type(\"org.openremote.model.asset.BaseAssetQuery$NumberType\");\n" +
+ "var StringPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$StringPredicate\");\n" +
+ "var BooleanPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$BooleanPredicate\");\n" +
+ "var StringArrayPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$StringArrayPredicate\");\n" +
+ "var DateTimePredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$DateTimePredicate\");\n" +
+ "var NumberPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$NumberPredicate\");\n" +
+ "var ParentPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$ParentPredicate\");\n" +
+ "var PathPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$PathPredicate\");\n" +
+ "var TenantPredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$TenantPredicate\");\n" +
+ "var AttributePredicate = Java.type(\"org.openremote.model.asset.BaseAssetQuery$AttributePredicate\");\n" +
+ "var AttributeExecuteStatus = Java.type(\"org.openremote.model.attribute.AttributeExecuteStatus\");\n" +
+ "var EXACT = Match.EXACT;\n" +
+ "var BEGIN = Match.BEGIN;\n" +
+ "var END = Match.END;\n" +
+ "var CONTAINS = Match.CONTAINS;\n" +
+ "var EQUALS = Operator.EQUALS;\n" +
+ "var GREATER_THAN = Operator.GREATER_THAN;\n" +
+ "var GREATER_EQUALS = Operator.GREATER_EQUALS;\n" +
+ "var LESS_THAN = Operator.LESS_THAN;\n" +
+ "var LESS_EQUALS = Operator.LESS_EQUALS;\n" +
+ "var BETWEEN = Operator.BETWEEN;\n" +
+ "var REQUEST_START = AttributeExecuteStatus.REQUEST_START;\n" +
+ "var REQUEST_REPEATING = AttributeExecuteStatus.REQUEST_REPEATING;\n" +
+ "var REQUEST_CANCEL = AttributeExecuteStatus.REQUEST_CANCEL;\n" +
+ "var READY = AttributeExecuteStatus.READY;\n" +
+ "var COMPLETED = AttributeExecuteStatus.COMPLETED;\n" +
+ "var RUNNING = AttributeExecuteStatus.RUNNING;\n" +
+ "var CANCELLED = AttributeExecuteStatus.CANCELLED;\n" +
+ "var ERROR = AttributeExecuteStatus.ERROR;\n" +
+ "var DISABLED = AttributeExecuteStatus.DISABLED;\n" +
+ "\n"
+ + script;
+
+ try {
+ scriptEngine.eval(script, engineScope);
+
+ registerRulesJavascript((ScriptObjectMirror) engineScope.get("rules"));
+
+ RulesEngine.LOG.info("Evaluated ruleset deployment: " + ruleset);
+ return true;
+
+ } catch (Exception e) {
+ RulesEngine.LOG.log(Level.SEVERE, "Error evaluating ruleset: " + ruleset, e);
+ setError(e);
+ engineScope.clear();
+ return false;
+ }
+ }
+
+ /**
+ * Marshal the JavaScript rules array into {@link Rule} instances.
+ */
+ protected void registerRulesJavascript(ScriptObjectMirror scriptRules) {
+ if (scriptRules == null || !scriptRules.isArray()) {
+ throw new IllegalArgumentException("No 'rules' array defined in ruleset");
+ }
+ Collection<Object> rulesObjects = scriptRules.values();
+ for (Object rulesObject : rulesObjects) {
+ ScriptObjectMirror rule = (ScriptObjectMirror) rulesObject;
+
+ String name;
+ if (!rule.containsKey("name")) {
+ throw new IllegalArgumentException("Missing 'name' in rule definition");
+ }
+ try {
+ name = (String) rule.getMember("name");
+ } catch (ClassCastException ex) {
+ throw new IllegalArgumentException("Defined 'name' of rule is not a string");
+ }
+
+ String description;
+ try {
+ description = rule.containsKey("description") ? (String) rule.getMember("description") : null;
+ } catch (ClassCastException ex) {
+ throw new IllegalArgumentException("Defined 'description' is not a string in rule: " + name);
+ }
+
+ int priority;
+ try {
+ priority = rule.containsKey("priority") ? (int) rule.getMember("priority") : DEFAULT_RULE_PRIORITY;
+ } catch (ClassCastException ex) {
+ throw new IllegalArgumentException("Defined 'priority' is not a number in rule: " + name);
+ }
+
+ if (!rule.containsKey("when")) {
+ throw new IllegalArgumentException("Missing 'when' function in rule: " + name);
+ }
+
+ Condition when;
+ try {
+ ScriptObjectMirror whenMirror = (ScriptObjectMirror) rule.getMember("when");
+ if (!whenMirror.isFunction()) {
+ throw new IllegalArgumentException("Defined 'when' is not a function in rule: " + name);
+ }
+ when = whenMirror.to(Condition.class);
+ } catch (ClassCastException ex) {
+ throw new IllegalArgumentException("Defined 'when' is not a function in rule: " + name);
+ }
+
+ Action then;
+ try {
+ ScriptObjectMirror thenMirror = (ScriptObjectMirror) rule.getMember("then");
+ if (!thenMirror.isFunction()) {
+ throw new IllegalArgumentException("Defined 'then' is not a function in rule: " + name);
+ }
+ then = thenMirror.to(Action.class);
+ } catch (ClassCastException ex) {
+ throw new IllegalArgumentException("Defined 'then' is not a function in rule: " + name);
+ }
+
+ RulesEngine.LOG.info("Registering rule: " + name);
+
+ rules.register(
+ new RuleBuilder().name(name).description(description).priority(priority).when(when).then(then).build()
+ );
+ }
+ }
+
+ public boolean registerRulesGroovy(Ruleset ruleset, Assets assetsFacade, Users usersFacade) {
+ try {
+ // TODO Implement sandbox
+ // new DenyAll().register();
+ Script script = groovyShell.parse(ruleset.getRules());
+ Binding binding = new Binding();
+ RulesBuilder rulesBuilder = new RulesBuilder();
+ binding.setVariable("LOG", RulesEngine.RULES_LOG);
+ binding.setVariable("rules", rulesBuilder);
+ binding.setVariable("assets", assetsFacade);
+ binding.setVariable("users", usersFacade);
+ script.setBinding(binding);
+ script.run();
+ for (Rule rule : rulesBuilder.build()) {
+ RulesEngine.LOG.info("Registering rule: " + rule.getName());
+ rules.register(rule);
+ }
+ RulesEngine.LOG.info("Evaluated ruleset deployment: " + ruleset);
+ return true;
+
+ } catch (Exception e) {
+ RulesEngine.LOG.log(Level.SEVERE, "Error evaluating ruleset: " + ruleset, e);
+ setError(e);
+ return false;
+ }
+ }
+
+ public Status getStatus() {
+ return status;
+ }
+
+ public void setStatus(Status status) {
+ this.status = status;
+ }
+
+ public Throwable getError() {
+ return error;
+ }
+
+ public void setError(Throwable error) {
+ this.error = error;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "id=" + id +
+ ", name='" + name + '\'' +
+ ", version=" + version +
+ ", status=" + status +
+ '}';
+ }
+}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
index 7be0265da..008d02135 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesetStorageService.java
@@ -122,7 +122,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.GlobalRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang" +
") " +
"from GlobalRuleset rs " +
"where rs.enabled = true",
@@ -138,7 +138,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.GlobalRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang" +
") " +
"from GlobalRuleset rs " +
"where rs.enabled = true and rs.templateAssetId is not null and rs.templateAssetId = :templateAssetId",
@@ -154,7 +154,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.TenantRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.realmId" +
") " +
"from TenantRuleset rs " +
"where rs.enabled = true",
@@ -170,7 +170,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.TenantRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.realmId" +
") " +
"from TenantRuleset rs " +
"where rs.enabled = true and rs.realmId = :realmId",
@@ -186,7 +186,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.TenantRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.realmId" +
") " +
"from TenantRuleset rs " +
"where rs.realmId = :realmId " +
@@ -205,7 +205,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.AssetRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.assetId, a.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.assetId, a.realmId" +
") " +
"from AssetRuleset rs, Asset a " +
"where rs.assetId = a.id " +
@@ -222,7 +222,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager -> {
List<AssetRuleset> result = entityManager.createQuery(
"select new org.openremote.model.rules.AssetRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.assetId, a.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.assetId, a.realmId" +
") " +
"from AssetRuleset rs, Asset a " +
"where rs.assetId = a.id " +
@@ -242,7 +242,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.AssetRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.assetId, a.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.assetId, a.realmId" +
") " +
"from AssetRuleset rs, Asset a " +
"where rs.assetId = a.id and a.realmId = :realmId " +
@@ -259,7 +259,7 @@ public class RulesetStorageService implements ContainerService {
return persistenceService.doReturningTransaction(entityManager ->
entityManager.createQuery(
"select new org.openremote.model.rules.AssetRuleset(" +
- "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.assetId, a.realmId" +
+ "rs.id, rs.version, rs.createdOn, rs.lastModified, rs.name, rs.enabled, rs.templateAssetId, rs.rules, rs.lang, rs.assetId, a.realmId" +
") " +
"from AssetRuleset rs, Asset a " +
"where rs.assetId = a.id and a.realmId = :realmId " +
diff --git a/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java b/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java
new file mode 100644
index 000000000..48cd0f67b
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/rules/TemporaryFactImpl.java
@@ -0,0 +1,70 @@
+/*
+ * 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 javaemul.internal.annotations.GwtIncompatible;
+import org.openremote.model.event.Event;
+import org.openremote.model.rules.TemporaryFact;
+
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
+import java.time.temporal.ChronoUnit;
+
+/**
+ * An arbitrary value as a punctual event in rules processing.
+ */
+@GwtIncompatible
+public class TemporaryFactImpl<T> extends Event implements TemporaryFact {
+
+ final protected long expirationMilliseconds;
+ final protected T fact;
+ // These are only useful for debugging, easier to read than timestamps
+ final public LocalDateTime time;
+ final public LocalDateTime expirationTime;
+
+ public TemporaryFactImpl(long timestamp, long expirationMilliseconds, T fact) {
+ super(timestamp);
+ this.expirationMilliseconds = expirationMilliseconds;
+ this.fact = fact;
+ this.time = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
+ this.expirationTime = time.plus(expirationMilliseconds, ChronoUnit.MILLIS);
+ }
+
+ @Override
+ public long getExpirationMilliseconds() {
+ return expirationMilliseconds;
+ }
+
+ public T getFact() {
+ return fact;
+ }
+
+ @Override
+ public String toString() {
+ return TemporaryFact.class.getSimpleName() + "{" +
+ "timestamp=" + timestamp +
+ ", time=" + time +
+ ", expirationMilliseconds=" + expirationMilliseconds +
+ ", expirationTime=" + expirationTime +
+ ", fact=" + fact +
+ '}';
+ }
+}
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.java
index b2295e79d..a5f3f4909 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,14 +21,16 @@ package org.openremote.manager.rules.facade;
import org.openremote.manager.asset.AssetStorageService;
import org.openremote.manager.asset.ServerAsset;
-import org.openremote.model.asset.BaseAssetQuery;
import org.openremote.model.asset.Asset;
+import org.openremote.model.asset.BaseAssetQuery;
import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeExecuteStatus;
import org.openremote.model.rules.*;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.Values;
-import java.util.List;
import java.util.function.Consumer;
-import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static org.openremote.model.asset.AssetQuery.PathPredicate;
import static org.openremote.model.asset.AssetQuery.TenantPredicate;
@@ -88,55 +90,41 @@ public class AssetsFacade<T extends Ruleset> extends Assets {
}
@Override
- public List<String> getResults() {
+ public Stream<String> stream() {
if (this.select == null)
this.select = new Select();
Include oldValue = this.select.include;
this.select.include = Include.ONLY_ID_AND_NAME;
try {
- return assetStorageService
- .findAll(this)
- .stream()
- .map(Asset::getId)
- .collect(Collectors.toList());
+ return assetStorageService.findAll(this).stream().map(Asset::getId);
} finally {
this.select.include = oldValue;
}
}
-
- @Override
- public void applyResult(Consumer<String> assetIdConsumer) {
- assetIdConsumer.accept(getResult());
- }
-
- @Override
- public void applyResults(Consumer<List<String>> assetIdListConsumer) {
- assetIdListConsumer.accept(getResults());
- }
};
if (TenantRuleset.class.isAssignableFrom(rulesetType)) {
- query.tenantPredicate = new TenantPredicate(rulesetId);
+ query.tenant = new TenantPredicate(rulesetId);
}
if (AssetRuleset.class.isAssignableFrom(rulesetType)) {
ServerAsset restrictedAsset = assetStorageService.find(rulesetId, true);
if (restrictedAsset == null) {
throw new IllegalStateException("Asset is no longer available for this deployment: " + rulesetId);
}
- query.pathPredicate = new PathPredicate(restrictedAsset.getPath());
+ query.path = new PathPredicate(restrictedAsset.getPath());
}
return query;
}
@Override
- public void dispatch(AttributeEvent... events) {
+ public Assets dispatch(AttributeEvent... events) {
if (events == null)
- return;
+ return this;
for (AttributeEvent event : events) {
- // Check if the asset ID of the event can be found in the original query
+ // Check if the asset ID of the event can be found with the default query of this facade
BaseAssetQuery<RestrictedQuery> checkQuery = query();
- checkQuery.id = event.getEntityId();
+ checkQuery.id = event.getEntityId(); // Set directly on field, as modifying query restrictions is not allowed
if (assetStorageService.find(checkQuery) == null) {
throw new IllegalArgumentException(
"Access to asset not allowed for this rule engine scope: " + event
@@ -144,5 +132,36 @@ public class AssetsFacade<T extends Ruleset> extends Assets {
}
eventConsumer.accept(event);
}
+ return this;
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName, Value value) {
+ return dispatch(new AttributeEvent(assetId, attributeName, value));
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName, String value) {
+ return dispatch(assetId, attributeName, Values.create(value));
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName, double value) {
+ return dispatch(assetId, attributeName, Values.create(value));
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName, boolean value) {
+ return dispatch(assetId, attributeName, Values.create(value));
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName, AttributeExecuteStatus status) {
+ return dispatch(assetId, attributeName, status.asValue());
+ }
+
+ @Override
+ public Assets dispatch(String assetId, String attributeName) {
+ return dispatch(new AttributeEvent(assetId, attributeName));
}
}
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
index f0798f013..f8a20199a 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractManagerSetup.java
@@ -89,7 +89,6 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(DESCRIPTION, Values.create("Presence detected in any room")),
new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
new MetaItem(RULE_STATE, Values.create(true)),
- new MetaItem(RULE_EVENT, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true)),
new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))
)),
@@ -153,7 +152,6 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(DESCRIPTION, Values.create("Greater than zero when motion is sensed")),
new MetaItem(READ_ONLY, Values.create(true)),
new MetaItem(RULE_STATE, Values.create(true)),
- new MetaItem(RULE_EVENT, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true))
).addMeta(shouldBeLinked ? agentLinker.get() : null),
new AssetAttribute("presenceDetected", AttributeType.BOOLEAN)
@@ -161,7 +159,6 @@ public abstract class AbstractManagerSetup implements Setup {
new MetaItem(LABEL, Values.create("Presence detected")),
new MetaItem(DESCRIPTION, Values.create("Someone is moving or resting in the room")),
new MetaItem(RULE_STATE, Values.create(true)),
- new MetaItem(RULE_EVENT, Values.create(true)),
new MetaItem(ACCESS_RESTRICTED_READ, Values.create(true)),
new MetaItem(STORE_DATA_POINTS, Values.create(true)),
new MetaItem(SHOW_ON_DASHBOARD, Values.create(true))
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
index 18b26a0a6..e17747f9a 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/ManagerDemoSetup.java
@@ -50,8 +50,8 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
final protected boolean importDemoScenes;
// Update these numbers whenever you change a RULE_STATE flag in test data
- public static final int DEMO_RULE_STATES_APARTMENT_1 = 19;
- public static final int DEMO_RULE_STATES_APARTMENT_2 = 9;
+ public static final int DEMO_RULE_STATES_APARTMENT_1 = 23;
+ public static final int DEMO_RULE_STATES_APARTMENT_2 = 11;
public static final int DEMO_RULE_STATES_APARTMENT_3 = 0;
public static final int DEMO_RULE_STATES_SMART_HOME = DEMO_RULE_STATES_APARTMENT_1 + DEMO_RULE_STATES_APARTMENT_2 + DEMO_RULE_STATES_APARTMENT_3;
public static final int DEMO_RULE_STATES_CUSTOMER_A = DEMO_RULE_STATES_SMART_HOME;
@@ -74,6 +74,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
public String apartment1ServiceAgentId;
public String apartment1LivingroomId;
public String apartment1KitchenId;
+ public String apartment1HallwayId;
public String apartment2Id;
public String apartment3Id;
public String apartment2LivingroomId;
@@ -384,6 +385,15 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
apartment1Kitchen = assetStorageService.merge(apartment1Kitchen);
apartment1KitchenId = apartment1Kitchen.getId();
+ ServerAsset apartment1Hallway = createDemoApartmentRoom(apartment1, "Hallway");
+ addDemoApartmentRoomMotionSensor(apartment1Hallway, true, () -> new MetaItem[]{
+ new MetaItem(AGENT_LINK, new AttributeRef(apartment1ServiceAgentId, "apartmentSimulator").toArrayValue()),
+ new MetaItem(SimulatorProtocol.SIMULATOR_ELEMENT, Values.create(NumberSimulatorElement.ELEMENT_NAME))
+ });
+
+ apartment1Hallway = assetStorageService.merge(apartment1Hallway);
+ apartment1HallwayId = apartment1Hallway.getId();
+
if (importDemoScenes) {
Scene[] scenes = new Scene[]{
new Scene("homeScene", "Home scene", "HOME", "0 0 7 ? *", false, 21d),
@@ -393,7 +403,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
};
ServerAsset demoApartmentSceneAgent = createDemoApartmentSceneAgent(
- apartment1, scenes, apartment1Livingroom, apartment1Kitchen
+ apartment1, scenes, apartment1Livingroom, apartment1Kitchen, apartment1Hallway
);
demoApartmentSceneAgent = assetStorageService.merge(demoApartmentSceneAgent);
@@ -409,7 +419,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new MetaItem(LABEL, Values.create("All Lights Off Switch")),
new MetaItem(DESCRIPTION, Values.create("When triggered, turns all lights in the apartment off")),
new MetaItem(RULE_EVENT, Values.create(true)),
- new MetaItem(RULE_EVENT_EXPIRES, Values.create("10s"))
+ new MetaItem(RULE_EVENT_EXPIRES, Values.create("3s"))
)
);
apartment2 = assetStorageService.merge(apartment2);
@@ -451,7 +461,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Values.create(true))
.setMeta(
new MetaItem(LABEL, Values.create("Light Switch")),
- new MetaItem(RULE_STATE, Values.create(false))
+ new MetaItem(RULE_STATE, Values.create(true))
),
new AssetAttribute("windowOpen", AttributeType.BOOLEAN, Values.create(false))
.setMeta(
@@ -492,7 +502,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
new AssetAttribute("lightSwitch", AttributeType.BOOLEAN, Values.create(true))
.setMeta(
new MetaItem(LABEL, Values.create("Light Switch")),
- new MetaItem(RULE_STATE, Values.create(false))
+ new MetaItem(RULE_STATE, Values.create(true))
)
);
apartment2Bathroom = assetStorageService.merge(apartment2Bathroom);
@@ -517,6 +527,7 @@ public class ManagerDemoSetup extends AbstractManagerSetup {
assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1Id));
assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1LivingroomId));
assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1KitchenId));
+ assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment1HallwayId));
assetStorageService.storeUserAsset(new UserAsset(keycloakDemoSetup.customerATenant.getId(), keycloakDemoSetup.testuser3Id, apartment2Id));
}
}
\ No newline at end of file
diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
index fe1f68e33..e981d22c6 100644
--- a/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/RulesDemoSetup.java
@@ -50,21 +50,27 @@ public class RulesDemoSetup extends AbstractManagerSetup {
// ################################ Rules demo data ###################################
// Apartment 1
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentPresenceDetection.drl")) {
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoResidencePresenceDetection.GROOVY")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new AssetRuleset("Demo Apartment - Presence Detection with motion sensor", managerDemoSetup.apartment1Id, rules);
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Residence - Presence Detection with motion and CO2 sensors", managerDemoSetup.apartment1Id, rules, Ruleset.Lang.GROOVY
+ );
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentVacationMode.drl")) {
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoResidenceVacationMode.groovy")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new AssetRuleset("Demo Apartment - Vacation Mode", managerDemoSetup.apartment1Id, rules);
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Residence - Vacation Mode", managerDemoSetup.apartment1Id, rules, Ruleset.Lang.GROOVY
+ );
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
// Apartment 2
- try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoApartmentAllLightsOff.drl")) {
+ try (InputStream inputStream = RulesDemoSetup.class.getResourceAsStream("/demo/rules/DemoResidenceAllLightsOff.js")) {
String rules = IOUtils.toString(inputStream, Charset.forName("utf-8"));
- Ruleset ruleset = new AssetRuleset("Demo Apartment - All Lights Off", managerDemoSetup.apartment2Id, rules);
+ Ruleset ruleset = new AssetRuleset(
+ "Demo Residence - All Lights Off", managerDemoSetup.apartment2Id, rules, Ruleset.Lang.JAVASCRIPT
+ );
apartmentActionsRulesetId = rulesetStorageService.merge(ruleset).getId();
}
}
diff --git a/manager/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl b/manager/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl
deleted file mode 100644
index 52d8ba3d8..000000000
--- a/manager/src/main/resources/demo/rules/DemoApartmentAllLightsOff.drl
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.asset.*
-import org.openremote.model.attribute.*
-import org.openremote.model.value.*
-import org.openremote.model.value.Values
-
-global java.util.logging.Logger LOG;
-global org.openremote.model.rules.Assets assets;
-
-rule "Switch room lights off when apartment ALL LIGHTS OFF push-button is pressed"
-when
- // In an asset of type RESIDENCE the All Lights Off push-button is pressed, which sends a 'true' value
- $e: AssetEvent(type == AssetType.RESIDENCE, attributeName == "allLightsOffSwitch", valueAsBoolean == true)
-then
- assets.query() // Execute a query to get "other" assets
- .parent($e.getId()) // Where parent is the apartment in LHS
- .type(AssetType.ROOM) // And the children are of type ROOM
- .applyResults(assetIds -> assetIds.forEach(assetId -> assets.dispatch( // For each asset ID in result...
- new AttributeEvent(assetId, "lightSwitch", Values.create(false)) // Dispatch an event that turns the switch off
- )));
-end
diff --git a/manager/src/main/resources/demo/rules/DemoApartmentNotifyAlarmTrigger.drl b/manager/src/main/resources/demo/rules/DemoApartmentNotifyAlarmTrigger.drl
deleted file mode 100644
index 017873bfd..000000000
--- a/manager/src/main/resources/demo/rules/DemoApartmentNotifyAlarmTrigger.drl
+++ /dev/null
@@ -1,94 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.asset.*;
-import org.openremote.model.user.*;
-import org.openremote.model.value.*;
-import org.openremote.model.attribute.*;
-import org.openremote.model.notification.*;
-import java.text.SimpleDateFormat;
-import java.util.List;
-
-global java.util.logging.Logger LOG;
-global org.openremote.model.rules.Users users;
-global org.openremote.model.rules.Assets assets;
-
-declare AlarmTrigger
- residenceId : String
- roomName : String
-end
-
-// Notify the user every 30 minutes while alarm is triggered
-declare UserNotified
- @role(event)
- @expires(30m)
- residenceId : String
-end
-
-rule "Trigger alarm when alarm is enabled and presence is detected in any room"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "alarmEnabled", valueTrue)
- $room : AssetState(parentId == $residence.id, type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
- not AlarmTrigger(residenceId == $residence.id) // we don't need more than one trigger per apartment
-then
- AlarmTrigger trigger =new AlarmTrigger();
- trigger.setResidenceId($residence.getId());
- trigger.setRoomName($room.getName());
- insert(trigger);
-end
-
-rule "Stop alarm when alarm has been triggered and no presence is detected in any room"
-when
- $residence : AssetState(type == AssetType.RESIDENCE) // retract trigger always so they don't leak
- $alarmTrigger : AlarmTrigger(residenceId == $residence.id)
- not AssetState(parentId == $residence.id, type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
-then
- delete($alarmTrigger);
-end
-
-rule "Alert user when alarm has been triggered and not done so already"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "alarmEnabled", valueTrue)
- $alarmTrigger : AlarmTrigger(residenceId == $residence.id)
- not(UserNotified(residenceId == $residence.id))
-then
- LOG.fine("Alarm in apartment (room: " + $alarmTrigger.getRoomName() + "): " + $residence);
-
- String timestamp = new SimpleDateFormat(Constants.DEFAULT_DATETIME_FORMAT).format(
- drools.getWorkingMemory().getSessionClock().getCurrentTime()
- );
- AlertNotification alert = new AlertNotification(
- "Apartment Alarm", "Aanwezigheid in " + $alarmTrigger.getRoomName() + " (" + timestamp + ")."
- );
- alert.addLinkAction("Details", "#/Veilig");
- alert.addActuatorAction("Alarm uit", $residence.getId(), "alarmEnabled", Values.create(false).toJson());
-
- List<String> userIds = users
- .query()
- .asset(new UserQuery.AssetPredicate($residence.getId()))
- .getResults();
-
- LOG.fine("Sending alert to apartment users: " + userIds);
- userIds.forEach(userId -> users.storeAndNotify(userId, alert));
-
- UserNotified userNotified = new UserNotified();
- userNotified.setResidenceId($residence.getId());
- insert(userNotified);
- delete($alarmTrigger); // For sure we don't want to notify user on the same trigger.
-end
-
-rule "Retract alarm triggers and alerts when alarm disabled"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "alarmEnabled", valueFalse)
- $alarmTrigger : AlarmTrigger(residenceId == $residence.id)
-then
- delete($alarmTrigger);
-end
-
-rule "Retract user notified and alerts when alarm disabled"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "alarmEnabled", valueFalse)
- $userNotified : UserNotified(residenceId == $residence.id)
-then
- delete($userNotified);
-end
diff --git a/manager/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl b/manager/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
deleted file mode 100644
index 1720b785b..000000000
--- a/manager/src/main/resources/demo/rules/DemoApartmentPresenceDetection.drl
+++ /dev/null
@@ -1,132 +0,0 @@
-package org.openremote.test.rules;
-
-import java.util.ArrayList;
-import org.openremote.model.*;
-import org.openremote.model.asset.*;
-import org.openremote.model.value.*;
-import org.openremote.model.attribute.*;
-
-global java.util.logging.Logger LOG;
-global org.openremote.model.rules.Assets assets;
-
-/*
-Uses 'motionSensor' and optional 'co2Level' of a room asset to set the 'presenceDetected'
-and 'lastPresenceDetected' attributes of the room. Presence detection is based on motion
-sensing and if available for a room, increasing CO2 level over a time window. The assumption
-is that the 'motionSensor' is set to 0 or 1, depending on whether motion has been detected
-in a room over a time window that is internal to the sensor (e.g. the last minute). The
-'presenceDetected' attribute of the apartment is set depending on whether any child room
-assets have presence set.
-*/
-
-
-rule "Set presence detected flag of room when motion is detected and no CO2 sensor exists"
-when
- // A room were the presence detected flag is not set
- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueFalse)
- // And the motion sensor has been triggered
- AssetState(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0))
- // And the room does not have a CO2 sensor
- not AssetState(id == $room.id, attributeName == "co2Level")
-then
- // Set the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
- );
-end
-
-
-rule "Clear presence detected flag of room if no motion is detected and no CO2 sensor exists"
-when
- // A room where the presence detected flag is set
- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
- // And the motion sensor has not been triggered
- AssetState(id == $room.id, attributeName == "motionSensor", value == null || valueAsNumber == 0)
- // And the room does not have a CO2 sensor
- not AssetState(id == $room.id, attributeName == "co2Level")
-then
- // Clear the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(false))
- );
-end
-
-
-rule "Set presence detected flag of room when motion is detected and confirmed with CO2 level rising"
-when
- // A room were the presence detected flag is not set
- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueFalse)
- // And the motion sensor has been triggered
- AssetState(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0))
- // And the CO2 level has increased at least 2 times in the last 11 minutes
- accumulate(
- AssetEvent(id == $room.id, attributeName == "co2Level", valueGreaterThanOldValue) over window:time(11m);
- $increasedCO2: count(1);
- $increasedCO2 >= 2
- )
-then
- // Set the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(true))
- );
-end
-
-
-rule "Clear presence detected flag of room if no motion or CO2 increase was sensed in a while"
-when
- // A room where the presence detected flag is set
- $room: AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
- // And the motion sensor has not been triggered
- AssetState(id == $room.id, attributeName == "motionSensor", value == null || valueAsNumber == 0)
- // And the room has a CO2 sensor
- AssetState(id == $room.id, attributeName == "co2Level")
- // And the CO2 level has not increased in the last 11 minutes
- accumulate(
- AssetEvent(id == $room.id, attributeName == "co2Level", valueGreaterThanOldValue) over window:time(11m);
- $increasedCO2: count(1);
- $increasedCO2 == 0
- )
-then
- // Clear the presence detected flag of the room
- assets.dispatch(
- new AttributeEvent($room.getId(), "presenceDetected", Values.create(false))
- );
-end
-
-
-rule "Update presence detected timestamp of room with last trigger of motion sensor"
-when
- // A room were the presence detected flag is set
- $room : AssetState(type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
- // And the motion sensor has been triggered
- AssetState(id == $room.id, attributeName == "motionSensor", isValueGreaterThan(0), $lastTriggerTimestamp: valueTimestamp)
- // And the last sensor trigger event is newer than the recorded last detected time
- AssetState(id == $room.id, attributeName == "lastPresenceDetected", isValueLessThan($lastTriggerTimestamp))
-then
- // Update the last presence detected timestamp to the latest motion sensor trigger event
- assets.dispatch(
- new AttributeEvent($room.getId(), "lastPresenceDetected", Values.create($lastTriggerTimestamp))
- );
-end
-
-
-rule "Set presence detected flag of apartment if presence is detected in any room"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "presenceDetected", valueFalse)
- $room : AssetState(parentId == $residence.id, type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
-then
- assets.dispatch(
- new AttributeEvent($residence.getId(), "presenceDetected", Values.create(true))
- );
-end
-
-
-rule "Clear presence detected flag of apartment when no presence is detected in any room"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "presenceDetected", valueTrue)
- not AssetState(parentId == $residence.id, type == AssetType.ROOM, attributeName == "presenceDetected", valueTrue)
-then
- assets.dispatch(
- new AttributeEvent($residence.getId(), "presenceDetected", Values.create(false))
- );
-end
diff --git a/manager/src/main/resources/demo/rules/DemoApartmentVacationMode.drl b/manager/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
deleted file mode 100644
index acd4b531e..000000000
--- a/manager/src/main/resources/demo/rules/DemoApartmentVacationMode.drl
+++ /dev/null
@@ -1,44 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.asset.*
-import org.openremote.model.value.*
-import org.openremote.model.attribute.*
-import java.time.DayOfWeek
-import org.drools.core.util.Drools
-
-global java.util.logging.Logger LOG;
-global org.openremote.model.rules.Assets assets;
-
-rule "When vacation mode is enabled, execute AWAY scene and disable scene timers"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "vacationUntil", value != null, oldValue == null)
-then
- assets.dispatch(
- new AttributeEvent($residence.getId(), "awayScene", AttributeExecuteStatus.REQUEST_START.asValue()),
- new AttributeEvent($residence.getId(), "disableSceneTimer", AttributeExecuteStatus.REQUEST_START.asValue())
- );
-end
-
-rule "When vacation mode is disabled, enable scene timers"
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "vacationUntil", value == null, oldValue != null)
-then
- assets.dispatch(
- new AttributeEvent($residence.getId(), "enableSceneTimer", AttributeExecuteStatus.REQUEST_START.asValue())
- );
-end
-
-rule "When vacation mode is on, check periodically if vacation mode should be disabled"
- // Run every hour
- timer (cron: 0 0 0/1 1/1 * ? *)
-when
- $residence : AssetState(type == AssetType.RESIDENCE, attributeName == "vacationUntil", $vacationUntil: valueAsNumber, valueAsNumber > 0)
-then
- if ($vacationUntil <= drools.getWorkingMemory().getSessionClock().getCurrentTime()) {
- assets.dispatch(
- new AttributeEvent($residence.getId(), "vacationUntil", null)
- );
- }
-end
-
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js b/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js
new file mode 100644
index 000000000..52d8eb377
--- /dev/null
+++ b/manager/src/main/resources/demo/rules/DemoResidenceAllLightsOff.js
@@ -0,0 +1,41 @@
+rules = [{
+ name: "Switch room lights off when residence ALL LIGHTS OFF push-button is pressed",
+ when: function (facts) {
+
+ var roomWithLightOn = facts.matchFirstAssetState( // Find asset state
+ new AssetQuery()
+ .type(AssetType.ROOM) // for a room
+ .attributeValue("lightSwitch", true) // where the light switch is on
+ );
+
+ // If we have a room where the light is on
+ if (roomWithLightOn.isPresent()) {
+ var room = roomWithLightOn.get();
+
+ var residenceWithLightOff = facts.matchFirstAssetEvent( // Find asset event
+ new AssetQuery()
+ .type(AssetType.RESIDENCE) // for a residence
+ .id(room.parentId) // that is the parent asset of the room
+ .attributeValue("allLightsOffSwitch", true) // where the "all lights off" switch has been triggered
+ );
+
+ // If we have a residence where the light has been switched off
+ if (residenceWithLightOff.isPresent()) {
+
+ // Store the room for RHS consumption
+ facts.bind("roomId", room.id);
+
+ // Trigger the action
+ return true;
+ }
+ }
+ return false;
+
+ },
+ then: function (facts) {
+ // Turn the light off in the room
+ facts.updateAssetState(
+ facts.bound("roomId"), "lightSwitch", false
+ );
+ }
+}];
\ No newline at end of file
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
new file mode 100644
index 000000000..12cdb7606
--- /dev/null
+++ b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
@@ -0,0 +1,186 @@
+package demo.rules
+
+import groovy.transform.ToString
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+import org.openremote.model.notification.AlertNotification
+import org.openremote.model.rules.Users
+import org.openremote.model.user.UserQuery
+import org.openremote.model.value.Values
+
+import java.util.logging.Logger
+
+import static org.openremote.model.asset.AssetType.RESIDENCE
+import static org.openremote.model.asset.AssetType.ROOM
+
+Logger LOG = binding.LOG
+RulesBuilder rules = binding.rules
+Users users = binding.users
+
+@ToString(includeNames = true)
+class AlarmTrigger {
+ String residenceId
+ String roomName
+}
+
+/**
+ * When this temporary fact is present, don't alert users again.
+ */
+@ToString(includeNames = true)
+class AlertSilence {
+ static String DURATION = "30m"
+ String residenceId
+}
+
+rules.add()
+ .name("Create alarm trigger when residence alarm is enabled and presence is detected in any room")
+ .when(
+ { facts ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", true)
+ ).filter({ residenceWithAlarmEnabled ->
+ !facts.matchFirst(AlarmTrigger, { alarmTrigger ->
+ alarmTrigger.residenceId == residenceWithAlarmEnabled.id
+ }).isPresent()
+ }).map({ residenceWithoutAlarmTrigger ->
+ // Map to Optional<AssetState> of the "first" room in the residence with presence detected
+ facts.matchFirstAssetState(
+ new AssetQuery().type(ROOM)
+ .parent(residenceWithoutAlarmTrigger.id)
+ .attributeValue("presenceDetected", true)
+ )
+ }).filter({ roomWithPresence ->
+ roomWithPresence.isPresent()
+ }).map({ roomWithPresence ->
+ roomWithPresence.get()
+ }).findFirst().map({ roomWithPresence ->
+ facts.bind("residenceId", roomWithPresence.parentId).bind("roomName", roomWithPresence.name)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AlarmTrigger alarmTrigger = new AlarmTrigger(
+ residenceId: facts.bound("residenceId"),
+ roomName: facts.bound("roomName")
+ )
+ LOG.info("Alarm enabled and presence detected, creating: " + alarmTrigger)
+ facts.put(alarmTrigger)
+ })
+
+rules.add()
+ .name("Remove alarm trigger when no presence is detected in any room of residence")
+ .when(
+ { facts ->
+ facts.matchFirst(AlarmTrigger, { alarmTrigger ->
+ !facts.matchFirstAssetState(
+ new AssetQuery().type(ROOM)
+ .parent(alarmTrigger.residenceId)
+ .attributeValue("presenceDetected", true)
+ ).isPresent()
+ }).map({ alarmTrigger ->
+ facts.bind("alarmTrigger", alarmTrigger)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AlarmTrigger alarmTrigger = facts.bound("alarmTrigger")
+ LOG.info("No presence in any room, removing: " + alarmTrigger)
+ facts.remove(alarmTrigger)
+ })
+
+rules.add()
+ .name("Remove alarm trigger when residence alarm is disabled")
+ .when(
+ { facts ->
+ facts.matchFirst(AlarmTrigger, { alarmTrigger ->
+ facts.matchFirstAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .id(alarmTrigger.residenceId)
+ .attributeValue("alarmEnabled", false)
+ ).isPresent()
+ }).map({ alarmTrigger ->
+ facts.bind("alarmTrigger", alarmTrigger)
+ true
+ }).orElse(false)
+ }).then(
+ { facts ->
+ AlarmTrigger alarmTrigger = facts.bound("alarmTrigger")
+ LOG.info("Alarm disabled, removing: " + alarmTrigger)
+ facts.remove(alarmTrigger)
+ })
+
+rules.add()
+ .name("Alert user when alarm has been triggered and not done so already")
+ .when(
+ { facts ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", true)
+ ).map({ residenceWithAlarmEnabled ->
+ facts.matchFirst(AlarmTrigger, { alarmTrigger ->
+ alarmTrigger.residenceId == residenceWithAlarmEnabled.id
+ })
+ }).filter({ alarmTrigger ->
+ // there is an alarm trigger and alerts are not silenced for this residence
+ alarmTrigger.isPresent() &&
+ !facts.matchFirst(AlertSilence, { alertSilence ->
+ alertSilence.residenceId == alarmTrigger.get().residenceId
+ }).isPresent()
+ }).map({ alarmTrigger ->
+ alarmTrigger.get()
+ }).findFirst().map({ alarmTrigger ->
+ facts.bind("alarmTrigger", alarmTrigger)
+ true
+ }).orElse(false)
+ }).then(
+ { facts ->
+ AlarmTrigger alarmTrigger = facts.bound("alarmTrigger")
+
+ AlertNotification alert = new AlertNotification(
+ title: "Apartment Alarm",
+ message: "Aanwezigheid in " + alarmTrigger.roomName + " (" + facts.clock.time + ")."
+ )
+ alert.addLinkAction("Details", "#/Veilig")
+ alert.addActuatorAction("Alarm uit", alarmTrigger.residenceId, "alarmEnabled", Values.create(false).toJson())
+
+ List<String> userIds = users
+ .query()
+ .asset(new UserQuery.AssetPredicate(alarmTrigger.residenceId))
+ .getResults()
+
+ LOG.info("Alerting users of " + alarmTrigger + ": " + userIds)
+ userIds.forEach({ userId ->
+ users.storeAndNotify(userId, alert)
+ })
+
+ AlertSilence alertSilence = new AlertSilence(residenceId: alarmTrigger.residenceId)
+ facts.putTemporary(AlertSilence.DURATION, alertSilence)
+
+ facts.remove(alarmTrigger)
+ })
+
+rules.add()
+ .name("Remove alert silence when residence alarm is disabled")
+ .when(
+ { facts ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE).attributeValue("alarmEnabled", false)
+ ).map({ residenceWithAlarmEnabled ->
+ facts.matchFirst(AlertSilence, { alertSilence ->
+ alertSilence.residenceId == residenceWithAlarmEnabled.id
+ })
+ }).filter({ alertSilence ->
+ alertSilence.isPresent()
+ }).map({ alertSilence ->
+ alertSilence.get()
+ }).findFirst().map({ alertSilence ->
+ facts.bind("alertSilence", alertSilence)
+ true
+ }).orElse(false)
+ }).then(
+ { facts ->
+ AlertSilence alertSilence = facts.bound("alertSilence")
+ LOG.info("Alarm disabled, removing: " + alertSilence)
+ facts.remove(alertSilence)
+ })
diff --git a/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
new file mode 100644
index 000000000..fa43fab40
--- /dev/null
+++ b/manager/src/main/resources/demo/rules/DemoResidencePresenceDetection.groovy
@@ -0,0 +1,190 @@
+/*
+Uses 'motionSensor' and optional 'co2Level' of a room asset to set the 'presenceDetected'
+and 'lastPresenceDetected' attributes of the room. Presence detection is based on motion
+sensing and if available for a room, increasing CO2 level over a time window. The assumption
+is that the 'motionSensor' is set to 0 or 1, depending on whether motion has been detected
+in a room over a time window that is internal to the sensor (e.g. the last minute). The
+'presenceDetected' attribute of the residence is set depending on whether any child room
+assets have presence set.
+*/
+package demo.rules
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+import org.openremote.model.asset.AssetState
+import org.openremote.model.util.Pair
+
+import java.util.logging.Logger
+
+import static org.openremote.model.asset.AssetType.RESIDENCE
+import static org.openremote.model.asset.AssetType.ROOM
+import static org.openremote.model.asset.BaseAssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_THAN
+
+Logger LOG = binding.LOG
+RulesBuilder rules = binding.rules
+
+rules.add()
+ .name("Set presence detected flag of room when motion is detected and (optional) CO2 increased")
+ .when(
+ { facts ->
+ // Any room where the presence detected flag is not set
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).attributeValue("presenceDetected", false)
+ ).flatMap({ roomWithoutPresence ->
+ // and the motion sensor has been triggered
+ facts.matchAssetState(
+ new AssetQuery().id(roomWithoutPresence.id).attributeValue("motionSensor", GREATER_THAN, 0)
+ )
+ }).findFirst().map({ roomWithMotionSensorTriggered ->
+
+ facts.bind("room", roomWithMotionSensorTriggered)
+
+ // and there is a CO2 sensor in the room
+ facts.matchFirstAssetState(
+ new AssetQuery().id(roomWithMotionSensorTriggered.id).attributeName("co2Level")
+ ).map({ co2Level ->
+ // and there are sensor events
+ facts.matchAssetEvent(
+ new AssetQuery().id(roomWithMotionSensorTriggered.id).attributeName("co2Level")
+ ).filter(
+ // in the last 12 minutes
+ facts.clock.last("12m")
+ ).filter({ coLevel ->
+ // with increasing values
+ coLevel.isValueGreaterThanOldValue()
+ }).count() >= 2 // at least 2
+ }).orElse(true) // or we don't have a CO2 sensor
+
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState room = facts.bound("room")
+ LOG.info("Presence detected in residence '" + room.parentName + "', room: " + room.name)
+ facts.updateAssetState(room.id, "presenceDetected", true)
+ })
+
+rules.add()
+ .name("Clear presence detected flag of room if no motion is detected and (optional) CO2 did not increase")
+ .when(
+ { facts ->
+ // Any room where the presence detected flag is set
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ ).flatMap({ roomWithPresence ->
+ // and the motion sensor has not been triggered
+ facts.matchAssetState(
+ new AssetQuery().id(roomWithPresence.id).attributeValue("motionSensor", LESS_THAN, 1)
+ )
+ }).findFirst().map({ roomWithoutMotionSensorTriggered ->
+
+ facts.bind("room", roomWithoutMotionSensorTriggered)
+
+ // and there is a CO2 sensor in the room
+ facts.matchFirstAssetState(
+ new AssetQuery().id(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
+ ).map({ co2Level ->
+ // and there are no sensor events
+ facts.matchAssetEvent(
+ new AssetQuery().id(roomWithoutMotionSensorTriggered.id).attributeName("co2Level")
+ ).filter({ coLevel ->
+ // with increasing values
+ coLevel.isValueGreaterThanOldValue()
+ // in the last 12 minutes≤
+ }).filter(facts.clock.last("12m")).count() == 0
+ }).orElse(true) // or we don't have a CO2 sensor
+
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState room = facts.bound("room")
+ LOG.info("Presence gone in residence '" + room.parentName + "', room: " + room.name)
+ facts.updateAssetState(room.id, "presenceDetected", false)
+ })
+
+rules.add()
+ .name("Update presence detected timestamp of room with last trigger of motion sensor")
+ .when(
+ { facts ->
+ // Any room where the presence detected flag is set
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ ).flatMap({ roomWithPresence ->
+ // and the motion sensor has been triggered
+ facts.matchAssetState(
+ new AssetQuery().id(roomWithPresence.id)
+ .attributeValue("motionSensor", GREATER_THAN, 0)
+ ).flatMap({ roomWithMotionSensorTriggered ->
+ // and the last presence detection timestamp is older than the motion sensor timestamp
+ facts.matchAssetState(
+ new AssetQuery().id(roomWithMotionSensorTriggered.id)
+ .attributeValue("lastPresenceDetected", LESS_THAN, roomWithMotionSensorTriggered.timestamp)
+ ).map({ outdatedLastPresenceDetected ->
+ // keep the room and the new timestamp
+ new Pair<AssetState, Double>(outdatedLastPresenceDetected, roomWithMotionSensorTriggered.timestamp)
+ })
+ })
+ }).findFirst().map({ pair ->
+ facts.bind("room", pair.key).bind("lastPresenceTimestamp", pair.value)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState room = facts.bound("room")
+ LOG.info("Motion sensor triggered, updating last presence in residence '" + room.parentName + "', room: " + room.name)
+ facts.updateAssetState(room.id, "lastPresenceDetected", facts.bound("lastPresenceTimestamp") as Double)
+ })
+
+rules.add()
+ .name("Set presence detected flag of residence if presence is detected in any room")
+ .when(
+ { facts ->
+ // A room where the presence detected flag is set
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).attributeValue("presenceDetected", true)
+ ).flatMap({ roomWithPresence ->
+ // and a residence parent where the presence detected flag is not set
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .id(roomWithPresence.parentId)
+ .attributeValue("presenceDetected", false)
+ )
+ }).findFirst().map({ residenceWithoutPresence ->
+ facts.bind("residence", residenceWithoutPresence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Presence detected in residence: " + residence.name)
+ facts.updateAssetState(residence.id, "presenceDetected", true)
+ })
+
+rules.add()
+ .name("Clear presence detected flag of residence when no presence is detected in any room")
+ .when(
+ { facts ->
+ // A residence where the presence detected flag is set
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE).attributeValue("presenceDetected", true)
+ ).filter({ residenceWithPresence ->
+ // and no room child of that residence has presence
+ facts.matchAssetState(
+ new AssetQuery().type(ROOM).parent(residenceWithPresence.id)
+ .attributeValue("presenceDetected", true)
+ ).count() == 0
+ }).findFirst().map({ residenceWithPresence ->
+ facts.bind("residence", residenceWithPresence)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Presence gone in residence: " + residence.name)
+ facts.updateAssetState(residence.id, "presenceDetected", false)
+ })
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
new file mode 100644
index 000000000..c9222ab05
--- /dev/null
+++ b/manager/src/main/resources/demo/rules/DemoResidenceVacationMode.groovy
@@ -0,0 +1,127 @@
+package demo.rules
+
+import groovy.transform.ToString
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+import org.openremote.model.asset.AssetState
+import org.openremote.model.rules.Assets
+
+import java.util.logging.Logger
+
+import static org.openremote.model.asset.AssetType.RESIDENCE
+import static org.openremote.model.asset.BaseAssetQuery.Operator.GREATER_THAN
+import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_EQUALS
+import static org.openremote.model.attribute.AttributeExecuteStatus.REQUEST_START
+
+Logger LOG = binding.LOG
+RulesBuilder rules = binding.rules
+Assets assets = binding.assets
+
+@ToString(includeNames = true)
+class VacationMode {
+ String residenceId
+ double until
+}
+
+rules.add()
+ .name("When residence has vacation until in future, add vacation mode, execute AWAY scene and disable scene timers")
+ .when(
+ { facts ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .attributeValue("vacationUntil", GREATER_THAN, facts.clock.timestamp)
+ ).filter({ residenceWithVacationUntil ->
+ facts.match(VacationMode).noneMatch({
+ vacationMode -> vacationMode.residenceId == residenceWithVacationUntil.id
+ })
+ }).findFirst().map({ residenceWithoutVacationMode ->
+ facts.bind("residenceId", residenceWithoutVacationMode.id)
+ .bind("vacationUntil", residenceWithoutVacationMode.valueAsNumber.get())
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ VacationMode vacationMode = new VacationMode(
+ residenceId: facts.bound("residenceId"),
+ until: facts.bound("vacationUntil")
+ )
+ LOG.info("Vacation mode enabled: " + vacationMode)
+
+ def vacationModeExpiresMillis = vacationMode.until - facts.clock.timestamp
+ facts.putTemporary(vacationModeExpiresMillis, vacationMode)
+
+ facts.updateAssetState(vacationMode.residenceId, "awayScene", REQUEST_START)
+ .updateAssetState(vacationMode.residenceId, "disableSceneTimer", REQUEST_START)
+ })
+
+rules.add()
+ .name("When residence has vacation until in past, clear it and enable scene timers")
+ .when(
+ { facts ->
+ facts.matchAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .attributeValue("vacationUntil", LESS_EQUALS, facts.clock.timestamp)
+ ).filter({ residenceWithVacationUntilInPast ->
+ residenceWithVacationUntilInPast.getValueAsNumber().isPresent()
+ }).filter({ residenceWithVacationUntilInPast ->
+ facts.match(VacationMode).noneMatch({
+ vacationMode -> vacationMode.residenceId == residenceWithVacationUntilInPast.id
+ })
+ }).findFirst().map({ residenceWithVacationUntilInPastWithoutVacationMode ->
+ facts.bind("residence", residenceWithVacationUntilInPastWithoutVacationMode)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ AssetState residence = facts.bound("residence")
+ LOG.info("Vacation ended in residence: " + residence.name)
+ facts.updateAssetState(residence.id, "vacationUntil")
+ assets.dispatch(residence.id, "enableSceneTimer", REQUEST_START)
+ })
+
+rules.add()
+ .name("Remove vacation mode when residence has different vacation until")
+ .when(
+ { facts ->
+ facts.matchFirst(VacationMode, { vacationMode ->
+ facts.matchFirstAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .id(vacationMode.residenceId)
+ .attributeValue("vacationUntil")
+ ).map({ residence ->
+ vacationMode.until != residence.valueAsNumber.get()
+ }).orElse(false)
+ }).map({ vacationMode ->
+ facts.bind("vacationMode", vacationMode)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ VacationMode vacationMode = facts.bound("vacationMode")
+ LOG.info("Removing outdated vacation mode: " + vacationMode)
+ facts.remove(vacationMode)
+ })
+
+rules.add()
+ .name("Remove vacation mode when residence has no vacation until, enable scene timers")
+ .when(
+ { facts ->
+ facts.matchFirst(VacationMode, { vacationMode ->
+ !facts.matchFirstAssetState(
+ new AssetQuery().type(RESIDENCE)
+ .id(vacationMode.residenceId)
+ .attributeValue("vacationUntil")).isPresent()
+ }).map({ vacationMode ->
+ facts.bind("vacationMode", vacationMode)
+ true
+ }).orElse(false)
+ })
+ .then(
+ { facts ->
+ VacationMode vacationMode = facts.bound("vacationMode")
+ LOG.info("Vacation mode disabled: " + vacationMode)
+ facts.remove(vacationMode)
+ })
\ No newline at end of file
diff --git a/manager/src/main/resources/logging.properties b/manager/src/main/resources/logging.properties
index aa5928ce5..3fff220e2 100644
--- a/manager/src/main/resources/logging.properties
+++ b/manager/src/main/resources/logging.properties
@@ -61,11 +61,11 @@ org.openremote.level=FINEST
# Rule execution logging
#
-# - Use "global java.util.logging.Logger LOG;" in rule RHS to access this logger
-# - Set to FINEST to automatically log all fact additions, removals, and updates
+# - Use "LOG" or "console" in your rules to access this logger
+# - Set to FINEST to automatically log all facts and when they are modified
# - Set to INFO and prefix your rule name with "-" or "--" to log execution details
#
-org.openremote.rules.Rules.level=FINE
+org.openremote.rules.Rules.level=FINEST
# Set to INFO to get rules engine statistics periodically, FINEST to dump all facts
org.openremote.rules.RulesEngineStats.level=INFO
@@ -101,3 +101,4 @@ org.xnio.level=WARNING
org.apache.camel.management.level=WARNING
org.apache.camel.impl.converter.DefaultTypeConverter.level=WARNING
org.apache.camel.impl.DefaultShutdownStrategy.level=SEVERE
+org.jeasy.rules.level=WARNING
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql
new file mode 100644
index 000000000..edef007bb
--- /dev/null
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20180119_01__Ruleset_Lang.sql
@@ -0,0 +1,8 @@
+alter table ASSET_RULESET
+ add column RULES_LANG varchar(255) not null default 'ECMASCRIPT_5_1';
+
+alter table GLOBAL_RULESET
+ add column RULES_LANG varchar(255) not null default 'ECMASCRIPT_5_1';
+
+alter table TENANT_RULESET
+ add column RULES_LANG varchar(255) not null default 'ECMASCRIPT_5_1';
diff --git a/model/build.gradle b/model/build.gradle
index c1a19dcf4..6c2cdfce3 100644
--- a/model/build.gradle
+++ b/model/build.gradle
@@ -13,9 +13,6 @@ dependencies {
compile "org.hibernate:hibernate-validator:$hibernateValidatorVersion"
compile "org.glassfish.web:javax.el:$javaxELVersion"
compile "org.jboss.logging:jboss-logging-annotations:$jbossLoggingAnnotationsVersion"
- compile("org.kie:kie-api:$droolsVersion") {
- exclude group: "org.slf4j"
- }
compile "org.jboss.spec.javax.annotation:jboss-annotations-api_1.2_spec:$javaxAnnotationsVersion"
compile "org.jboss.spec.javax.ws.rs:jboss-jaxrs-api_2.0_spec:$jaxrsSpecVersion"
@@ -23,6 +20,8 @@ dependencies {
compile "org.keycloak:keycloak-core:$keycloakVersion"
compile "org.keycloak:keycloak-core:$keycloakVersion:sources"
+
+ compile "org.jeasy:easy-rules-core:$easyRulesVersion"
}
jar {
diff --git a/model/src/main/java/org/openremote/model/ValidationFailure.java b/model/src/main/java/org/openremote/model/ValidationFailure.java
index f48ad2010..51fabf10a 100644
--- a/model/src/main/java/org/openremote/model/ValidationFailure.java
+++ b/model/src/main/java/org/openremote/model/ValidationFailure.java
@@ -55,36 +55,34 @@ public class ValidationFailure {
}
}
- @JsonProperty
- protected Reason reason;
- @JsonProperty // This is called param because GWT Jackson is crap at resolving annotations
- protected String param;
+ public Reason reason;
+ public String parameter;
+
+ protected ValidationFailure() {
+ }
public ValidationFailure(Reason reason) {
this(reason, null);
}
- @JsonCreator
- public ValidationFailure(@JsonProperty("reason") Reason reason, @JsonProperty("param") String parameter) {
+ public ValidationFailure(Reason reason, String parameter) {
this.reason = reason;
- this.param = parameter;
+ this.parameter = parameter;
}
- @JsonIgnore
public Reason getReason() {
return reason;
}
- @JsonIgnore
public Optional<String> getParameter() {
- return Optional.ofNullable(param);
+ return Optional.ofNullable(parameter);
}
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"reason=" + reason +
- ", param='" + param + '\'' +
+ ", param='" + parameter + '\'' +
'}';
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
index 3e5b1f598..6702b2379 100644
--- a/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
+++ b/model/src/main/java/org/openremote/model/asset/AbstractAssetUpdate.java
@@ -20,6 +20,7 @@
package org.openremote.model.asset;
+import javaemul.internal.annotations.GwtIncompatible;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.AttributeType;
@@ -28,6 +29,9 @@ import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
import org.openremote.model.value.Values;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.time.ZoneId;
import java.util.Date;
import java.util.Optional;
@@ -39,13 +43,14 @@ import static org.openremote.model.asset.AssetType.CUSTOM;
* This class layout is convenient for writing expressions that match getters, while
* carrying as much asset details as needed.
*/
-public abstract class AbstractAssetUpdate {
+@GwtIncompatible
+public abstract class AbstractAssetUpdate implements Comparable<AbstractAssetUpdate> {
- final protected AssetAttribute attribute;
+ final public AssetAttribute attribute;
- final protected Date createdOn;
+ final public Date createdOn;
- final protected String id;
+ final public String id;
final protected String name;
@@ -57,27 +62,29 @@ public abstract class AbstractAssetUpdate {
* The identifiers of all parents representing the path in the tree. The first element
* is the root asset without a parent, the last is the identifier of this instance.
*/
- final protected String[] pathFromRoot;
+ final public String[] path;
- final protected String parentId;
+ final public String parentId;
- final protected String parentName;
+ final public String parentName;
- final protected String parentTypeString;
+ final public String parentTypeString;
- final protected AssetType parentType;
+ final public AssetType parentType;
- final protected String realmId;
+ final public String realmId;
- final protected String tenantRealm;
+ final public String tenantRealm;
- final protected double[] coordinates;
+ final public double[] coordinates;
- final protected Value oldValue;
+ final public Value oldValue;
final protected long oldValueTimestamp;
- final protected AttributeEvent.Source source;
+ final public AttributeEvent.Source source;
+
+ final protected LocalDateTime time;
public AbstractAssetUpdate(Asset asset, AssetAttribute attribute, AttributeEvent.Source source) {
this(asset, attribute, null, 0, source);
@@ -91,7 +98,7 @@ public abstract class AbstractAssetUpdate {
asset.getName(),
asset.getType(),
asset.getWellKnownType(),
- asset.getReversePath(),
+ asset.getPath(),
asset.getParentId(),
asset.getParentName(),
asset.getParentType(),
@@ -113,7 +120,7 @@ public abstract class AbstractAssetUpdate {
that.name,
that.typeString,
that.type,
- that.pathFromRoot,
+ that.path,
that.parentId,
that.parentName,
that.parentTypeString,
@@ -129,7 +136,7 @@ public abstract class AbstractAssetUpdate {
protected AbstractAssetUpdate(AssetAttribute attribute,
Date createdOn, String id, String name, String typeString, AssetType type,
- String[] pathFromRoot, String parentId, String parentName, String parentTypeString, AssetType parentType,
+ String[] path, String parentId, String parentName, String parentTypeString, AssetType parentType,
String realmId, String tenantRealm,
double[] coordinates,
Value oldValue,
@@ -141,10 +148,10 @@ public abstract class AbstractAssetUpdate {
this.name = name;
this.typeString = typeString;
this.type = type;
- if (pathFromRoot == null) {
+ if (path == null) {
throw new IllegalArgumentException("Empty path (asset not completely loaded?): " + id);
}
- this.pathFromRoot = pathFromRoot;
+ this.path = path;
this.parentId = parentId;
this.parentName = parentName;
this.parentTypeString = parentTypeString;
@@ -155,6 +162,7 @@ public abstract class AbstractAssetUpdate {
this.oldValue = oldValue;
this.oldValueTimestamp = oldValueTimestamp;
this.source = source;
+ this.time = attribute.getValueTimestamp().map(ts -> LocalDateTime.ofInstant(Instant.ofEpochMilli(ts), ZoneId.systemDefault())).orElse(null);
}
public Date getCreatedOn() {
@@ -177,8 +185,8 @@ public abstract class AbstractAssetUpdate {
return type;
}
- public String[] getPathFromRoot() {
- return pathFromRoot;
+ public String[] getPath() {
+ return path;
}
public String getParentId() {
@@ -221,28 +229,28 @@ public abstract class AbstractAssetUpdate {
return source;
}
- public Value getValue() {
- return attribute.getValue().orElse(null);
+ public Optional<Value> getValue() {
+ return attribute.getValue();
}
- public Boolean getValueAsBoolean() {
- return attribute.getValueAsBoolean().orElse(null);
+ public Optional<Boolean> getValueAsBoolean() {
+ return attribute.getValueAsBoolean();
}
- public Double getValueAsNumber() {
- return attribute.getValueAsNumber().orElse(null);
+ public Optional<Double> getValueAsNumber() {
+ return attribute.getValueAsNumber();
}
- public String getValueAsString() {
- return attribute.getValueAsString().orElse(null);
+ public Optional<String> getValueAsString() {
+ return attribute.getValueAsString();
}
- public ObjectValue getValueAsObject() {
- return attribute.getValueAsObject().orElse(null);
+ public Optional<ObjectValue> getValueAsObject() {
+ return attribute.getValueAsObject();
}
- public ArrayValue getValueAsArray() {
- return attribute.getValueAsArray().orElse(null);
+ public Optional<ArrayValue> getValueAsArray() {
+ return attribute.getValueAsArray();
}
public AssetAttribute getAttribute() {
@@ -253,10 +261,14 @@ public abstract class AbstractAssetUpdate {
return attribute.getName().orElse(null);
}
- public long getValueTimestamp() {
+ public long getTimestamp() {
return attribute.getValueTimestamp().orElse(-1L);
}
+ public LocalDateTime getTime() {
+ return time;
+ }
+
public AttributeType getAttributeType() {
return attribute.getType().orElse(null);
}
@@ -266,47 +278,47 @@ public abstract class AbstractAssetUpdate {
}
/**
- * <code>true</code> if this value is not null and that value is null or this value is greater than that value.
+ * <code>true</code> if this value is not empty and that value is null or this value is greater than that value.
*/
public boolean isValueGreaterThan(Number that) {
- Double number = getValueAsNumber();
- return (number != null && that == null) || (number != null && number > that.doubleValue());
+ Optional<Double> number = getValueAsNumber();
+ return (number.isPresent() && that == null) || (number.isPresent() && number.get() > that.doubleValue());
}
/**
- * <code>true</code> if this value is not null and the old value is null or this value is greater than old value.
+ * <code>true</code> if this value is not empty and the old value is null or this value is greater than old value.
*/
public boolean isValueGreaterThanOldValue() {
return isValueGreaterThan(Values.getNumber(getOldValue()).orElse(null));
}
/**
- * <code>true</code> if this value is null and that value is not null or this value is less than that value.
+ * <code>true</code> if this value is empty and that value is not null or this value is less than that value.
*/
public boolean isValueLessThan(Number that) {
- Double number = getValueAsNumber();
- return (number == null && that != null) || (number != null && number < that.doubleValue());
+ Optional<Double> number = getValueAsNumber();
+ return (!number.isPresent() && that != null) || (number.isPresent() && number.get() < that.doubleValue());
}
/**
- * <code>true</code> if this value is null and the old value is not null or this value is less than old value.
+ * <code>true</code> if this value is empty and the old value is not null or this value is less than old value.
*/
public boolean isValueLessThanOldValue() {
return isValueLessThan(Values.getNumber(getOldValue()).orElse(null));
}
/**
- * Value is null or {@link org.openremote.model.value.BooleanValue} <code>false</code>.
+ * Value is empty or {@link org.openremote.model.value.BooleanValue} <code>false</code>.
*/
public boolean isValueFalse() {
- return getValueAsBoolean() == null || !getValueAsBoolean();
+ return !getValueAsBoolean().isPresent() || !getValueAsBoolean().get();
}
/**
- * Value is not null and {@link org.openremote.model.value.BooleanValue} <code>true</code>.
+ * Value is not empty and {@link org.openremote.model.value.BooleanValue} <code>true</code>.
*/
public boolean isValueTrue() {
- return getValueAsBoolean() != null && getValueAsBoolean();
+ return getValueAsBoolean().isPresent() && getValueAsBoolean().get();
}
public AttributeRef getAttributeRef() {
@@ -323,18 +335,21 @@ public abstract class AbstractAssetUpdate {
/**
* Compares entity identifier, attribute name, value, source, and optional timestamp.
*/
- public boolean matches(AttributeEvent event, AttributeEvent.Source source, boolean ignoreTimestamp) {
- return event.getAttributeRef().equals(getAttributeRef())
- && Optional.ofNullable(getValue()).equals(event.getAttributeState().getCurrentValue())
- && (ignoreTimestamp || getValueTimestamp() == event.getTimestamp())
+ public boolean matches(AttributeEvent that, AttributeEvent.Source source, boolean ignoreTimestamp) {
+ return getAttributeRef().equals(that.getAttributeRef())
+ && getValue().equals(that.getValue())
+ && (ignoreTimestamp || getTimestamp() == that.getTimestamp())
&& (source == null || getSource() == source);
}
- /**
- * This is here because {@link #attribute} is not always publicly accessible
- */
- public boolean attributeRefsEqual(AbstractAssetUpdate assetUpdate) {
- return assetUpdate != null && assetUpdate.getAttributeRef().equals(getAttributeRef());
+ @Override
+ public int compareTo(AbstractAssetUpdate that) {
+ int result = getId().compareTo(that.getId());
+ if (result == 0)
+ result = getAttributeName().compareTo(that.getAttributeName());
+ if (result == 0)
+ result = Long.compare(getTimestamp(), that.getTimestamp());
+ return result;
}
@Override
@@ -345,21 +360,13 @@ public abstract class AbstractAssetUpdate {
AbstractAssetUpdate that = (AbstractAssetUpdate) o;
return getId().equals(that.getId()) &&
- getAttribute().getName().equals(that.getAttribute().getName()) &&
- getAttribute().getValue().equals(that.getAttribute().getValue()) &&
- getValueTimestamp() == that.getValueTimestamp() &&
- Optional.ofNullable(getOldValue()).equals(Optional.ofNullable(that.getOldValue())) &&
- getOldValueTimestamp() == that.getOldValueTimestamp();
+ getAttribute().getName().equals(that.getAttribute().getName());
}
@Override
public int hashCode() {
return getId().hashCode()
- + getAttributeName().hashCode()
- + getAttribute().getValue().hashCode()
- + Long.hashCode(getValueTimestamp())
- + Optional.ofNullable(getOldValue()).hashCode()
- + Long.hashCode(getOldValueTimestamp());
+ + getAttributeName().hashCode();
}
@Override
@@ -371,8 +378,9 @@ public abstract class AbstractAssetUpdate {
", typeString='" + getType() + '\'' +
", attributeName='" + getAttributeName() + '\'' +
", attributeType=" + getAttributeType() +
- ", value='" + (getValue() != null ? getValue().toJson() : "null") + '\'' +
- ", valueTimestamp=" + getValueTimestamp() +
+ ", value='" + (getValue().isPresent() ? getValue().get().toJson() : "null") + '\'' + // TODO Performance?
+ ", timestamp=" + getTimestamp() +
+ ", time=" + getTime() +
", oldValue='" + (getOldValue() != null ? getOldValue().toJson() : "null") + '\'' +
", oldValueTimestamp=" + getOldValueTimestamp() +
", source=" + getSource() +
diff --git a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
index 7f030d74e..a38afdb8e 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetAttribute.java
@@ -19,7 +19,6 @@
*/
package org.openremote.model.asset;
-import com.fasterxml.jackson.annotation.JsonIgnore;
import org.openremote.model.AbstractValueHolder;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.*;
@@ -86,7 +85,6 @@ public class AssetAttribute extends Attribute {
setAssetId(assetId);
}
- @JsonIgnore
public Optional<String> getAssetId() {
return Optional.ofNullable(assetId);
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetEvent.java b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
index cf8904956..ec1011366 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetEvent.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetEvent.java
@@ -19,24 +19,48 @@
*/
package org.openremote.model.asset;
-import org.kie.api.definition.type.Role;
+import org.openremote.model.rules.TemporaryFact;
+import org.openremote.model.util.TimeUtil;
import java.util.Optional;
/**
* An asset attribute value change as a punctual event in rules processing.
*/
[email protected](Role.Type.EVENT)
[email protected]("valueTimestamp")
-// TODO Bug in drools, it fails if there is no @Expires annotation https://issues.jboss.org/browse/DROOLS-2182
[email protected](value = "10000d")
-public class AssetEvent extends AbstractAssetUpdate {
+public class AssetEvent extends AbstractAssetUpdate implements TemporaryFact {
- public AssetEvent(AbstractAssetUpdate that) {
+ final protected long expirationMilliseconds;
+
+ public AssetEvent(AbstractAssetUpdate that, String expires) {
super(that);
+ this.expirationMilliseconds = TimeUtil.parseTimeString(expires);
+ }
+
+ @Override
+ public long getExpirationMilliseconds() {
+ return expirationMilliseconds;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AssetEvent that = (AssetEvent) o;
+
+ return getAttributeRef().equals(that.getAttributeRef()) &&
+ getAttribute().getValue().equals(that.getAttribute().getValue()) &&
+ getTimestamp() == that.getTimestamp() &&
+ Optional.ofNullable(getOldValue()).equals(Optional.ofNullable(that.getOldValue())) &&
+ getOldValueTimestamp() == that.getOldValueTimestamp();
}
- public Optional<String> getExpires() {
- return attribute.getRuleEventExpires();
+ @Override
+ public int hashCode() {
+ return getAttributeRef().hashCode()
+ + getAttribute().getValue().hashCode()
+ + Long.hashCode(getTimestamp())
+ + Optional.ofNullable(getOldValue()).hashCode()
+ + Long.hashCode(getOldValueTimestamp());
}
}
diff --git a/model/src/main/java/org/openremote/model/asset/AssetMeta.java b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
index 5281f4161..54d2103dd 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetMeta.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetMeta.java
@@ -21,7 +21,10 @@ package org.openremote.model.asset;
import org.openremote.model.ValidationFailure;
import org.openremote.model.attribute.*;
-import org.openremote.model.value.*;
+import org.openremote.model.rules.TemporaryFact;
+import org.openremote.model.value.Value;
+import org.openremote.model.value.ValueType;
+import org.openremote.model.value.Values;
import java.util.Optional;
import java.util.function.Function;
@@ -72,7 +75,6 @@ public enum AssetMeta implements MetaItemDescriptor {
: new ValidationFailure(META_ITEM_VALUE_MISMATCH, AttributeRef.class.getSimpleName()))
),
-
/**
* Links an attribute to the location of the owning {@link Asset}; this is intended to be coupled with
* {@link #AGENT_LINK} to allow protocols to write an {@link Asset}'s location.
@@ -286,10 +288,10 @@ public enum AssetMeta implements MetaItemDescriptor {
true),
/**
- * Should attribute writes be processed by the rules engines as {@link AssetState} facts in knowledge sessions,
- * with a lifecycle that reflects the state of the asset attribute. The state facts in the rules sessions are kept
+ * Should attribute writes be processed by the rules engines as {@link AssetState} facts,
+ * with a lifecycle that reflects the state of the asset attribute. The state facts are kept
* in sync with asset changes: For an attribute there will always be a single fact that is updated
- * when the attribute is updated. If you want two types of facts in your rules knowledge session for a single
+ * when the attribute is updated. If you want two types of facts in your rules for a single
* attribute, with state and event behavior, combine this with {@link #RULE_EVENT}.
*/
RULE_STATE(
@@ -302,10 +304,10 @@ public enum AssetMeta implements MetaItemDescriptor {
true),
/**
- * Should attribute writes be processed by the rules engines as events in knowledge sessions. Any attribute
- * update will be inserted as an {@link AssetEvent} fact in the rules sessions, these events are expired
+ * Should attribute writes be processed by the rules engines as event facts. Any attribute
+ * update will be inserted as an {@link AssetEvent} fact in a rules engine, these events are expired
* automatically after a defined time and/or if they can no longer be matched by rule LHS time constraints.
- * If you want two types of facts in your rules knowledge session for a single attribute, with state and event
+ * If you want two types of facts in your rules for a single attribute, with state and event
* behavior, combine this with {@link #RULE_STATE}.
*/
RULE_EVENT(
@@ -318,15 +320,19 @@ public enum AssetMeta implements MetaItemDescriptor {
true),
/**
- * Set maximum lifetime of {@link AssetEvent} facts in knowledge sessions, for example "1h30m". The rules
- * engine will remove {@link AssetEvent} facts from the rules sessions if they are older than this value
- * (using event source timestamp, not event processing time).
+ * Set maximum lifetime of {@link AssetEvent} facts in rules, for example "1h30m5s". The rules
+ * engine will remove {@link AssetEvent} facts if they are older than this value (using event source/value
+ * timestamp, not event processing time).
+ * <p>
+ * The default expiration for asset events can be configured with environment variable <code>RULE_EVENT_EXPIRES</code>.
+ * <p>
+ * Also see {@link TemporaryFact#GUARANTEED_MIN_EXPIRATION_MILLIS}.
*/
RULE_EVENT_EXPIRES(
ASSET_META_NAMESPACE + ":ruleEventExpires",
new Access(true, false, true),
ValueType.STRING,
- "^([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?$", // From DROOLS
+ "^([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?$", // See TimeUtil
PatternFailure.DAYS_HOURS_MINS_SECONDS.name(),
null,
false),
diff --git a/model/src/main/java/org/openremote/model/asset/AssetState.java b/model/src/main/java/org/openremote/model/asset/AssetState.java
index f3fc73b16..0b754dccc 100644
--- a/model/src/main/java/org/openremote/model/asset/AssetState.java
+++ b/model/src/main/java/org/openremote/model/asset/AssetState.java
@@ -104,4 +104,19 @@ public class AssetState extends AbstractAssetUpdate {
throw new IllegalStateException("Instance is immutable, processing status '" + getProcessingStatus() + "': " + this);
}
}
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) return true;
+ if (o == null || getClass() != o.getClass()) return false;
+
+ AssetState that = (AssetState) o;
+
+ return getAttributeRef().equals(that.getAttributeRef());
+ }
+
+ @Override
+ public int hashCode() {
+ return getAttributeRef().hashCode();
+ }
}
diff --git a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java
index 00b854cc6..3117a8143 100644
--- a/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java
+++ b/model/src/main/java/org/openremote/model/asset/BaseAssetQuery.java
@@ -19,19 +19,24 @@
*/
package org.openremote.model.asset;
-import com.fasterxml.jackson.annotation.JsonSubTypes;
-import com.fasterxml.jackson.annotation.JsonTypeInfo;
+import com.fasterxml.jackson.annotation.*;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.attribute.MetaItemDescriptor;
+import org.openremote.model.value.Value;
import java.util.Arrays;
import java.util.Locale;
+import java.util.function.Predicate;
+
+import static org.openremote.model.asset.BaseAssetQuery.Operator.EQUALS;
+import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_EQUALS;
+import static org.openremote.model.asset.BaseAssetQuery.Operator.LESS_THAN;
/**
* Encapsulate asset query restriction, projection, and ordering of results.
*/
@SuppressWarnings("unchecked")
-public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
+public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> implements Predicate<AbstractAssetUpdate> {
public enum Include {
ALL_EXCEPT_PATH_AND_ATTRIBUTES,
@@ -109,6 +114,9 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
+ /**
+ * String matching options
+ */
public enum Match {
EXACT,
BEGIN,
@@ -130,11 +138,14 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public enum OperatorMatch {
- EXACT,
- GREATER_THEN,
+ /**
+ * Binary operators
+ */
+ public enum Operator {
+ EQUALS,
+ GREATER_THAN,
GREATER_EQUALS,
- LESS_THEN,
+ LESS_THAN,
LESS_EQUALS,
BETWEEN
}
@@ -156,10 +167,18 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
include = JsonTypeInfo.As.PROPERTY,
property = "predicateType"
)
- public interface ValuePredicate {
+ public interface ValuePredicate<T> extends Predicate<T> {
+ }
+
+ public static class ValueNotEmptyPredicate implements ValuePredicate<Value> {
+
+ @Override
+ public boolean test(Value value) {
+ return value != null;
+ }
}
- public static class StringPredicate implements ValuePredicate {
+ public static class StringPredicate implements ValuePredicate<String> {
public Match match = Match.EXACT;
public boolean caseSensitive = true;
public String value;
@@ -204,6 +223,29 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return s;
}
+ @Override
+ public boolean test(String string) {
+ if (string == null && value == null)
+ return true;
+ if (string == null)
+ return false;
+ if (value == null)
+ return false;
+
+ String have = caseSensitive ? value : value.toUpperCase(Locale.ROOT);
+ String given = caseSensitive ? string : string.toUpperCase(Locale.ROOT);
+
+ switch (match) {
+ case BEGIN:
+ return have.startsWith(given);
+ case END:
+ return have.endsWith(given);
+ case CONTAINS:
+ return have.contains(given);
+ }
+ return have.equals(given);
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -214,30 +256,38 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public static class BooleanPredicate implements ValuePredicate {
- public boolean predicate;
+ public static class BooleanPredicate implements ValuePredicate<Boolean> {
+ public boolean value;
public BooleanPredicate() {
}
- public BooleanPredicate(boolean predicate) {
- this.predicate = predicate;
+ public BooleanPredicate(boolean value) {
+ this.value = value;
}
- public BooleanPredicate predicate(boolean predicate) {
- this.predicate = predicate;
+ public BooleanPredicate value(boolean value) {
+ this.value = value;
return this;
}
+ @Override
+ public boolean test(Boolean b) {
+ // If given a null, we assume it's false!
+ if (b == null)
+ b = false;
+ return b == value;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "predicate=" + predicate +
+ "predicate=" + value +
'}';
}
}
- public static class StringArrayPredicate implements ValuePredicate {
+ public static class StringArrayPredicate implements ValuePredicate<String[]> {
public StringPredicate[] predicates = new StringPredicate[0];
public StringArrayPredicate() {
@@ -252,6 +302,24 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return this;
}
+ @Override
+ public boolean test(String[] strings) {
+ if (strings == null && predicates == null)
+ return true;
+ if (strings == null)
+ return false;
+ if (predicates == null)
+ return false;
+ if (strings.length != predicates.length)
+ return false;
+ for (int i = 0; i < predicates.length; i++) {
+ StringPredicate predicate = predicates[i];
+ if (!predicate.test(strings[i]))
+ return false;
+ }
+ return true;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -260,28 +328,28 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public static class DateTimePredicate implements ValuePredicate {
- public OperatorMatch operatorMatch = OperatorMatch.EXACT;
- public String dateFormat = "YYYY-MM-DD HH24:MI:SS";//postgres dateformat
+ public static class DateTimePredicate implements ValuePredicate<Long> {
public String value;
- public String rangeValue;//used when operatorMatch is Between as end date
+ public String rangeValue; // Used as upper bound when Operator.BETWEEN
+ public Operator operator = Operator.EQUALS;
+ public String dateFormat = "YYYY-MM-DD HH24:MI:SS";//postgres dateformat
public DateTimePredicate() {
}
- public DateTimePredicate(OperatorMatch operatorMatch, String value) {
- this.operatorMatch = operatorMatch;
+ public DateTimePredicate(Operator operator, String value) {
+ this.operator = operator;
this.value = value;
}
public DateTimePredicate(String afterValue, String beforeValue) {
- this.operatorMatch = OperatorMatch.BETWEEN;
+ this.operator = Operator.BETWEEN;
this.value = afterValue;
this.rangeValue = beforeValue;
}
- public DateTimePredicate dateMatch(OperatorMatch dateMatch) {
- this.operatorMatch = dateMatch;
+ public DateTimePredicate dateMatch(Operator dateMatch) {
+ this.operator = dateMatch;
return this;
}
@@ -296,26 +364,31 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
public DateTimePredicate rangeValue(String beforeValue) {
- this.operatorMatch = OperatorMatch.BETWEEN;
+ this.operator = Operator.BETWEEN;
this.rangeValue = beforeValue;
return this;
}
+ @Override
+ public boolean test(Long aLong) {
+ throw new UnsupportedOperationException("NOT IMPLEMENTED");
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
- "operatorMatch=" + operatorMatch +
- ", dateFormat='" + dateFormat + '\'' +
- ", value='" + value + '\'' +
+ "value='" + value + '\'' +
", rangeValue='" + rangeValue + '\'' +
+ ", operator =" + operator +
+ ", dateFormat='" + dateFormat + '\'' +
'}';
}
}
- public static class NumberPredicate implements ValuePredicate {
+ public static class NumberPredicate implements ValuePredicate<Double> {
public double value;
- public double rangeValue; //used when operatorMatch is Between as second value
- public OperatorMatch operatorMatch = OperatorMatch.EXACT;
+ public double rangeValue; // Used as upper bound when Operator.BETWEEN
+ public Operator operator = Operator.EQUALS;
public NumberType numberType = NumberType.DOUBLE;
public NumberPredicate() {
@@ -325,9 +398,9 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
this.value = value;
}
- public NumberPredicate(double value, OperatorMatch operatorMatch) {
+ public NumberPredicate(double value, Operator operator) {
this.value = value;
- this.operatorMatch = operatorMatch;
+ this.operator = operator;
}
public NumberPredicate(double value, NumberType numberType) {
@@ -335,9 +408,9 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
this.numberType = numberType;
}
- public NumberPredicate(double value, OperatorMatch operatorMatch, NumberType numberType) {
+ public NumberPredicate(double value, Operator operator, NumberType numberType) {
this.value = value;
- this.operatorMatch = operatorMatch;
+ this.operator = operator;
this.numberType = numberType;
}
@@ -346,8 +419,8 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return this;
}
- public NumberPredicate numberMatch(OperatorMatch operatorMatch) {
- this.operatorMatch = operatorMatch;
+ public NumberPredicate numberMatch(Operator operator) {
+ this.operator = operator;
return this;
}
@@ -357,23 +430,55 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
public NumberPredicate rangeValue(double rangeValue) {
- this.operatorMatch = OperatorMatch.BETWEEN;
+ this.operator = Operator.BETWEEN;
this.rangeValue = rangeValue;
return this;
}
+ @Override
+ public boolean test(Double d) {
+ if (d == null) {
+
+ // If given a null and we want to know if it's "less than x", it's always less than x
+ // TODO Should be consistent with BETWEEN behavior?
+ if (operator == LESS_THAN || operator == LESS_EQUALS) {
+ return true;
+ }
+
+ return false;
+ }
+
+ Number leftOperand = numberType == NumberType.DOUBLE ? d : d.intValue();
+ Number rightOperand = numberType == NumberType.DOUBLE ? value : (int) value;
+ switch (operator) {
+ case EQUALS:
+ return leftOperand.equals(rightOperand);
+ case BETWEEN:
+ return leftOperand.doubleValue() >= rightOperand.doubleValue() && leftOperand.doubleValue() <= rangeValue;
+ case LESS_THAN:
+ return leftOperand.doubleValue() < rightOperand.doubleValue();
+ case LESS_EQUALS:
+ return leftOperand.doubleValue() <= rightOperand.doubleValue();
+ case GREATER_THAN:
+ return leftOperand.doubleValue() > rightOperand.doubleValue();
+ case GREATER_EQUALS:
+ return leftOperand.doubleValue() >= rightOperand.doubleValue();
+ }
+ return false;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"value=" + value +
", rangeValue=" + rangeValue +
- ", operatorMatch=" + operatorMatch +
+ ", operator=" + operator +
", numberType=" + numberType +
'}';
}
}
- public static class ParentPredicate {
+ public static class ParentPredicate implements Predicate<AbstractAssetUpdate> {
public String id;
public String type;
public boolean noParent;
@@ -408,6 +513,13 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return this;
}
+ @Override
+ public boolean test(AbstractAssetUpdate assetUpdate) {
+ return (id == null || id.equals(assetUpdate.getParentId()))
+ && (type == null || type.equals(assetUpdate.getParentTypeString()))
+ && (!noParent || assetUpdate.getParentId() == null);
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -418,7 +530,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public static class PathPredicate {
+ public static class PathPredicate implements Predicate<String[]> {
public String[] path;
public PathPredicate() {
@@ -437,6 +549,11 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return path != null && path.length > 0;
}
+ @Override
+ public boolean test(String[] givenPath) {
+ return Arrays.equals(path, givenPath);
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -445,7 +562,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public static class TenantPredicate {
+ public static class TenantPredicate implements Predicate<AbstractAssetUpdate> {
public String realmId;
public String realm;
@@ -466,6 +583,12 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return this;
}
+ @Override
+ public boolean test(AbstractAssetUpdate assetUpdate) {
+ return (realm == null || realm.equals(assetUpdate.getTenantRealm()))
+ && (realmId == null || realmId.equals(assetUpdate.getRealmId()));
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -475,13 +598,17 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
}
- public static class AttributePredicate {
+ public static class AttributePredicate implements Predicate<AbstractAssetUpdate> {
public StringPredicate name;
public ValuePredicate value;
public AttributePredicate() {
}
+ public AttributePredicate(String name) {
+ this(new StringPredicate(name));
+ }
+
public AttributePredicate(StringPredicate name) {
this.name = name;
}
@@ -505,6 +632,42 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return this;
}
+ @Override
+ public boolean test(AbstractAssetUpdate assetUpdate) {
+ if (name != null && !name.test(assetUpdate.getAttributeName()))
+ return false;
+
+ if (value == null)
+ return true;
+
+ if (value instanceof AssetQuery.ValueNotEmptyPredicate) {
+
+ AssetQuery.ValueNotEmptyPredicate predicate = (AssetQuery.ValueNotEmptyPredicate) value;
+ return predicate.test(assetUpdate.getValue().orElse(null));
+
+ } else if (value instanceof AssetQuery.StringPredicate) {
+
+ AssetQuery.StringPredicate predicate = (AssetQuery.StringPredicate) value;
+ return predicate.test(assetUpdate.getValueAsString().orElse(null));
+
+ } else if (value instanceof AssetQuery.BooleanPredicate) {
+
+ AssetQuery.BooleanPredicate predicate = (AssetQuery.BooleanPredicate) value;
+ return predicate.test(assetUpdate.getValueAsBoolean().orElse(null));
+
+ } else if (value instanceof AssetQuery.NumberPredicate) {
+
+ AssetQuery.NumberPredicate predicate = (AssetQuery.NumberPredicate) value;
+ return predicate.test(assetUpdate.getValueAsNumber().orElse(null));
+
+ } else {
+ // TODO Implement more
+ throw new UnsupportedOperationException(
+ "Restriction by attribute value not implemented in rules matching for " + value.getClass()
+ );
+ }
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
@@ -658,14 +821,14 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
// Restriction predicates
public String id;
- public StringPredicate namePredicate;
- public ParentPredicate parentPredicate;
- public PathPredicate pathPredicate;
- public TenantPredicate tenantPredicate;
+ public StringPredicate name;
+ public ParentPredicate parent;
+ public PathPredicate path;
+ public TenantPredicate tenant;
public String userId;
public StringPredicate type;
- public AttributePredicate[] attributePredicates;
- public AttributeMetaPredicate[] attributeMetaPredicates;
+ public AttributePredicate[] attribute;
+ public AttributeMetaPredicate[] attributeMeta;
// Ordering
public OrderBy orderBy;
@@ -692,7 +855,7 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
public CHILD name(StringPredicate name) {
- this.namePredicate = name;
+ this.name = name;
return (CHILD) this;
}
@@ -705,17 +868,17 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
}
public CHILD parent(ParentPredicate parentPredicate) {
- this.parentPredicate = parentPredicate;
+ this.parent = parentPredicate;
return (CHILD) this;
}
public CHILD path(PathPredicate pathPredicate) {
- this.pathPredicate = pathPredicate;
+ this.path = pathPredicate;
return (CHILD) this;
}
public CHILD tenant(TenantPredicate tenantPredicate) {
- this.tenantPredicate = tenantPredicate;
+ this.tenant = tenantPredicate;
return (CHILD) this;
}
@@ -729,17 +892,60 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return (CHILD) this;
}
+ public CHILD type(String type) {
+ return type(new StringPredicate(type));
+ }
+
public CHILD type(AssetType assetType) {
return type(new StringPredicate(assetType.getValue()));
}
public CHILD attributes(AttributePredicate... attributePredicates) {
- this.attributePredicates = attributePredicates;
+ this.attribute = attributePredicates;
return (CHILD) this;
}
+ public CHILD attributeName(String attributeName) {
+ return attributes(new AttributePredicate(attributeName));
+ }
+
+ /**
+ * Match non-empty attribute value.
+ */
+ public CHILD attributeValue(String name) {
+ return attributes(new AttributePredicate(new StringPredicate(name), new ValueNotEmptyPredicate()));
+ }
+
+ public CHILD attributeValue(String name, ValuePredicate valuePredicate) {
+ return attributes(new AttributePredicate(new StringPredicate(name), valuePredicate));
+ }
+
+ public CHILD attributeValue(String name, boolean b) {
+ return attributeValue(name, new BooleanPredicate(b));
+ }
+
+ public CHILD attributeValue(String name, String s) {
+ return attributeValue(name, new StringPredicate(s));
+ }
+
+ public CHILD attributeValue(String name, Match match, String s) {
+ return attributeValue(name, new StringPredicate(match, s));
+ }
+
+ public CHILD attributeValue(String name, Match match, boolean caseSensitive, String s) {
+ return attributeValue(name, new StringPredicate(match, caseSensitive, s));
+ }
+
+ public CHILD attributeValue(String name, double d) {
+ return attributeValue(name, new NumberPredicate(d));
+ }
+
+ public CHILD attributeValue(String name, Operator operator, double d) {
+ return attributeValue(name, new NumberPredicate(d, operator));
+ }
+
public CHILD attributeMeta(AttributeMetaPredicate... attributeMetaPredicates) {
- this.attributeMetaPredicates = attributeMetaPredicates;
+ this.attributeMeta = attributeMetaPredicates;
return (CHILD) this;
}
@@ -748,19 +954,57 @@ public class BaseAssetQuery<CHILD extends BaseAssetQuery<CHILD>> {
return (CHILD) this;
}
+ @Override
+ public boolean test(AbstractAssetUpdate assetUpdate) {
+ if (id != null && !id.equals(assetUpdate.getId()))
+ return false;
+
+ if (name != null && !name.test(assetUpdate.getName()))
+ return false;
+
+ if (parent != null && !parent.test(assetUpdate))
+ return false;
+
+ if (path != null && !path.test(assetUpdate.getPath()))
+ return false;
+
+ if (tenant != null && !tenant.test(assetUpdate))
+ return false;
+
+ if (userId != null) {
+ // TODO Would require linked user IDs in AbstractAssetUpdate
+ throw new UnsupportedOperationException("Restriction by user ID not implemented in rules matching");
+ }
+ if (type != null && !type.test(assetUpdate.getTypeString()))
+ return false;
+
+ if (attribute != null) {
+ for (BaseAssetQuery.AttributePredicate attributePredicate : attribute) {
+ if (!attributePredicate.test(assetUpdate))
+ return false;
+ }
+ }
+
+ if (attributeMeta != null) {
+ // TODO Would require meta items in AbstractAssetUpdate
+ throw new UnsupportedOperationException("Restriction by attribute meta not implemented in rules matching");
+ }
+ return true;
+ }
+
@Override
public String toString() {
return getClass().getSimpleName() + "{" +
"select=" + select +
", id='" + id + '\'' +
- ", namePredicate=" + namePredicate +
- ", parentPredicate=" + parentPredicate +
- ", pathPredicate=" + pathPredicate +
- ", tenantPredicate=" + tenantPredicate +
+ ", name=" + name +
+ ", parent=" + parent +
+ ", path=" + path +
+ ", tenant=" + tenant +
", userId='" + userId + '\'' +
", type=" + type +
- ", attributePredicates=" + Arrays.toString(attributePredicates) +
- ", attributeMetaPredicates=" + Arrays.toString(attributeMetaPredicates) +
+ ", attribute=" + Arrays.toString(attribute) +
+ ", attributeMeta=" + Arrays.toString(attributeMeta) +
", orderBy=" + orderBy +
'}';
}
diff --git a/model/src/main/java/org/openremote/model/attribute/Attribute.java b/model/src/main/java/org/openremote/model/attribute/Attribute.java
index 66506aa95..a416e02bd 100644
--- a/model/src/main/java/org/openremote/model/attribute/Attribute.java
+++ b/model/src/main/java/org/openremote/model/attribute/Attribute.java
@@ -59,12 +59,11 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
public static final String TYPE_FIELD_NAME = "type";
public static final String META_FIELD_NAME = "meta";
+ public String name;
+
@JsonIgnore
protected Meta meta;
- @JsonProperty
- protected String name;
-
protected Attribute(ObjectValue objectValue) {
super(objectValue);
}
@@ -91,17 +90,10 @@ public abstract class Attribute extends AbstractValueTimestampHolder {
setValue(value);
}
- @JsonIgnore
public Optional<String> getName() {
return Optional.ofNullable(name);
}
- // Only here for GWT jackson
- @JsonProperty("name")
- private String getNamePrivate() {
- return name;
- }
-
public void setName(String name) {
requireNonNullAndNonEmpty(name);
this.name = name;
diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeLink.java b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
index 534100945..6381c034c 100644
--- a/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
+++ b/model/src/main/java/org/openremote/model/attribute/AttributeLink.java
@@ -19,8 +19,6 @@
*/
package org.openremote.model.attribute;
-import com.fasterxml.jackson.annotation.JsonIgnore;
-import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.value.ObjectValue;
import org.openremote.model.value.Value;
import org.openremote.model.value.ValueType;
@@ -106,7 +104,6 @@ public class AttributeLink {
return attributeRef;
}
- @JsonIgnore
public Optional<ObjectValue> getConverter() {
return Optional.ofNullable(converter);
}
@@ -115,12 +112,6 @@ public class AttributeLink {
this.converter = converter;
}
- // For GWT jackson only
- @JsonProperty("converter")
- private ObjectValue getConverterPrivate() {
- return converter;
- }
-
public ObjectValue toObjectValue() {
ObjectValue objectValue = Values.createObject();
objectValue.put("attributeRef", getAttributeRef().toArrayValue());
diff --git a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
index 23586792a..84b016bfe 100644
--- a/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/AssetRuleset.java
@@ -47,16 +47,16 @@ public class AssetRuleset extends Ruleset {
}
public AssetRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String assetId) {
- this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, null, assetId);
+ this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, Lang.JAVASCRIPT, null, assetId);
}
- public AssetRuleset(String name, String assetId, String rules) {
- super(name, rules);
+ public AssetRuleset(String name, String assetId, String rules, Lang lang) {
+ super(name, rules, lang);
this.assetId = assetId;
}
- public AssetRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, String assetId, String realmId) {
- super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules);
+ public AssetRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang, String assetId, String realmId) {
+ super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules, lang);
this.assetId = assetId;
this.realmId = realmId;
}
@@ -83,6 +83,7 @@ public class AssetRuleset extends Ruleset {
"id='" + id + '\'' +
", version='" + version + '\'' +
", name='" + name + '\'' +
+ ", lang='" + lang + '\'' +
", createdOn='" + createdOn + '\'' +
", lastModified='" + lastModified + '\'' +
", enabled='" + enabled + '\'' +
diff --git a/model/src/main/java/org/openremote/model/rules/Assets.java b/model/src/main/java/org/openremote/model/rules/Assets.java
index 16b9e1aca..a3befe267 100644
--- a/model/src/main/java/org/openremote/model/rules/Assets.java
+++ b/model/src/main/java/org/openremote/model/rules/Assets.java
@@ -19,11 +19,12 @@
*/
package org.openremote.model.rules;
-import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.asset.BaseAssetQuery;
+import org.openremote.model.attribute.AttributeEvent;
+import org.openremote.model.attribute.AttributeExecuteStatus;
+import org.openremote.model.value.Value;
-import java.util.List;
-import java.util.function.Consumer;
+import java.util.stream.Stream;
/**
* Facade for writing rules RHS actions, supporting asset queries within the scope
@@ -35,16 +36,23 @@ public abstract class Assets {
abstract public String getResult();
- abstract public List<String> getResults();
+ abstract public Stream<String> stream();
+ }
- abstract public void applyResult(Consumer<String> assetIdConsumer);
+ abstract public RestrictedQuery query();
- abstract public void applyResults(Consumer<List<String>> assetIdListConsumer);
+ abstract public Assets dispatch(AttributeEvent... event);
- }
+ abstract public Assets dispatch(String assetId, String attributeName, Value value);
- abstract public RestrictedQuery query();
+ abstract public Assets dispatch(String assetId, String attributeName, String value);
+
+ abstract public Assets dispatch(String assetId, String attributeName, double value);
+
+ abstract public Assets dispatch(String assetId, String attributeName, boolean value);
+
+ abstract public Assets dispatch(String assetId, String attributeName, AttributeExecuteStatus status);
- abstract public void dispatch(AttributeEvent... event);
+ abstract public Assets dispatch(String assetId, String attributeName);
}
diff --git a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
index 454a02c5b..8f63bedef 100644
--- a/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/GlobalRuleset.java
@@ -37,18 +37,25 @@ public class GlobalRuleset extends Ruleset {
super(id, version, createdOn, lastModified, name, enabled, templateAssetId);
}
- public GlobalRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules) {
- super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules);
+ public GlobalRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang) {
+ super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules, lang);
}
- public GlobalRuleset(String name, String rules) {
- super(name, rules);
+ public GlobalRuleset(String name, String rules, Lang lang) {
+ super(name, rules, lang);
}
@Override
public String toString() {
- return getClass().getSimpleName() + "{}";
+ return getClass().getSimpleName() + "{" +
+ "id='" + id + '\'' +
+ ", version='" + version + '\'' +
+ ", name='" + name + '\'' +
+ ", lang='" + lang + '\'' +
+ ", createdOn='" + createdOn + '\'' +
+ ", lastModified='" + lastModified + '\'' +
+ ", enabled='" + enabled + '\'' +
+ '}';
}
-
}
diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.java
index ba7961d62..04df8f699 100644
--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java
+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java
@@ -24,6 +24,7 @@ import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.util.Date;
+import java.util.Optional;
import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
@@ -33,21 +34,82 @@ import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;
@MappedSuperclass
public abstract class Ruleset {
- public enum DeploymentStatus {
- /**
- * Ruleset compiled successfully but is not running, due to failure of other rulesets in same scope.
- */
- READY,
-
- /**
- * Ruleset has been compiled and is running.
- */
- DEPLOYED,
-
- /**
- * Ruleset did not compile successfully.
- */
- FAILED
+ public enum Lang {
+ JAVASCRIPT(".js",
+ "rules = [ // An array of rules, add more objects to add more rules\n" +
+ " {\n" +
+ " name: \"Set bar to foo on someAttribute\",\n" +
+ " description: \"An example rule that sets 'bar' on someAttribute when it is 'foo'\",\n" +
+ " when: function(facts) {\n" +
+ " return facts.matchAssetState(\n" +
+ " new AssetQuery().type(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
+ " ).map(function(thing) {\n" +
+ " facts.bind(\"assetId\", thing.id);\n" +
+ " return true;\n" +
+ " }).orElse(false);\n" +
+ " },\n" +
+ " then: function(facts) {\n" +
+ " facts.updateAssetState(\n" +
+ " facts.bound(\"assetId\"), \"someAttribute\", \"bar\"\n" +
+ " );\n" +
+ " }\n" +
+ " }\n" +
+ "]"),
+ GROOVY(".groovy",
+ "package demo.rules\n" +
+ "\n" +
+ "import org.openremote.manager.rules.RulesBuilder\n" +
+ "import org.openremote.model.asset.*\n" +
+ "import org.openremote.model.attribute.*\n" +
+ "import org.openremote.model.value.*\n" +
+ "\n" +
+ "Logger LOG = binding.LOG\n" +
+ "RulesBuilder rules = binding.rules\n" +
+ "Assets assets = binding.assets\n" +
+ "\n" +
+ "rules.add()\n" +
+ " .name(\"Set bar to foo on someAttribute\")\n" +
+ " .description(\"An example rule that sets 'bar' on someAttribute when it is 'foo'\")\n" +
+ " .when(\n" +
+ " { facts ->\n" +
+ " facts.matchAssetState(\n" +
+ " new AssetQuery().type(AssetType.THING).attributeValue(\"someAttribute\", \"foo\")\n" +
+ " ).map({ thing ->\n" +
+ " facts.bind(\"assetId\", thing.id)\n" +
+ " true\n" +
+ " }).orElse(false)\n" +
+ " })\n" +
+ " .then(\n" +
+ " { facts ->\n" +
+ " facts.updateAssetState(\n" +
+ " facts.bound(\"assetId\") as String, \"someAttribute\", \"bar\"\n" +
+ " )\n" +
+ " })"
+ );
+
+ final String fileExtension;
+ final String emptyRulesExample;
+
+ Lang(String fileExtension, String emptyRulesExample) {
+ this.fileExtension = fileExtension;
+ this.emptyRulesExample = emptyRulesExample;
+ }
+
+ public String getFileExtension() {
+ return fileExtension;
+ }
+
+ public String getEmptyRulesExample() {
+ return emptyRulesExample;
+ }
+
+ static public Optional<Lang> valueOfFileName(String fileName) {
+ for (Lang lang : values()) {
+ if (fileName.endsWith(lang.getFileExtension()))
+ return Optional.of(lang);
+ }
+ return Optional.empty();
+ }
}
@Id
@@ -82,17 +144,19 @@ public abstract class Ruleset {
@Column(name = "RULES", nullable = false)
protected String rules;
- @Transient
- protected DeploymentStatus deploymentStatus;
+ @NotNull
+ @Enumerated(EnumType.STRING)
+ @Column(name = "RULES_LANG", nullable = false)
+ protected Lang lang = Lang.JAVASCRIPT;
public Ruleset() {
}
public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId) {
- this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null);
+ this(id, version, createdOn, lastModified, name, enabled, templateAssetId, null, Lang.JAVASCRIPT);
}
- public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules) {
+ public Ruleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang) {
this.id = id;
this.version = version;
this.createdOn = createdOn;
@@ -101,16 +165,19 @@ public abstract class Ruleset {
this.enabled = enabled;
this.templateAssetId = templateAssetId;
this.rules = rules;
+ this.lang = lang;
}
- public Ruleset(String name, String rules) {
+ public Ruleset(String name, String rules, Lang lang) {
this.name = name;
this.rules = rules;
+ this.lang = lang;
}
- public Ruleset(String name, String rules, String templateAssetId) {
+ public Ruleset(String name, String rules, Lang lang, String templateAssetId) {
this.name = name;
this.rules = rules;
+ this.lang = lang;
this.templateAssetId = templateAssetId;
}
@@ -172,24 +239,15 @@ public abstract class Ruleset {
this.rules = rules;
}
- public DeploymentStatus getDeploymentStatus() {
- return deploymentStatus;
+ public void setId(Long id) {
+ this.id = id;
}
- public void setDeploymentStatus(DeploymentStatus deploymentStatus) {
- this.deploymentStatus = deploymentStatus;
+ public Lang getLang() {
+ return lang;
}
- @Override
- public String toString() {
- return getClass().getSimpleName() + "{" +
- "id='" + id + '\'' +
- ", version='" + version + '\'' +
- ", name='" + name + '\'' +
- ", createdOn='" + createdOn + '\'' +
- ", lastModified='" + lastModified + '\'' +
- ", enabled='" + enabled + '\'' +
- ", templateAssetId='" + templateAssetId+ '\'' +
- '}';
+ public void setLang(Lang lang) {
+ this.lang = lang;
}
}
diff --git a/model/src/main/java/org/openremote/model/rules/TemporaryFact.java b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java
new file mode 100644
index 000000000..f3348b375
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/rules/TemporaryFact.java
@@ -0,0 +1,42 @@
+/*
+ * 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.model.rules;
+
+/**
+ * A rule fact that has a timestamp, it expires after a certain time.
+ */
+public interface TemporaryFact {
+
+ /**
+ * This value defines the periodic firing of the rules engines when temporary
+ * facts are present, and therefore has an impact on system load. If a temporary
+ * fact has a shorter expiration time, it's not guaranteed to be removed within
+ * that time.
+ */
+ int GUARANTEED_MIN_EXPIRATION_MILLIS = 3000;
+
+ long getTimestamp();
+
+ long getExpirationMilliseconds();
+
+ default boolean isExpired(long currentTimestamp) {
+ return getTimestamp() + getExpirationMilliseconds() < currentTimestamp;
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/rules/TenantRuleset.java b/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
index 2c315a068..8d23e1d69 100644
--- a/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
+++ b/model/src/main/java/org/openremote/model/rules/TenantRuleset.java
@@ -43,23 +43,23 @@ public class TenantRuleset extends Ruleset {
this.realmId = realmId;
}
- public TenantRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, String realmId) {
- super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules);
+ public TenantRuleset(long id, long version, Date createdOn, Date lastModified, String name, boolean enabled, String templateAssetId, String rules, Lang lang, String realmId) {
+ super(id, version, createdOn, lastModified, name, enabled, templateAssetId, rules, lang);
this.realmId = realmId;
}
public TenantRuleset(String realmId) {
- this(null, realmId, null);
+ this(null, realmId, null, Lang.JAVASCRIPT);
}
- public TenantRuleset(String name, String realmId, String rules) {
- super(name, rules);
+ public TenantRuleset(String name, String realmId, String rules, Lang lang) {
+ super(name, rules, lang);
this.realmId = realmId;
}
- public TenantRuleset(String name, String realmId, String rules, String templateAssetId) {
- super(name, rules, templateAssetId);
+ public TenantRuleset(String name, String realmId, String rules, Lang lang, String templateAssetId) {
+ super(name, rules, lang, templateAssetId);
this.realmId = realmId;
}
@@ -77,6 +77,7 @@ public class TenantRuleset extends Ruleset {
"id='" + id + '\'' +
", version='" + version + '\'' +
", name='" + name + '\'' +
+ ", lang='" + lang + '\'' +
", createdOn='" + createdOn + '\'' +
", lastModified='" + lastModified + '\'' +
", enabled='" + enabled + '\'' +
diff --git a/model/src/main/java/org/openremote/model/util/TimeUtil.java b/model/src/main/java/org/openremote/model/util/TimeUtil.java
new file mode 100644
index 000000000..184e5d0c2
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/util/TimeUtil.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2010 Red Hat, Inc. and/or its affiliates.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.openremote.model.util;
+
+import javaemul.internal.annotations.GwtIncompatible;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/**
+ * A helper class with utility methods for
+ * time related operations.
+ */
+@SuppressWarnings("NonJREEmulationClassesInClientCode")
+@GwtIncompatible
+public class TimeUtil {
+
+ // Simple syntax
+ public static final Pattern SIMPLE = Pattern.compile("([+-])?((\\d+)[Dd])?\\s*((\\d+)[Hh])?\\s*((\\d+)[Mm])?\\s*((\\d+)[Ss])?\\s*((\\d+)([Mm][Ss])?)?");
+
+ private static final int SIM_SGN = 1;
+ private static final int SIM_DAY = 3;
+ private static final int SIM_HOU = 5;
+ private static final int SIM_MIN = 7;
+ private static final int SIM_SEC = 9;
+ private static final int SIM_MS = 11;
+
+ private static final long SEC_MS = 1000;
+ private static final long MIN_MS = 60 * SEC_MS;
+ private static final long HOU_MS = 60 * MIN_MS;
+ private static final long DAY_MS = 24 * HOU_MS;
+
+ /**
+ * Parses the given time String and returns the corresponding time in milliseconds
+ *
+ * @throws NullPointerException if time is null
+ */
+ public static long parseTimeString(String time) {
+ time = time.trim();
+ if (time.length() > 0) {
+ String trimmed = time.trim();
+ long result = 0;
+ if (trimmed.length() > 0) {
+ Matcher mat = SIMPLE.matcher(trimmed);
+ if (mat.matches()) {
+ int days = (mat.group(SIM_DAY) != null) ? Integer.parseInt(mat.group(SIM_DAY)) : 0;
+ int hours = (mat.group(SIM_HOU) != null) ? Integer.parseInt(mat.group(SIM_HOU)) : 0;
+ int min = (mat.group(SIM_MIN) != null) ? Integer.parseInt(mat.group(SIM_MIN)) : 0;
+ int sec = (mat.group(SIM_SEC) != null) ? Integer.parseInt(mat.group(SIM_SEC)) : 0;
+ int ms = (mat.group(SIM_MS) != null) ? Integer.parseInt(mat.group(SIM_MS)) : 0;
+ long r = days * DAY_MS + hours * HOU_MS + min * MIN_MS + sec * SEC_MS + ms;
+ if (mat.group(SIM_SGN) != null && mat.group(SIM_SGN).equals("-")) {
+ r = -r;
+ }
+ result = r;
+ } else if ("*".equals(trimmed) || "+*".equals(trimmed)) {
+ // positive infinity
+ result = Long.MAX_VALUE;
+ } else if ("-*".equals(trimmed)) {
+ // negative infinity
+ result = Long.MIN_VALUE;
+ } else {
+ throw new RuntimeException("Error parsing time string: [ " + time + " ]");
+ }
+ }
+ return result;
+ }
+ throw new RuntimeException("Empty parameters not allowed in: [" + time + "]");
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/validation/ConstraintViolation.java b/model/src/main/java/org/openremote/model/validation/ConstraintViolation.java
new file mode 100644
index 000000000..72102ca46
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/ConstraintViolation.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.validation;
+
+import java.io.Serializable;
+
+public class ConstraintViolation implements Serializable {
+
+ public enum Type {CLASS, FIELD, PROPERTY, PARAMETER, RETURN_VALUE}
+
+ protected Type constraintType;
+ protected String path;
+ protected String message;
+ protected String value;
+
+ public ConstraintViolation() {
+ }
+
+ public ConstraintViolation(Type constraintType, String path, String message) {
+ this.constraintType = constraintType;
+ this.path = path;
+ this.message = message;
+ }
+
+ public ConstraintViolation(Type constraintType, String message) {
+ this.constraintType = constraintType;
+ this.message = message;
+ }
+
+ public Type getConstraintType() {
+ return constraintType;
+ }
+
+ public void setConstraintType(Type constraintType) {
+ this.constraintType = constraintType;
+ }
+
+ public String getPath() {
+ return path;
+ }
+
+ public void setPath(String path) {
+ this.path = path;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ public void setValue(String value) {
+ this.value = value;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "constraintType=" + constraintType +
+ ", path='" + path + '\'' +
+ ", message='" + message + '\'' +
+ ", value='" + value + '\'' +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/validation/ConstraintViolationReport.java b/model/src/main/java/org/openremote/model/validation/ConstraintViolationReport.java
new file mode 100644
index 000000000..e1db64c11
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/validation/ConstraintViolationReport.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2016, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+package org.openremote.model.validation;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+public class ConstraintViolationReport implements java.io.Serializable {
+
+ public static final String VIOLATION_EXCEPTION_HEADER = "validation-exception";
+
+ protected String exception;
+ protected ConstraintViolation[] fieldViolations = new ConstraintViolation[0];
+ protected ConstraintViolation[] propertyViolations = new ConstraintViolation[0];
+ protected ConstraintViolation[] classViolations = new ConstraintViolation[0];
+ protected ConstraintViolation[] parameterViolations = new ConstraintViolation[0];
+ protected ConstraintViolation[] returnValueViolations = new ConstraintViolation[0];
+
+ public String getException() {
+ return exception;
+ }
+
+ public void setException(String exception) {
+ this.exception = exception;
+ }
+
+ public ConstraintViolation[] getFieldViolations() {
+ return fieldViolations;
+ }
+
+ public void setFieldViolations(ConstraintViolation[] fieldViolations) {
+ this.fieldViolations = fieldViolations;
+ }
+
+ public ConstraintViolation[] getPropertyViolations() {
+ return propertyViolations;
+ }
+
+ public void setPropertyViolations(ConstraintViolation[] propertyViolations) {
+ this.propertyViolations = propertyViolations;
+ }
+
+ public ConstraintViolation[] getClassViolations() {
+ return classViolations;
+ }
+
+ public void setClassViolations(ConstraintViolation[] classViolations) {
+ this.classViolations = classViolations;
+ }
+
+ public ConstraintViolation[] getParameterViolations() {
+ return parameterViolations;
+ }
+
+ public void setParameterViolations(ConstraintViolation[] parameterViolations) {
+ this.parameterViolations = parameterViolations;
+ }
+
+ public ConstraintViolation[] getReturnValueViolations() {
+ return returnValueViolations;
+ }
+
+ public void setReturnValueViolations(ConstraintViolation[] returnValueViolations) {
+ this.returnValueViolations = returnValueViolations;
+ }
+
+ public boolean hasViolations() {
+ return getFieldViolations().length > 0
+ || getPropertyViolations().length > 0
+ || getClassViolations().length > 0
+ || getParameterViolations().length > 0
+ || getReturnValueViolations().length > 0;
+ }
+
+ public ConstraintViolation[] getAllViolations() {
+ List<ConstraintViolation> violations = new ArrayList<>();
+ violations.addAll(Arrays.asList(getFieldViolations()));
+ violations.addAll(Arrays.asList(getPropertyViolations()));
+ violations.addAll(Arrays.asList(getClassViolations()));
+ violations.addAll(Arrays.asList(getParameterViolations()));
+ violations.addAll(Arrays.asList(getReturnValueViolations()));
+ return violations.toArray(new ConstraintViolation[violations.size()]);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "exception='" + exception + '\'' +
+ ", fieldViolations=" + Arrays.toString(fieldViolations) +
+ ", propertyViolations=" + Arrays.toString(propertyViolations) +
+ ", classViolations=" + Arrays.toString(classViolations) +
+ ", parameterViolations=" + Arrays.toString(parameterViolations) +
+ ", returnValueViolations=" + Arrays.toString(returnValueViolations) +
+ '}';
+ }
+}
\ No newline at end of file
diff --git a/profile/deploy.yml b/profile/deploy.yml
index e2442f131..e1ca69c00 100644
--- a/profile/deploy.yml
+++ b/profile/deploy.yml
@@ -178,18 +178,16 @@ services:
# Override logging.properties with a file of your choice.
# LOGGING_CONFIG_FILE: '/deployment/logging.properties'
- # The number of threads and therefore rules engines that can be instantiated (default unlimited).
- # RULES_THREADS_MAX: 32
-
# The number of threads and therefore background tasks that can be executed at the same
# time. Used by scheduled, usually short-lived and non-blocking tasks, such as protocols
# polling a remote service at regular interval, or the internal checks for expired client
- # subscriptions on the event bus (default depends on detected CPU cores).
+ # subscriptions on the event bus (default depends on detected CPU cores). Also used by
+ # the rules engine.
# SCHEDULED_TASKS_THREADS_MAX: 4
# When asset attributes are enabled for rule events, each value update will be an event fact
- # in a rules knowledge session. You can set the global default expiration time span, after which
- # rule event facts are retracted automatically. Default is 1 hour.
+ # in a rules. You can set the global default expiration time span, after which rule event
+ # facts are retracted automatically. Default is 1 hour.
# RULE_EVENT_EXPIRES: '1h'
# The identity provider implementation to use for managing user identities, roles, and
diff --git a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index 4654c09fd..6171c82f0 100644
--- a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -1,7 +1,6 @@
package org.openremote.test
import com.google.common.collect.Lists
-import org.drools.core.time.impl.PseudoClockScheduler
import org.openremote.agent.protocol.Protocol
import org.openremote.container.Container
import org.openremote.container.ContainerService
@@ -21,7 +20,6 @@ import org.openremote.manager.i18n.I18NService
import org.openremote.manager.map.MapService
import org.openremote.manager.notification.NotificationService
import org.openremote.manager.persistence.ManagerPersistenceService
-import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.security.ManagerIdentityService
@@ -112,17 +110,6 @@ trait ManagerContainerTrait extends ContainerTrait {
&& assetProcessingService.lastProcessedEventTimestamp + milliseconds < System.currentTimeMillis())
}
- /**
- * Execute pseudo clock operations in Rules engine.
- */
- static void withClockOf(RulesEngine engine, Closure<PseudoClockScheduler> clockConsumer) {
- clockConsumer.call(engine.sessionClock as PseudoClockScheduler)
- }
-
- static long getClockTimeOf(RulesEngine engine) {
- (engine.sessionClock as PseudoClockScheduler).currentTime
- }
-
/**
* Execute pseudo clock operations in Container.
*/
@@ -134,33 +121,7 @@ trait ManagerContainerTrait extends ContainerTrait {
container.getService(TimerService.class).getClock().getCurrentTimeMillis()
}
- static void advancePseudoClocks(long amount, TimeUnit unit, Container container, RulesEngine[] engines) {
- if (engines == null) {
- throw new NullPointerException("Engine can't be null")
- }
+ static void advancePseudoClock(long amount, TimeUnit unit, Container container) {
withClockOf(container) { it.advanceTime(amount, unit) }
- engines.each { engine ->
- withClockOf(engine) { clock ->
- if (clock == null) {
- throw new IllegalArgumentException("Knowledge session/clock not available for: " + engine)
- }
- clock.advanceTime(amount, unit)
- }
- }
- }
-
- static void setPseudoClocksToRealTime(Container container, RulesEngine[] engines) {
- withClockOf(container) {
- it.advanceTime(System.currentTimeMillis() - it.currentTimeMillis, TimeUnit.MILLISECONDS)
- }
- engines.each { engine ->
- withClockOf(engine) { clock ->
- if (clock == null) {
- throw new IllegalArgumentException("Knowledge session/clock not available for: " + engine)
- }
- clock.advanceTime(System.currentTimeMillis() - clock.currentTime, TimeUnit.MILLISECONDS)
- }
- }
}
-
}
diff --git a/test/src/main/groovy/org/openremote/test/RulesTestUtil.groovy b/test/src/main/groovy/org/openremote/test/RulesTestUtil.groovy
deleted file mode 100644
index 8c33dc6da..000000000
--- a/test/src/main/groovy/org/openremote/test/RulesTestUtil.groovy
+++ /dev/null
@@ -1,20 +0,0 @@
-package org.openremote.test
-
-import org.kie.api.event.rule.AfterMatchFiredEvent
-import org.kie.api.event.rule.AgendaEventListener
-import org.kie.api.event.rule.DefaultAgendaEventListener
-
-class RulesTestUtil {
-
- static AgendaEventListener createRulesExecutionListener(List<String> executedRules) {
- return new DefaultAgendaEventListener() {
- @Override
- void afterMatchFired(AfterMatchFiredEvent event) {
- def rule = event.getMatch().getRule()
- def ruleName = rule.getName()
- executedRules.add(ruleName)
- }
- }
- }
-
-}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
index 45b7a59ce..b5765fbf4 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy
@@ -36,7 +36,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint1ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3))
then: "the attribute should be updated"
@@ -46,7 +46,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint2ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(14.4))
then: "the attribute should be updated"
@@ -56,7 +56,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint3ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(15.5))
then: "the attribute should be updated"
@@ -115,7 +115,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint1ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1Toggle", Values.create(false))
then: "the attribute should be updated"
@@ -125,7 +125,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint2ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1Toggle", Values.create(true))
then: "the attribute should be updated"
@@ -135,7 +135,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait
}
when: "a simulated sensor receives a new value"
- advancePseudoClocks(10, SECONDS, container)
+ advancePseudoClock(10, SECONDS, container)
def datapoint3ExpectedTimestamp = getClockTimeOf(container)
simulatorProtocol.putValue(managerDemoSetup.thingId, "light1Toggle", Values.create(false))
then: "the attribute should be updated"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 840e0ce46..846fbe948 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -575,7 +575,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
def assets = assetResource.getCurrentUserAssets(null)
then: "result should match"
- assets.length == 4
+ assets.length == 5
Asset apartment1 = assets[0]
apartment1.id == managerDemoSetup.apartment1Id
apartment1.name == "Apartment 1"
@@ -596,7 +596,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
apartment1Kitchen.id == managerDemoSetup.apartment1KitchenId
apartment1Kitchen.name == "Kitchen"
- Asset apartment2 = assets[3]
+ Asset apartment1Hallway = assets[3]
+ apartment1Hallway.id == managerDemoSetup.apartment1HallwayId
+ apartment1Hallway.name == "Hallway"
+
+ Asset apartment2 = assets[4]
apartment2.id == managerDemoSetup.apartment2Id
apartment2.name == "Apartment 2"
@@ -636,7 +640,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
)
then: "result should match"
- assets.length == 2
+ assets.length == 3
when: "the child assets of an asset in the authenticated realm are retrieved"
assets = assetResource.queryAssets(null,
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
index 64721e464..66ba9b5f0 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy
@@ -22,6 +22,7 @@ import java.util.function.Consumer
import java.util.logging.Logger
class AssetProcessingTest extends Specification implements ManagerContainerTrait {
+
Logger LOG = Logger.getLogger(AssetProcessingTest.class.getName())
def "Check processing of asset updates through the processing chain"() {
@@ -195,7 +196,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
assert updatesPassedDatapointService.size() == 0
assert updatesPassedStartOfProcessingChain[0].attribute.getAssetId().orElse("") == mockThing.getId()
assert updatesPassedStartOfProcessingChain[0].attribute.getName().orElse("") == "light1Toggle"
- assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean()
+ assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean().get()
assert updatesPassedStartOfProcessingChain[0].error == null
assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED
assert sendToActuatorEvents.size() == 1
@@ -219,7 +220,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
assert updatesPassedStartOfProcessingChain[0].attribute.getAssetId().orElse("") == mockThing.getId()
assert updatesPassedStartOfProcessingChain[0].attribute.getName().orElse("") == "light1Toggle"
assert !Values.getBoolean(updatesPassedStartOfProcessingChain[0].getOldValue()).orElse(true)
- assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean()
+ assert !updatesPassedStartOfProcessingChain[0].getValueAsBoolean().get()
assert updatesPassedStartOfProcessingChain[0].error == null
assert updatesPassedStartOfProcessingChain[0].processingStatus == AssetState.ProcessingStatus.COMPLETED
}
@@ -274,7 +275,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait
assert updatesPassedDatapointService[0].name == "Mock Thing Asset"
assert updatesPassedDatapointService[0].attributeName == "plainAttribute"
assert Values.getString(updatesPassedDatapointService[0].oldValue).orElse(null) == "demo"
- assert Values.getString(updatesPassedDatapointService[0].value).orElse(null) == "test"
+ assert updatesPassedDatapointService[0].valueAsString.orElse(null) == "test"
assert updatesPassedDatapointService[0].error == null
assert updatesPassedDatapointService[0].processingStatus == AssetState.ProcessingStatus.COMPLETED
}
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index 1c5a2125d..8c25e88e9 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -84,7 +84,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "only the users assets should be retrieved"
- assets.size() == 4
+ assets.size() == 5
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(1).getAttributesList().size() == 8
@@ -94,7 +94,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
!assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("targetTemperature").get().meta.size() == 1
assets.get(2).id == managerDemoSetup.apartment1KitchenId
- assets.get(3).id == managerDemoSetup.apartment2Id
+ assets.get(3).id == managerDemoSetup.apartment1HallwayId
+ assets.get(4).id == managerDemoSetup.apartment2Id
when: "a user filtering query is executed that returns only IDs, names and attribute names and limits to protected attributes and meta"
assets = assetStorageService.findAll(
@@ -104,7 +105,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "only the users assets should be retrieved"
- assets.size() == 4
+ assets.size() == 5
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(1).getAttributesList().size() == 7
@@ -114,7 +115,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
!assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("targetTemperature").get().meta.size() == 1
assets.get(2).id == managerDemoSetup.apartment1KitchenId
- assets.get(3).id == managerDemoSetup.apartment2Id
+ assets.get(3).id == managerDemoSetup.apartment1HallwayId
+ assets.get(4).id == managerDemoSetup.apartment2Id
when: "a query is executed that returns a protected attribute without any other meta items"
assets = assetStorageService.findAll(
@@ -140,7 +142,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "result should contain only ids, names and attribute names and label meta"
- assets.size() == 10
+ assets.size() == 11
assets[0].id == managerDemoSetup.smartHomeId
assets[0].name == "Smart Home"
assets[1].id == managerDemoSetup.apartment1Id
@@ -170,11 +172,12 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets[2].id == managerDemoSetup.apartment1ServiceAgentId
assets[3].id == managerDemoSetup.apartment1LivingroomId
assets[4].id == managerDemoSetup.apartment1KitchenId
- assets[5].id == managerDemoSetup.apartment2Id
- assets[6].id == managerDemoSetup.apartment2LivingroomId
- assets[7].id == managerDemoSetup.apartment2BathroomId
- assets[8].id == managerDemoSetup.apartment3Id
- assets[9].id == managerDemoSetup.apartment3LivingroomId
+ assets[5].id == managerDemoSetup.apartment1HallwayId
+ assets[6].id == managerDemoSetup.apartment2Id
+ assets[7].id == managerDemoSetup.apartment2LivingroomId
+ assets[8].id == managerDemoSetup.apartment2BathroomId
+ assets[9].id == managerDemoSetup.apartment3Id
+ assets[10].id == managerDemoSetup.apartment3LivingroomId
when: "an asset is loaded by identifier through JPA"
def asset = persistenceService.doReturningTransaction(new Function<EntityManager, ServerAsset>() {
@@ -367,11 +370,12 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "result should match"
- assets.size() == 4
+ assets.size() == 5
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1ServiceAgentId
assets.get(2).id == managerDemoSetup.apartment1LivingroomId
assets.get(3).id == managerDemoSetup.apartment1KitchenId
+ assets.get(4).id == managerDemoSetup.apartment1HallwayId
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -381,9 +385,10 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "result should match"
- assets.size() == 2
+ assets.size() == 3
assets.get(0).id == managerDemoSetup.apartment1LivingroomId
assets.get(1).id == managerDemoSetup.apartment1KitchenId
+ assets.get(2).id == managerDemoSetup.apartment1HallwayId
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -391,7 +396,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
)
then: "result should match"
- assets.size() == 4
+ assets.size() == 5
assets.get(0).id == managerDemoSetup.apartment1Id
assets.get(1).id == managerDemoSetup.apartment1LivingroomId
assets.get(1).getAttributesList().size() == 7
@@ -400,7 +405,8 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
!assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()
assets.get(1).getAttribute("targetTemperature").get().meta.size() == 4
assets.get(2).id == managerDemoSetup.apartment1KitchenId
- assets.get(3).id == managerDemoSetup.apartment2Id
+ assets.get(3).id == managerDemoSetup.apartment1HallwayId
+ assets.get(4).id == managerDemoSetup.apartment2Id
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -588,7 +594,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.getAttribute("lastPresenceDetected").isPresent()
asset.getAttribute("lastPresenceDetected").get().meta.size() == 3
asset.getAttribute("motionSensor").isPresent()
- asset.getAttribute("motionSensor").get().meta.size() == 8
+ asset.getAttribute("motionSensor").get().meta.size() == 7
when: "a query is executed to select a subset of protected attributes"
asset = assetStorageService.find(
@@ -625,7 +631,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
new StringPredicate("windowOpen"), new BooleanPredicate(false)
),
new AttributePredicate(
- new StringPredicate("co2Level"), new NumberPredicate(340, OperatorMatch.GREATER_THEN, NumberType.INTEGER)
+ new StringPredicate("co2Level"), new NumberPredicate(340, Operator.GREATER_THAN, NumberType.INTEGER)
)
)
)
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
index 3d987d74d..f7b6c34cb 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy
@@ -51,7 +51,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
def userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, null, null)
then: "result should match"
- userAssets.length == 4
+ userAssets.length == 5
userAssets.any {
it.id.realmId == keycloakDemoSetup.customerATenant.id &&
it.id.userId == keycloakDemoSetup.testuser3Id &&
@@ -76,6 +76,14 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
it.parentAssetName == "Apartment 1" &&
it.userFullName == "testuser3 (Testuserfirst Testuserlast)"
}
+ userAssets.any {
+ it.id.realmId == keycloakDemoSetup.customerATenant.id &&
+ it.id.userId == keycloakDemoSetup.testuser3Id &&
+ it.id.assetId == managerDemoSetup.apartment1HallwayId &&
+ it.assetName == "Hallway" &&
+ it.parentAssetName == "Apartment 1" &&
+ it.userFullName == "testuser3 (Testuserfirst Testuserlast)"
+ }
userAssets.any {
it.id.realmId == keycloakDemoSetup.customerATenant.id &&
it.id.userId == keycloakDemoSetup.testuser3Id &&
@@ -89,7 +97,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTrai
userAssets = assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerATenant.id, keycloakDemoSetup.testuser3Id, null)
then: "result should match"
- userAssets.length == 4
+ userAssets.length == 5
when: "the realm and user don't match"
assetResource.getUserAssetLinks(null, keycloakDemoSetup.customerBTenant.id, keycloakDemoSetup.testuser3Id, null)
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
index 8e142f41c..115f89cbe 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy
@@ -9,16 +9,17 @@ 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.GlobalRuleset
-import org.openremote.model.rules.Ruleset.DeploymentStatus
import org.openremote.model.rules.TenantRuleset
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import static org.openremote.container.util.MapAccess.getString
+import static org.openremote.manager.rules.RulesetDeployment.Status.*
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
+import static org.openremote.model.rules.Ruleset.Lang.GROOVY
class BasicRulesDeploymentTest extends Specification implements ManagerContainerTrait {
@@ -56,7 +57,8 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
when: "a new global rule definition is added"
def ruleset = new GlobalRuleset(
"Some more global rules",
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy").text,
+ GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -64,20 +66,17 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
conditions.eventually {
assert rulesService.globalEngine != null
assert rulesService.globalEngine.isRunning()
- assert rulesService.globalEngine.allRulesets.length == 2
- assert rulesService.globalEngine.allRulesets[0].enabled
- assert rulesService.globalEngine.allRulesets[0].name == "Some global demo rules"
- assert rulesService.globalEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
- assert rulesService.globalEngine.allRulesets[1].enabled
- assert rulesService.globalEngine.allRulesets[1].name == "Some more global rules"
- assert rulesService.globalEngine.allRulesets[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert rulesService.globalEngine.deployments.size() == 2
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED})
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED})
}
when: "a new tenant rule definition is added to customer A"
ruleset = new TenantRuleset(
"Some more customerA tenant rules",
keycloakDemoSetup.customerATenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy").text,
+ GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -86,20 +85,17 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
def customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.allRulesets.length == 2
- assert customerAEngine.allRulesets[0].enabled
- assert customerAEngine.allRulesets[0].name == "Some customerA tenant demo rules"
- assert customerAEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
- assert customerAEngine.allRulesets[1].enabled
- assert customerAEngine.allRulesets[1].name == "Some more customerA tenant rules"
- assert customerAEngine.allRulesets[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerAEngine.deployments.size() == 2
+ assert customerAEngine.deployments.values().any({ it.name == "Some customerA tenant demo rules" && it.status == DEPLOYED})
+ assert customerAEngine.deployments.values().any({ it.name == "Some more customerA tenant rules" && it.status == DEPLOYED})
}
when: "a new tenant rule definition is added to customer B"
ruleset = new TenantRuleset(
"Some more customerB tenant rules",
keycloakDemoSetup.customerBTenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy").text,
+ GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -109,10 +105,8 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
assert rulesService.tenantEngines.size() == 3
assert customerBEngine != null
assert customerBEngine.isRunning()
- assert customerBEngine.allRulesets.length == 1
- assert customerBEngine.allRulesets[0].enabled
- assert customerBEngine.allRulesets[0].name == "Some more customerB tenant rules"
- assert customerBEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerBEngine.deployments.size() == 1
+ assert customerBEngine.deployments.values().any({ it.name == "Some more customerB tenant rules" && it.status == DEPLOYED})
}
when: "the disabled rule definition for customer B is enabled"
@@ -126,13 +120,9 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
assert rulesService.tenantEngines.size() == 3
assert customerBEngine != null
assert customerBEngine.isRunning()
- assert customerBEngine.allRulesets.length == 2
- assert customerBEngine.allRulesets[0].enabled
- assert customerBEngine.allRulesets[0].name == "Some more customerB tenant rules"
- assert customerBEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
- assert customerBEngine.allRulesets[1].enabled
- assert customerBEngine.allRulesets[1].name == "Some customerB tenant demo rules"
- assert customerBEngine.allRulesets[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerBEngine.deployments.size() == 2
+ assert customerBEngine.deployments.values().any({ it.name == "Some more customerB tenant rules" && it.status == DEPLOYED})
+ assert customerBEngine.deployments.values().any({ it.name == "Some customerB tenant demo rules" && it.status == DEPLOYED})
}
when: "the enabled rule definition for customer B is disabled"
@@ -146,10 +136,8 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
def customerBEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerBTenant.id)
assert customerBEngine != null
assert customerBEngine.isRunning()
- assert customerBEngine.allRulesets.length == 1
- assert customerBEngine.allRulesets[0].enabled
- assert customerBEngine.allRulesets[0].name == "Some more customerB tenant rules"
- assert customerBEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerBEngine.deployments.size() == 1
+ assert customerBEngine.deployments.values().any({ it.name == "Some more customerB tenant rules" && it.status == DEPLOYED})
}
when: "the asset rule definition for apartment 2 is deleted"
@@ -168,25 +156,20 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
when: "a broken rule definition is added to the global rules engine"
ruleset = new GlobalRuleset(
"Some broken global rules",
- getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.groovy").text,
+ GROOVY
)
ruleset = rulesetStorageService.merge(ruleset)
then: "the global rules engine should not run and the rule engine status should indicate the issue"
conditions.eventually {
- assert rulesService.globalEngine.allRulesets.length == 3
+ assert rulesService.globalEngine.deployments.size() == 3
assert rulesService.globalEngine.running == false
assert rulesService.globalEngine.isError()
assert rulesService.globalEngine.error instanceof RuntimeException
- assert rulesService.globalEngine.allRulesets[0].enabled
- assert rulesService.globalEngine.allRulesets[0].name == "Some global demo rules"
- assert rulesService.globalEngine.allRulesets[0].deploymentStatus == DeploymentStatus.READY
- assert rulesService.globalEngine.allRulesets[1].enabled
- assert rulesService.globalEngine.allRulesets[1].name == "Some more global rules"
- assert rulesService.globalEngine.allRulesets[1].deploymentStatus == DeploymentStatus.READY
- assert rulesService.globalEngine.allRulesets[2].enabled
- assert rulesService.globalEngine.allRulesets[2].name == "Some broken global rules"
- assert rulesService.globalEngine.allRulesets[2].deploymentStatus == DeploymentStatus.FAILED
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == READY})
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == READY})
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some broken global rules" && it.status == COMPILATION_ERROR})
}
when: "the broken rule definition is removed from the global engine"
@@ -194,15 +177,11 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
then: "the global rules engine should restart"
conditions.eventually {
- assert rulesService.globalEngine.allRulesets.length == 2
+ assert rulesService.globalEngine.deployments.size() == 2
assert rulesService.globalEngine.running == true
assert rulesService.globalEngine.isError() == false
- assert rulesService.globalEngine.allRulesets[0].enabled
- assert rulesService.globalEngine.allRulesets[0].name == "Some global demo rules"
- assert rulesService.globalEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
- assert rulesService.globalEngine.allRulesets[1].enabled
- assert rulesService.globalEngine.allRulesets[1].name == "Some more global rules"
- assert rulesService.globalEngine.allRulesets[1].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some global demo rules" && it.status == DEPLOYED })
+ assert rulesService.globalEngine.deployments.values().any({ it.name == "Some more global rules" && it.status == DEPLOYED })
}
when: "a tenant is disabled"
@@ -215,10 +194,10 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
then: "the tenants rule engine should stop and all asset rule engines in this realm should also stop"
conditions.eventually {
assert customerAEngine.isRunning() == false
- assert customerAEngine.allRulesets.length == 0
+ assert customerAEngine.deployments.size() == 2
assert rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id) == null
assert apartment3Engine.isRunning() == false
- assert apartment3Engine.allRulesets.length == 0
+ assert apartment3Engine.deployments.size() == 1
assert rulesService.assetEngines.get(managerDemoSetup.apartment3Id) == null
}
@@ -246,17 +225,11 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer
assert rulesService.assetEngines.size() == 1
assert customerAEngine != null
assert customerAEngine.isRunning()
- assert customerAEngine.allRulesets.length == 2
- assert customerAEngine.allRulesets[0].enabled
- assert customerAEngine.allRulesets[0].name == "Some customerA tenant demo rules"
- assert customerAEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
- assert customerAEngine.allRulesets[1].enabled
- assert customerAEngine.allRulesets[1].name == "Some more customerA tenant rules"
- assert customerAEngine.allRulesets[1].deploymentStatus == DeploymentStatus.DEPLOYED
- assert apartment3Engine.allRulesets.length == 1
- assert apartment3Engine.allRulesets[0].enabled
- assert apartment3Engine.allRulesets[0].name == "Some apartment 3 demo rules"
- assert apartment3Engine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerAEngine.deployments.size() == 2
+ assert customerAEngine.deployments.values().any({ it.name == "Some customerA tenant demo rules" && it.status == DEPLOYED})
+ assert customerAEngine.deployments.values().any({ it.name == "Some more customerA tenant rules" && it.status == DEPLOYED})
+ assert apartment3Engine.deployments.size() == 1
+ assert apartment3Engine.deployments.values().any({ it.name == "Some apartment 3 demo rules" && it.status == DEPLOYED})
}
//TODO: Reinstate the tenant delete test once tenant delete mechanism is finalised
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
new file mode 100644
index 000000000..43424415a
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesFactsTest.groovy
@@ -0,0 +1,265 @@
+package org.openremote.test.rules
+
+import org.openremote.container.Container
+import org.openremote.manager.rules.RulesClock
+import org.openremote.manager.rules.RulesFacts
+import org.openremote.model.rules.Assets
+import spock.lang.Specification
+
+import java.util.logging.Logger
+import java.util.stream.Collectors
+
+class BasicRulesFactsTest extends Specification {
+
+ private static final Logger LOG = Logger.getLogger(BasicRulesFactsTest.class.getName())
+
+ class AnonFact {
+ String foo
+ double bar
+ boolean baz
+
+ AnonFact(String foo, double bar, boolean baz) {
+ this.foo = foo
+ this.bar = bar
+ this.baz = baz
+ }
+
+
+ @Override
+ String toString() {
+ return getClass().getSimpleName() + "{" +
+ "foo='" + foo + '\'' +
+ ", bar=" + bar +
+ ", baz=" + baz +
+ '}'
+ }
+ }
+
+ def assetsFacade
+ RulesFacts rulesFacts
+
+ def setupSpec() {
+ // Init logging config
+ Container.LOG.info("Running test...")
+ }
+
+ def setup() {
+ given: "some rule facts"
+ assetsFacade = Mock(Assets)
+ rulesFacts = new RulesFacts(assetsFacade, this, LOG)
+
+ and: "a rules clock"
+ def rulesClock = new RulesClock(0)
+ rulesFacts.setClock(rulesClock)
+ }
+
+ def "Handle named facts"() {
+
+ when: "a fact is added with reserved name"
+ rulesFacts.put(RulesFacts.ASSET_STATES, "FOO")
+
+ then: "it should not be allowed"
+ IllegalArgumentException ex = thrown()
+ assert ex
+
+ when: "some named facts are added"
+ rulesFacts.put("foo", "FOO")
+ rulesFacts.put("bar", "BAR")
+ rulesFacts.put("baz", ["BAZ111", "BAZ111", "BAZ222"])
+
+ then: "facts should be present"
+ assert rulesFacts.allFacts.count() == 3
+ assert rulesFacts.assetStates.size() == 0
+ assert rulesFacts.assetEvents.size() == 0
+ assert rulesFacts.namedFacts.size() == 3
+ assert rulesFacts.anonymousFacts.size() == 0
+ assert rulesFacts.vars.size() == 0
+ assert !rulesFacts.hasTemporaryFacts()
+
+ and: "first matching should succeed"
+ assert rulesFacts.matchFirst("foo", { fact -> fact == "FOO" }).isPresent()
+ assert !rulesFacts.matchFirst("foo", { fact -> fact == "FOO123" }).isPresent()
+ assert rulesFacts.matchFirst("bar").isPresent()
+ assert !rulesFacts.matchFirst("bar", { fact -> fact == "BAR123" }).isPresent()
+
+ and: "stream matching should succeed "
+ assert rulesFacts.match(String.class).count() == 2
+ assert rulesFacts.match(String.class, { fact -> fact == "FOO" }).count() == 1
+ assert rulesFacts.match(String.class, { fact -> fact == "FOO123" }).count() == 0
+ assert rulesFacts.match(Integer.class).count() == 0
+ assert rulesFacts.match(Collection.class, { fact -> fact.size() == 3 }).count() == 1
+ assert rulesFacts.match(Collection.class, { fact -> fact.size() == 2 }).count() == 0
+
+ when: "a named fact is updated"
+ rulesFacts.put("foo", "NEWFOO")
+
+ then: "the update should be present"
+ assert !rulesFacts.matchFirst("foo", { fact -> fact == "FOO" }).isPresent()
+ assert rulesFacts.matchFirst("foo", { fact -> fact == "NEWFOO" }).isPresent()
+ assert rulesFacts.namedFacts.size() == 3
+
+ when: "a named fact is removed"
+ rulesFacts.remove("foo")
+
+ then: "the fact should be removed"
+ assert !rulesFacts.matchFirst("foo", { fact -> fact == "NEWFOO" }).isPresent()
+ assert rulesFacts.namedFacts.size() == 2
+ }
+
+ def "Handle anonymous facts"() {
+
+ when: "some anonymous facts are added"
+ def anonFact1 = new AnonFact("FOO1", 123, true)
+ rulesFacts.put(anonFact1)
+ rulesFacts.put(new AnonFact("FOO2", 456, false))
+ rulesFacts.put(new AnonFact("FOO3", 789, true))
+
+ then: "facts should be present"
+ assert rulesFacts.allFacts.count() == 3
+ assert rulesFacts.assetStates.size() == 0
+ assert rulesFacts.assetEvents.size() == 0
+ assert rulesFacts.namedFacts.size() == 0
+ assert rulesFacts.anonymousFacts.size() == 3
+ assert rulesFacts.vars.size() == 0
+ assert !rulesFacts.hasTemporaryFacts()
+
+ and: "first matching should succeed"
+ assert rulesFacts.matchFirst(AnonFact, { fact -> fact.foo == "FOO1" }).isPresent()
+ assert rulesFacts.matchFirst({ fact -> fact.foo == "FOO1" }).isPresent()
+ assert rulesFacts.matchFirst({ fact -> fact.bar == 456 }).isPresent()
+ assert rulesFacts.matchFirst({ fact -> fact.baz == true }).isPresent()
+ assert !rulesFacts.matchFirst({ fact -> fact.foo == "FOO1123" }).isPresent()
+ assert !rulesFacts.matchFirst({ fact -> fact.bar == 111 }).isPresent()
+
+ and: "stream matching should succeed "
+ assert rulesFacts.match({ fact -> fact.foo == "FOO1" }).count() == 1
+ assert rulesFacts.match({ fact -> fact.bar == 456 }).count() == 1
+ assert rulesFacts.match({ fact -> fact.baz == true }).count() == 2
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 1
+ assert rulesFacts.match(AnonFact, { fact -> fact.bar == 456 }).count() == 1
+ assert rulesFacts.match(AnonFact, { fact -> fact.baz }).count() == 2
+ assert rulesFacts.match(String, { fact -> true }).count() == 0
+
+ when: "an anonymous fact is updated"
+ anonFact1.foo = "NEWFOO1"
+ rulesFacts.put(anonFact1)
+
+ then: "the update should be present"
+ assert !rulesFacts.matchFirst({ fact -> fact.foo == "FOO" }).isPresent()
+ assert rulesFacts.matchFirst({ fact -> fact.foo == "NEWFOO1" }).isPresent()
+ assert rulesFacts.anonymousFacts.size() == 3
+
+ when: "an anonymous fact is removed"
+ rulesFacts.remove(anonFact1)
+
+ then: "the fact should be removed"
+ assert !rulesFacts.matchFirst({ fact -> fact.foo == "NEWFOO1" }).isPresent()
+ assert rulesFacts.anonymousFacts.size() == 2
+ }
+
+ def "Handle temporary named facts"() {
+
+ when: "some temporary facts are added"
+ rulesFacts.putTemporary("foo", "5s", "FOO")
+ rulesFacts.putTemporary("bar", "10s", "BAR")
+ rulesFacts.putTemporary("baz", "15s", "BAZ")
+
+ and: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(3000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "all temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.getAllFacts().count() == 3
+ assert rulesFacts.matchFirst("foo").isPresent()
+ assert rulesFacts.matchFirst("bar").isPresent()
+ assert rulesFacts.matchFirst("baz").isPresent()
+
+ when: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(6000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "some temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.getAllFacts().count() == 2
+ assert !rulesFacts.matchFirst("foo").isPresent()
+ assert rulesFacts.matchFirst("bar").isPresent()
+ assert rulesFacts.matchFirst("baz").isPresent()
+
+ when: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(12000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "some temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.getAllFacts().count() == 1
+ assert !rulesFacts.matchFirst("foo").isPresent()
+ assert !rulesFacts.matchFirst("bar").isPresent()
+ assert rulesFacts.matchFirst("baz").isPresent()
+
+ when: "a temporary fact is removed manually"
+ rulesFacts.remove("baz")
+
+ then: "all temporary facts should be gone"
+ assert !rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.getAllFacts().count() == 0
+ assert !rulesFacts.matchFirst("foo").isPresent()
+ assert !rulesFacts.matchFirst("bar").isPresent()
+ assert !rulesFacts.matchFirst("baz").isPresent()
+ }
+
+ def "Handle temporary anonymous facts"() {
+
+ when: "some temporary facts are added"
+ def anonFact1 = new AnonFact("FOO1", 123, true)
+ rulesFacts.putTemporary("5s", anonFact1)
+ def anonFact2 = new AnonFact("FOO2", 456, false)
+ rulesFacts.putTemporary("10s", anonFact2)
+ def anonFact3 = new AnonFact("FOO3", 789, true)
+ rulesFacts.putTemporary("15s", anonFact3)
+
+ and: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(3000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "all temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.match(AnonFact).count() == 3
+ assert rulesFacts.match(String).count() == 0
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 1
+ assert rulesFacts.matchFirst(AnonFact, { fact -> fact.foo == "FOO1" }).get() == anonFact1
+ assert rulesFacts.match(AnonFact, { fact -> fact.baz }).count() == 2
+ assert rulesFacts.match(AnonFact).collect(Collectors.toList()).contains(anonFact1)
+ assert rulesFacts.match(AnonFact).collect(Collectors.toList()).contains(anonFact2)
+ assert rulesFacts.match(AnonFact).collect(Collectors.toList()).contains(anonFact3)
+
+ when: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(6000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "some temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.match(AnonFact).count() == 2
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 0
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo.startsWith("FOO") }).count() == 2
+ assert rulesFacts.match(AnonFact, { fact -> fact.baz }).count() == 1
+
+ when: "the clock is advanced and temporary facts are expired"
+ rulesFacts.setClock(new RulesClock(12000))
+ rulesFacts.removeExpiredTemporaryFacts()
+
+ then: "some temporary facts should still be present"
+ assert rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.match(AnonFact).count() == 1
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo == "FOO1" }).count() == 0
+ assert rulesFacts.match(AnonFact, { fact -> fact.foo.startsWith("FOO") }).count() == 1
+ assert rulesFacts.match(AnonFact, { fact -> fact.baz }).count() == 1
+
+ when: "a temporary fact is removed manually"
+ rulesFacts.remove(anonFact3)
+
+ then: "all temporary facts should be gone"
+ assert !rulesFacts.hasTemporaryFacts()
+ assert rulesFacts.match(AnonFact).count() == 0
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy
index ab8b6a855..6b3122417 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy
@@ -8,9 +8,11 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.GlobalRuleset
import org.openremote.model.rules.Ruleset
-import org.openremote.model.rules.Ruleset.DeploymentStatus
import org.openremote.model.rules.TenantRuleset
+import static org.openremote.manager.rules.RulesetDeployment.Status.DEPLOYED
+import static org.openremote.model.rules.Ruleset.Lang.GROOVY
+
class BasicRulesImport {
final Long globalRulesetId
@@ -35,13 +37,15 @@ class BasicRulesImport {
Ruleset ruleset = new GlobalRuleset(
"Some global demo rules",
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
globalRulesetId = rulesetStorageService.merge(ruleset).id
ruleset = new GlobalRuleset(
"Other global demo rules with a long name that should fill up space in UI",
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
ruleset.setEnabled(false)
globalRuleset2Id = rulesetStorageService.merge(ruleset).id
@@ -49,21 +53,24 @@ class BasicRulesImport {
ruleset = new TenantRuleset(
"Some master tenant demo rules",
keycloakDemoSetup.masterTenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
masterRulesetId = rulesetStorageService.merge(ruleset).id
ruleset = new TenantRuleset(
"Some customerA tenant demo rules",
keycloakDemoSetup.customerATenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
customerARulesetId = rulesetStorageService.merge(ruleset).id
ruleset = new TenantRuleset(
"Some customerB tenant demo rules",
keycloakDemoSetup.customerBTenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
ruleset.setEnabled(false)
customerBRulesetId = rulesetStorageService.merge(ruleset).id
@@ -71,7 +78,8 @@ class BasicRulesImport {
ruleset = new AssetRuleset(
"Some apartment 1 demo rules",
managerDemoSetup.apartment1Id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
ruleset.setEnabled(false)
apartment1RulesetId = rulesetStorageService.merge(ruleset).id
@@ -79,14 +87,16 @@ class BasicRulesImport {
ruleset = new AssetRuleset(
"Some apartment 2 demo rules",
managerDemoSetup.apartment2Id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
apartment2RulesetId = rulesetStorageService.merge(ruleset).id
ruleset = new AssetRuleset(
"Some apartment 3 demo rules",
managerDemoSetup.apartment3Id,
- getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicMatchAllAssetStates.groovy").text,
+ GROOVY
)
apartment3RulesetId = rulesetStorageService.merge(ruleset).id
}
@@ -96,29 +106,29 @@ class BasicRulesImport {
ManagerDemoSetup managerDemoSetup) {
globalEngine = rulesService.globalEngine
+ globalEngine.disableTemporaryFactExpiration = true
assert globalEngine != null
assert globalEngine.isRunning()
assert globalEngine != null
assert globalEngine.isRunning()
- assert globalEngine.allRulesets.length == 1
- assert globalEngine.allRulesets[0].name == "Some global demo rules"
- assert globalEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert globalEngine.deployments.size() == 1
+ assert globalEngine.deployments.values().any { it -> it.name == "Some global demo rules" && it.status == DEPLOYED }
assert rulesService.tenantEngines.size() == 2
masterEngine = rulesService.tenantEngines.get(keycloakDemoSetup.masterTenant.id)
+ masterEngine.disableTemporaryFactExpiration = true
assert masterEngine != null
assert masterEngine.isRunning()
- assert masterEngine.allRulesets.length == 1
- assert masterEngine.allRulesets[0].enabled
- assert masterEngine.allRulesets[0].name == "Some master tenant demo rules"
- assert masterEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert masterEngine.deployments.size() == 1
+ assert masterEngine.deployments.values().iterator().next().name == "Some master tenant demo rules"
+ assert masterEngine.deployments.values().iterator().next().status == DEPLOYED
customerAEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerATenant.id)
assert customerAEngine != null
+ customerAEngine.disableTemporaryFactExpiration = true
assert customerAEngine.isRunning()
- assert customerAEngine.allRulesets.length == 1
- assert customerAEngine.allRulesets[0].enabled
- assert customerAEngine.allRulesets[0].name == "Some customerA tenant demo rules"
- assert customerAEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert customerAEngine.deployments.size() == 1
+ assert customerAEngine.deployments.values().iterator().next().name == "Some customerA tenant demo rules"
+ assert customerAEngine.deployments.values().iterator().next().status == DEPLOYED
def customerBEngine = rulesService.tenantEngines.get(keycloakDemoSetup.customerBTenant.id)
assert customerBEngine == null
@@ -127,19 +137,47 @@ class BasicRulesImport {
assert apartment1Engine == null
apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)
assert apartment2Engine != null
+ apartment2Engine.disableTemporaryFactExpiration = true
assert apartment2Engine.isRunning()
- assert apartment2Engine.allRulesets.length == 1
- assert apartment2Engine.allRulesets[0].enabled
- assert apartment2Engine.allRulesets[0].name == "Some apartment 2 demo rules"
- assert apartment2Engine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert apartment2Engine.deployments.size() == 1
+ assert apartment2Engine.deployments.values().iterator().next().name == "Some apartment 2 demo rules"
+ assert apartment2Engine.deployments.values().iterator().next().status == DEPLOYED
apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)
assert apartment3Engine != null
+ apartment3Engine.disableTemporaryFactExpiration = true
assert apartment3Engine.isRunning()
- assert apartment3Engine.allRulesets.length == 1
- assert apartment3Engine.allRulesets[0].enabled
- assert apartment3Engine.allRulesets[0].name == "Some apartment 3 demo rules"
- assert apartment3Engine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert apartment3Engine.deployments.size() == 1
+ assert apartment3Engine.deployments.values().iterator().next().name == "Some apartment 3 demo rules"
+ assert apartment3Engine.deployments.values().iterator().next().status == DEPLOYED
return true
}
+
+ void resetRulesFired(RulesEngine... engine) {
+ // Remove all named facts (those are the only ones inserted by basic test rules)
+ Collection<RulesEngine> engines = [globalEngine, masterEngine, customerAEngine, apartment2Engine, apartment3Engine]
+ engines.addAll(engine)
+ engines.forEach({ e ->
+ e.facts.namedFacts.keySet().forEach({ factName ->
+ e.facts.remove(factName)
+ })
+ })
+ }
+
+ void assertNoRulesFired(RulesEngine... engine) {
+ Collection<RulesEngine> engines = [globalEngine, masterEngine, customerAEngine, apartment2Engine, apartment3Engine]
+ engines.addAll(engine)
+ engines.forEach({ e ->
+ assert e.facts.namedFacts.size() == 0
+ })
+ }
+
+ static void assertRulesFired(RulesEngine engine, int fired) {
+ assert engine.facts.namedFacts.keySet().size() == fired
+ }
+
+ static void assertRulesFired(RulesEngine engine, Collection<String> facts) {
+ engine.facts.namedFacts.keySet().containsAll(facts)
+ }
+
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
index 16254ceaf..b1b716d55 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy
@@ -9,9 +9,6 @@ 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.DeploymentStatus
-import org.openremote.model.rules.TenantRuleset
import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetMeta
import org.openremote.model.asset.AssetType
@@ -19,60 +16,20 @@ import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.attribute.AttributeType
import org.openremote.model.attribute.Meta
import org.openremote.model.attribute.MetaItem
+import org.openremote.model.rules.AssetRuleset
+import org.openremote.model.rules.Ruleset
+import org.openremote.model.rules.TenantRuleset
import org.openremote.model.value.Values
import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
+import static org.openremote.manager.rules.RulesetDeployment.Status.*
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.*
-import static org.openremote.test.RulesTestUtil.createRulesExecutionListener
+import static org.openremote.test.rules.BasicRulesImport.assertRulesFired
class BasicRulesProcessingTest extends Specification implements ManagerContainerTrait {
- List<String> globalEngineFiredRules = []
- List<String> masterEngineFiredRules = []
- List<String> customerAEngineFiredRules = []
- List<String> smartHomeEngineFiredRules = []
- List<String> apartment2EngineFiredRules = []
- List<String> apartment3EngineFiredRules = []
-
- def createRulesExecutionListener(KeycloakDemoSetup keycloakDemoSetup,
- ManagerDemoSetup managerDemoSetup,
- RulesEngine rulesEngine) {
- switch (rulesEngine.id) {
- case RulesService.ID_GLOBAL_RULES_ENGINE:
- return createRulesExecutionListener(globalEngineFiredRules)
- case keycloakDemoSetup.masterTenant.id:
- return createRulesExecutionListener(masterEngineFiredRules)
- case keycloakDemoSetup.customerATenant.id:
- return createRulesExecutionListener(customerAEngineFiredRules)
- case managerDemoSetup.apartment2Id:
- return createRulesExecutionListener(apartment2EngineFiredRules)
- case managerDemoSetup.apartment3Id:
- return createRulesExecutionListener(apartment3EngineFiredRules)
- case managerDemoSetup.smartHomeId:
- return createRulesExecutionListener(smartHomeEngineFiredRules)
- }
- }
-
- def resetRulesExecutionListeners() {
- globalEngineFiredRules.clear()
- masterEngineFiredRules.clear()
- customerAEngineFiredRules.clear()
- smartHomeEngineFiredRules.clear()
- apartment2EngineFiredRules.clear()
- apartment3EngineFiredRules.clear()
- }
-
- def assertNoRulesFired = {
- assert globalEngineFiredRules.size() == 0
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 0
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 0
- assert apartment3EngineFiredRules.size() == 0
- }
-
def "Check scoped firing of rules"() {
given: "expected conditions"
def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)
@@ -86,16 +43,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def rulesetStorageService = container.getService(RulesetStorageService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
- and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
- createRulesExecutionListener(keycloakDemoSetup, managerDemoSetup, rulesEngine)
- }
-
and: "some test rulesets have been imported"
def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
+ conditions.eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -110,81 +62,34 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
}
when: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to true"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)
)
assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)
- then: "the rule engines in scope should fire the 'All' and 'All changed' rules"
+ then: "the rule engines in scope should fire the 'All' rule"
conditions.eventually {
- def expectedFiredRules = ["All", "All changed"]
- assert globalEngineFiredRules.size() == 2
- assert globalEngineFiredRules.containsAll(expectedFiredRules)
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 2
- assert customerAEngineFiredRules.containsAll(expectedFiredRules)
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 2
- assert apartment2EngineFiredRules.containsAll(expectedFiredRules)
- assert apartment3EngineFiredRules.size() == 0
+ def expectedFiredRules = ["All"]
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, expectedFiredRules)
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, expectedFiredRules)
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, expectedFiredRules)
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
- when: "an attribute event is pushed into the system for an attribute with RULE_STATE meta set to false"
- resetRulesExecutionListeners()
- def apartment2LivingroomLightSwitchChange = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "lightSwitch", Values.create(false)
- )
- assetProcessingService.sendAttributeEvent(apartment2LivingroomLightSwitchChange)
-
- then: "no rule engines should have fired after a few seconds"
- new PollingConditions(initialDelay: 3).eventually assertNoRulesFired
-
when: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
def apartment2LivingRoomWindowOpenChange = new AttributeEvent(
managerDemoSetup.apartment2LivingroomId, "windowOpen", Values.create(true)
)
assetProcessingService.sendAttributeEvent(apartment2LivingRoomWindowOpenChange)
then: "no rule engines should have fired after a few seconds"
- new PollingConditions(initialDelay: 3).eventually assertNoRulesFired
-
- when: "the same attribute event is pushed into the system (same timestamp as last asset state)"
- resetRulesExecutionListeners()
- assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)
-
- then: "the rule engines in scope should fire the 'All' rule but not the 'All changed' rule"
- conditions.eventually {
- assert globalEngineFiredRules.size() == 1
- assert globalEngineFiredRules[0] == "All"
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 1
- assert customerAEngineFiredRules[0] == "All"
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 1
- assert apartment2EngineFiredRules[0] == "All"
- assert apartment3EngineFiredRules.size() == 0
- }
-
- when: "an attribute event with the same value as current value is pushed into the system"
- resetRulesExecutionListeners()
- apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(
- managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)
- )
- assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)
-
- then: "the rule engines in scope should fire the 'All' rule but not the 'All changed' rule"
- conditions.eventually {
- assert globalEngineFiredRules.size() == 1
- assert globalEngineFiredRules[0] == "All"
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 1
- assert customerAEngineFiredRules[0] == "All"
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 1
- assert apartment2EngineFiredRules[0] == "All"
- assert apartment3EngineFiredRules.size() == 0
+ new PollingConditions(initialDelay: 3).eventually {
+ rulesImport.assertNoRulesFired()
}
cleanup: "the server should be stopped"
@@ -204,16 +109,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def rulesetStorageService = container.getService(RulesetStorageService.class)
def assetProcessingService = container.getService(AssetProcessingService.class)
- and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
- createRulesExecutionListener(keycloakDemoSetup, managerDemoSetup, rulesEngine)
- }
-
and: "some test rulesets have been imported"
def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
+ conditions.eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -228,11 +128,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
}
when: "a LHS filtering test rule definition is loaded into the smart home asset"
- resetRulesExecutionListeners()
def assetRuleset = new AssetRuleset(
"Some smart home asset rules",
managerDemoSetup.smartHomeId,
- getClass().getResource("/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(assetRuleset)
RulesEngine smartHomeEngine = null
@@ -242,36 +142,44 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
smartHomeEngine = rulesService.assetEngines.get(managerDemoSetup.smartHomeId)
assert smartHomeEngine != null
assert smartHomeEngine.isRunning()
- assert smartHomeEngine.allRulesets.length == 1
- assert smartHomeEngine.allRulesets[0].enabled
- assert smartHomeEngine.allRulesets[0].name == "Some smart home asset rules"
- assert smartHomeEngine.allRulesets[0].deploymentStatus == DeploymentStatus.DEPLOYED
+ assert smartHomeEngine.deployments.size() == 1
+ assert smartHomeEngine.deployments.values().any({
+ it.name == "Some smart home asset rules" && it.status == DEPLOYED
+ })
}
and: "the new rule engine is fully initialised"
conditions.eventually {
assert smartHomeEngine.assetStates.size() == DEMO_RULE_STATES_SMART_HOME
- assert smartHomeEngine.knowledgeSession.factCount == DEMO_RULE_STATES_SMART_HOME
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
+ assertRulesFired(smartHomeEngine, 8)
+ assertRulesFired(smartHomeEngine, ["Living Room All", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])
}
when: "an attribute event occurs"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired(smartHomeEngine)
def apartment2LivingRoomPresenceDetectedChange = new AttributeEvent(
managerDemoSetup.apartment2LivingroomId, "presenceDetected", Values.create(true)
)
assetProcessingService.sendAttributeEvent(apartment2LivingRoomPresenceDetectedChange)
- then: "the engines in scope should have fired the matched rules"
+ then: "the engines in scope should have fired"
conditions.eventually {
- assert globalEngineFiredRules.size() == 2
- assert globalEngineFiredRules.containsAll(["All", "All changed"])
- assert customerAEngineFiredRules.size() == 2
- assert customerAEngineFiredRules.containsAll(["All", "All changed"])
- assert smartHomeEngineFiredRules.size() == 5
- assert smartHomeEngineFiredRules.containsAll(["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])
- assert apartment2EngineFiredRules.size() == 2
- assert apartment2EngineFiredRules.containsAll(["All", "All changed"])
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
+ assertRulesFired(smartHomeEngine, 9)
+ assertRulesFired(smartHomeEngine, ["Living Room All", "Current Asset Update", "Parent Type Residence", "Asset Type Room", "Boolean Attributes"])
}
cleanup: "the server should be stopped"
@@ -291,21 +199,16 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def rulesetStorageService = container.getService(RulesetStorageService.class)
def assetStorageService = container.getService(AssetStorageService.class)
- and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
- createRulesExecutionListener(keycloakDemoSetup, managerDemoSetup, rulesEngine)
- }
-
and: "some test rulesets have been imported"
def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
+ conditions.eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
when: "a Kitchen room asset is inserted into apartment that contains a RULE_STATE = true meta flag"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
def apartment2 = assetStorageService.find(managerDemoSetup.apartment2Id)
def asset = new ServerAsset("Kitchen", AssetType.ROOM, apartment2)
asset.setRealmId(keycloakDemoSetup.customerATenant.getId())
@@ -327,20 +230,17 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1
assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1
assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3
- def expectedFiredRules = ["All", "All changed"]
- assert globalEngineFiredRules.size() == 2
- assert globalEngineFiredRules.containsAll(expectedFiredRules)
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 2
- assert customerAEngineFiredRules.containsAll(expectedFiredRules)
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 2
- assert apartment2EngineFiredRules.containsAll(expectedFiredRules)
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
when: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
attributes = [
new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))
.setMeta(
@@ -359,14 +259,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1
assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1
assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3
- assert globalEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 0
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 0
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 0)
+ assertRulesFired(rulesImport.customerAEngine, 0)
+ assertRulesFired(rulesImport.apartment2Engine, 0)
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
when: "the Kitchen room asset is modified to set the RULE_STATE to false"
+ rulesImport.resetRulesFired()
attributes = [
new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))
.setMeta(
@@ -377,7 +277,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
asset.setAttributes(attributes)
asset = assetStorageService.merge(asset)
- then: "the facts should be removed from the rule engines and no rules should have fired"
+ then: "the facts should be removed from the rule engines and rules should have fired"
conditions.eventually {
assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL
assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL
@@ -385,15 +285,17 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A
assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3
- assert globalEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 0
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 0
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
when: "the Kitchen room asset is modified to set all attributes to RULE_STATE = true"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
attributes = [
new AssetAttribute("testString", AttributeType.STRING, Values.create("test"))
.setMeta(
@@ -415,23 +317,20 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 2
assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 2
assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3
- def expectedFiredRules = ["All", "All changed"]
- assert globalEngineFiredRules.size() == 4
- assert globalEngineFiredRules.containsAll(expectedFiredRules)
- assert masterEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 4
- assert customerAEngineFiredRules.containsAll(expectedFiredRules)
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 4
- assert apartment2EngineFiredRules.containsAll(expectedFiredRules)
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
when: "the Kitchen room asset is deleted"
- resetRulesExecutionListeners()
+ rulesImport.resetRulesFired()
assetStorageService.delete(asset.getId())
- then: "the facts should be removed from the rule engines and no rules should have fired"
+ then: "the facts should be removed from the rule engines and rules should have fired"
conditions.eventually {
assert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL
assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL
@@ -439,11 +338,13 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
assert rulesImport.customerAEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A
assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3
- assert globalEngineFiredRules.size() == 0
- assert customerAEngineFiredRules.size() == 0
- assert smartHomeEngineFiredRules.size() == 0
- assert apartment2EngineFiredRules.size() == 0
- assert apartment3EngineFiredRules.size() == 0
+ assertRulesFired(rulesImport.globalEngine, 1)
+ assertRulesFired(rulesImport.globalEngine, ["All"])
+ assertRulesFired(rulesImport.customerAEngine, 1)
+ assertRulesFired(rulesImport.customerAEngine, ["All"])
+ assertRulesFired(rulesImport.apartment2Engine, 1)
+ assertRulesFired(rulesImport.apartment2Engine, ["All"])
+ assertRulesFired(rulesImport.apartment3Engine, 0)
}
cleanup: "the server should be stopped"
@@ -464,16 +365,11 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def assetProcessingService = container.getService(AssetProcessingService.class)
def assetStorageService = container.getService(AssetStorageService.class)
- and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
- createRulesExecutionListener(keycloakDemoSetup, managerDemoSetup, rulesEngine)
- }
-
and: "some test rulesets have been imported"
def rulesImport = new BasicRulesImport(rulesetStorageService, keycloakDemoSetup, managerDemoSetup)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
+ conditions.eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -481,22 +377,21 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainer
def ruleset = new TenantRuleset(
"Some broken test rules",
keycloakDemoSetup.customerATenant.id,
- getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.drl").text
+ getClass().getResource("/org/openremote/test/rules/BasicBrokenRules.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(ruleset)
then: "the customerA engine should not run and the rule engine status should indicate the issue"
conditions.eventually {
- assert rulesImport.customerAEngine.allRulesets.length == 2
+ assert rulesImport.customerAEngine.deployments.size() == 2
assert !rulesImport.customerAEngine.running
- assert rulesImport.customerAEngine.isError()
- assert rulesImport.customerAEngine.error instanceof RuntimeException
- assert rulesImport.customerAEngine.allRulesets[0].enabled
- assert rulesImport.customerAEngine.allRulesets[0].name == "Some customerA tenant demo rules"
- assert rulesImport.customerAEngine.allRulesets[0].deploymentStatus == DeploymentStatus.READY
- assert rulesImport.customerAEngine.allRulesets[1].enabled
- assert rulesImport.customerAEngine.allRulesets[1].name == "Some broken test rules"
- assert rulesImport.customerAEngine.allRulesets[1].deploymentStatus == DeploymentStatus.FAILED
+ assert rulesImport.customerAEngine.deployments.values().any({
+ it.name == "Some customerA tenant demo rules" && it.status == READY
+ })
+ assert rulesImport.customerAEngine.deployments.values().any({
+ it.name == "Some broken test rules" && it.status == COMPILATION_ERROR && it.error instanceof RuntimeException
+ })
}
when: "an attribute event occurs"
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
index 693803820..68a5136cb 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy
@@ -6,15 +6,14 @@ import org.openremote.manager.rules.RulesetStorageService
import org.openremote.model.rules.GlobalRuleset
import org.openremote.model.rules.Ruleset
import org.openremote.test.ManagerContainerTrait
+import spock.lang.Ignore
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
import static java.util.concurrent.TimeUnit.SECONDS
-import static org.openremote.container.timer.TimerService.Clock.PSEUDO
-import static org.openremote.container.timer.TimerService.TIMER_CLOCK_TYPE
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_GLOBAL
-import static org.openremote.test.RulesTestUtil.createRulesExecutionListener
+@Ignore // TODO Implement timer/deferred actions in rules engine
class BasicRulesTimedExecutionTest extends Specification implements ManagerContainerTrait {
RulesEngine globalEngine
@@ -36,9 +35,9 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
def rulesetStorageService = container.getService(RulesetStorageService.class)
and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
+ rulesService.ruleEngineExecutionListeners = { rulesEngine ->
if (rulesEngine.id == RulesService.ID_GLOBAL_RULES_ENGINE) {
- return createRulesExecutionListener(globalEngineFiredRules)
+ return createRuleExecutionListener(globalEngineFiredRules)
}
}
@@ -78,9 +77,9 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
def rulesetStorageService = container.getService(RulesetStorageService.class)
and: "registered rules execution listeners"
- rulesService.rulesEngineListeners = { rulesEngine ->
+ rulesService.ruleEngineExecutionListeners = { rulesEngine ->
if (rulesEngine.id == RulesService.ID_GLOBAL_RULES_ENGINE) {
- return createRulesExecutionListener(globalEngineFiredRules)
+ return createRuleExecutionListener(globalEngineFiredRules)
}
}
@@ -105,7 +104,7 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta
}
when: "the clock is advanced by a few seconds"
- advancePseudoClocks(100, SECONDS, container, globalEngine)
+ advancePseudoClock(100, SECONDS, container, globalEngine)
// TODO Weird behavior of timer rules, pseudo clock, and active mode: More than 5 seconds is needed to fire rule twice
// even more strange it stops at 2 even when advanced for more time. The same problems are with timer(cron: )
// realtime clock seems to be OK
diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
index 84d5ac674..d262443ca 100644
--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy
@@ -19,6 +19,7 @@ import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD_DEFAULT
import static org.openremote.model.Constants.*
+import static org.openremote.model.rules.Ruleset.Lang.GROOVY
class BasicRulesetResourceTest extends Specification implements ManagerContainerTrait {
@@ -47,7 +48,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
def rulesetResource = getClientTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesetResource.class)
expect: "the rules engines to be ready"
- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {
+ new PollingConditions(initialDelay: 2, timeout: 10, delay: 1).eventually {
rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)
}
@@ -86,7 +87,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
/* ############################################## WRITE ####################################### */
when: "global ruleset is created"
- def globalRuleset = new GlobalRuleset("Test global definition", "ThisShouldBeDRL")
+ def globalRuleset = new GlobalRuleset("Test global definition", "SomeRulesCode", GROOVY)
rulesetResource.createGlobalRuleset(null, globalRuleset)
def rulesetId = rulesetResource.getGlobalRulesets(null)[2].id
globalRuleset = rulesetResource.getGlobalRuleset(null, rulesetId)
@@ -98,11 +99,11 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
globalRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
globalRuleset.name == "Test global definition"
- globalRuleset.rules == "ThisShouldBeDRL"
+ globalRuleset.rules == "SomeRulesCode"
when: "a global ruleset is updated"
globalRuleset.name = "Renamed test global definition"
- globalRuleset.rules = "ThisShouldBeDRLAsWell"
+ globalRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateGlobalRuleset(null, rulesetId, globalRuleset)
globalRuleset = rulesetResource.getGlobalRuleset(null, rulesetId)
@@ -112,7 +113,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
globalRuleset.createdOn.time < System.currentTimeMillis()
globalRuleset.lastModified.time > lastModified.time
globalRuleset.name == "Renamed test global definition"
- globalRuleset.rules == "ThisShouldBeDRLAsWell"
+ globalRuleset.rules == "SomeRulesCodeModified"
when: "a global ruleset is deleted"
rulesetResource.deleteGlobalRuleset(null, rulesetId)
@@ -130,7 +131,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "a tenant ruleset is created in the authenticated realm"
- def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.masterTenant.id, "ThisShouldBeDRL")
+ def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.masterTenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
rulesetId = rulesetResource.getTenantRulesets(null, keycloakDemoSetup.masterTenant.id)[1].id
tenantRuleset = rulesetResource.getTenantRuleset(null, rulesetId)
@@ -142,12 +143,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
tenantRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
tenantRuleset.name == "Test tenant definition"
- tenantRuleset.rules == "ThisShouldBeDRL"
+ tenantRuleset.rules == "SomeRulesCode"
tenantRuleset.realmId == keycloakDemoSetup.masterTenant.id
when: "a tenant ruleset is updated"
tenantRuleset.name = "Renamed test tenant definition"
- tenantRuleset.rules = "ThisShouldBeDRLAsWell"
+ tenantRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateTenantRuleset(null, rulesetId, tenantRuleset)
tenantRuleset = rulesetResource.getTenantRuleset(null, rulesetId)
@@ -157,7 +158,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
tenantRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
tenantRuleset.name == "Renamed test tenant definition"
- tenantRuleset.rules == "ThisShouldBeDRLAsWell"
+ tenantRuleset.rules == "SomeRulesCodeModified"
tenantRuleset.realmId == keycloakDemoSetup.masterTenant.id
when: "a tenant ruleset is updated with an invalid realm"
@@ -193,7 +194,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "a tenant ruleset is created in a non-authenticated realm"
- tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "ThisShouldBeDRL")
+ tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
rulesetId = rulesetResource.getTenantRulesets(null, keycloakDemoSetup.customerATenant.id)[1].id
tenantRuleset = rulesetResource.getTenantRuleset(null, rulesetId)
@@ -205,11 +206,11 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
tenantRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
tenantRuleset.name == "Test tenant definition"
- tenantRuleset.rules == "ThisShouldBeDRL"
+ tenantRuleset.rules == "SomeRulesCode"
tenantRuleset.realmId == keycloakDemoSetup.customerATenant.id
when: "an asset ruleset is created in the authenticated realm"
- def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")
+ def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
rulesetId = rulesetResource.getAssetRulesets(null, managerDemoSetup.smartOfficeId)[0].id
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -221,12 +222,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Test asset definition"
- assetRuleset.rules == "ThisShouldBeDRL"
+ assetRuleset.rules == "SomeRulesCode"
assetRuleset.assetId == managerDemoSetup.smartOfficeId
when: "an asset ruleset is updated"
assetRuleset.name = "Renamed test asset definition"
- assetRuleset.rules = "ThisShouldBeDRLAsWell"
+ assetRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateAssetRuleset(null, rulesetId, assetRuleset)
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -236,7 +237,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Renamed test asset definition"
- assetRuleset.rules == "ThisShouldBeDRLAsWell"
+ assetRuleset.rules == "SomeRulesCodeModified"
assetRuleset.assetId == managerDemoSetup.smartOfficeId
when: "an asset ruleset is updated with an invalid asset ID"
@@ -272,7 +273,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "an asset ruleset is created in a non-authenticated realm"
- assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "ThisShouldBeDRL")
+ assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
rulesetId = rulesetResource.getAssetRulesets(null, managerDemoSetup.apartment2Id)[1].id
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -284,7 +285,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Test asset definition"
- assetRuleset.rules == "ThisShouldBeDRL"
+ assetRuleset.rules == "SomeRulesCode"
assetRuleset.assetId == managerDemoSetup.apartment2Id
cleanup: "the server should be stopped"
@@ -354,7 +355,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
/* ############################################## WRITE ####################################### */
when: "a global rule is created"
- def ruleDefinition = new GlobalRuleset("Test definition", "ThisShouldBeDRL")
+ def ruleDefinition = new GlobalRuleset("Test definition", "SomeRulesCode", GROOVY)
rulesetResource.createGlobalRuleset(null, ruleDefinition)
then: "access should be forbidden"
@@ -376,7 +377,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in the authenticated realm"
- def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.masterTenant.id, "ThisShouldBeDRL")
+ def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.masterTenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
def rulesetId = rulesetResource.getTenantRulesets(null, keycloakDemoSetup.masterTenant.id)[1].id
tenantRuleset = rulesetResource.getTenantRuleset(null, rulesetId)
@@ -388,12 +389,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
tenantRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
tenantRuleset.name == "Test tenant definition"
- tenantRuleset.rules == "ThisShouldBeDRL"
+ tenantRuleset.rules == "SomeRulesCode"
tenantRuleset.realmId == keycloakDemoSetup.masterTenant.id
when: "a tenant ruleset is updated"
tenantRuleset.name = "Renamed test tenant definition"
- tenantRuleset.rules = "ThisShouldBeDRLAsWell"
+ tenantRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateTenantRuleset(null, rulesetId, tenantRuleset)
tenantRuleset = rulesetResource.getTenantRuleset(null, rulesetId)
@@ -403,7 +404,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
tenantRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
tenantRuleset.name == "Renamed test tenant definition"
- tenantRuleset.rules == "ThisShouldBeDRLAsWell"
+ tenantRuleset.rules == "SomeRulesCodeModified"
tenantRuleset.realmId == keycloakDemoSetup.masterTenant.id
when: "a tenant ruleset is updated with an invalid realm"
@@ -439,7 +440,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "a tenant ruleset is created in a non-authenticated realm"
- tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "ThisShouldBeDRL")
+ tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
then: "access should be forbidden"
@@ -447,7 +448,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "an asset ruleset is created in the authenticated realm"
- def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")
+ def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
rulesetId = rulesetResource.getAssetRulesets(null, managerDemoSetup.smartOfficeId)[0].id
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -459,12 +460,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Test asset definition"
- assetRuleset.rules == "ThisShouldBeDRL"
+ assetRuleset.rules == "SomeRulesCode"
assetRuleset.assetId == managerDemoSetup.smartOfficeId
when: "an asset ruleset is updated"
assetRuleset.name = "Renamed test asset definition"
- assetRuleset.rules = "ThisShouldBeDRLAsWell"
+ assetRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateAssetRuleset(null, rulesetId, assetRuleset)
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -474,7 +475,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Renamed test asset definition"
- assetRuleset.rules == "ThisShouldBeDRLAsWell"
+ assetRuleset.rules == "SomeRulesCodeModified"
assetRuleset.assetId == managerDemoSetup.smartOfficeId
when: "an asset ruleset is updated with an invalid asset ID"
@@ -510,7 +511,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "an asset ruleset is created in a non-authenticated realm"
- assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "ThisShouldBeDRL")
+ assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
then: "access should be forbidden"
@@ -584,7 +585,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
/* ############################################## WRITE ####################################### */
when: "a global rule is created"
- def ruleDefinition = new GlobalRuleset("Test definition", "ThisShouldBeDRL")
+ def ruleDefinition = new GlobalRuleset("Test definition", "SomeRulesCode", GROOVY)
rulesetResource.createGlobalRuleset(null, ruleDefinition)
then: "access should be forbidden"
@@ -606,7 +607,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in the authenticated realm"
- def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "ThisShouldBeDRL")
+ def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
then: "access should be forbidden"
@@ -628,7 +629,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in a non-authenticated realm"
- tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerBTenant.id, "ThisShouldBeDRL")
+ tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerBTenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
then: "access should be forbidden"
@@ -636,7 +637,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in the authenticated realm"
- def assetRuleset = new AssetRuleset("Test asset definition", keycloakDemoSetup.customerATenant.id, "ThisShouldBeDRL")
+ def assetRuleset = new AssetRuleset("Test asset definition", keycloakDemoSetup.customerATenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
then: "access should be forbidden"
@@ -658,7 +659,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in a non-authenticated realm"
- assetRuleset = new AssetRuleset("Test asset definition", keycloakDemoSetup.customerBTenant.id, "ThisShouldBeDRL")
+ assetRuleset = new AssetRuleset("Test asset definition", keycloakDemoSetup.customerBTenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
then: "access should be forbidden"
@@ -739,7 +740,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
/* ############################################## WRITE ####################################### */
when: "a global rule is created"
- def ruleDefinition = new GlobalRuleset("Test definition", "ThisShouldBeDRL")
+ def ruleDefinition = new GlobalRuleset("Test definition", "SomeRulesCode", GROOVY)
rulesetResource.createGlobalRuleset(null, ruleDefinition)
then: "access should be forbidden"
@@ -761,7 +762,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "a tenant ruleset is created in the authenticated realm"
- def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "ThisShouldBeDRL")
+ def tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerATenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
then: "access should be forbidden"
@@ -784,7 +785,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "a tenant ruleset is created in a non-authenticated realm"
- tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerBTenant.id, "ThisShouldBeDRL")
+ tenantRuleset = new TenantRuleset("Test tenant definition", keycloakDemoSetup.customerBTenant.id, "SomeRulesCode", GROOVY)
rulesetResource.createTenantRuleset(null, tenantRuleset)
then: "access should be forbidden"
@@ -792,7 +793,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "an asset ruleset is created in the authenticated realm"
- def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "ThisShouldBeDRL")
+ def assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment2Id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
def rulesetId = rulesetResource.getAssetRulesets(null, managerDemoSetup.apartment2Id)[1].id
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -804,12 +805,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Test asset definition"
- assetRuleset.rules == "ThisShouldBeDRL"
+ assetRuleset.rules == "SomeRulesCode"
assetRuleset.assetId == managerDemoSetup.apartment2Id
when: "an asset ruleset is updated"
assetRuleset.name = "Renamed test asset definition"
- assetRuleset.rules = "ThisShouldBeDRLAsWell"
+ assetRuleset.rules = "SomeRulesCodeModified"
rulesetResource.updateAssetRuleset(null, rulesetId, assetRuleset)
assetRuleset = rulesetResource.getAssetRuleset(null, rulesetId)
@@ -819,7 +820,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
assetRuleset.createdOn.time < System.currentTimeMillis()
lastModified.time < System.currentTimeMillis()
assetRuleset.name == "Renamed test asset definition"
- assetRuleset.rules == "ThisShouldBeDRLAsWell"
+ assetRuleset.rules == "SomeRulesCodeModified"
assetRuleset.assetId == managerDemoSetup.apartment2Id
when: "an asset ruleset is updated with a changed asset ID"
@@ -863,7 +864,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 404
when: "an asset ruleset is created in the authenticated realm but on a forbidden asset "
- assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment3Id, "ThisShouldBeDRL")
+ assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.apartment3Id, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
then: "access should be forbidden"
@@ -871,7 +872,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainer
ex.response.status == 403
when: "an asset ruleset is created in a non-authenticated realm"
- assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "ThisShouldBeDRL")
+ assetRuleset = new AssetRuleset("Test asset definition", managerDemoSetup.smartOfficeId, "SomeRulesCode", GROOVY)
rulesetResource.createAssetRuleset(null, assetRuleset)
then: "access should be forbidden"
diff --git a/test/src/test/groovy/org/openremote/test/rules/designer/RulesDesignerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/designer/RulesDesignerTest.groovy
deleted file mode 100644
index d0c240ae1..000000000
--- a/test/src/test/groovy/org/openremote/test/rules/designer/RulesDesignerTest.groovy
+++ /dev/null
@@ -1,153 +0,0 @@
-package org.openremote.test.rules.designer
-
-/*
-import org.drools.workbench.models.commons.backend.oracle.PackageDataModelOracleImpl
-import org.drools.workbench.models.commons.backend.rule.ActionCallMethodBuilder
-import org.drools.workbench.models.commons.backend.rule.RuleModelDRLPersistenceImpl
-import org.drools.workbench.models.datamodel.imports.Import
-import org.drools.workbench.models.datamodel.oracle.DataType
-import org.drools.workbench.models.datamodel.rule.*
-import org.hamcrest.Matchers
-import org.openremote.model.asset.AssetEvent
-import org.openremote.model.asset.AssetType
-import org.openremote.model.rules.Assets
-*/
-import org.openremote.test.ManagerContainerTrait
-import spock.lang.Specification
-
-import java.util.logging.Logger
-
-
-/*
-TODO Build DRL programmatically
-
-Requires in test/build.xml:
-
- compile "org.hamcrest:hamcrest-library:1.3"
-
-Requires in manager/build.xml
-
- compile "org.drools:drools-workbench-models-commons:$droolsVersion"
-
-TODO Examples can be found:
-
-https://github.com/kiegroup/drools-wb/tree/master/drools-wb-screens/drools-wb-guided-rule-editor
-https://github.com/kiegroup/drools/tree/master/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule
-https://github.com/kiegroup/drools/blob/master/drools-workbench-models/drools-workbench-models-commons/src/test/java/org/drools/workbench/models/commons/backend/rule/RuleModelDRLPersistenceUnmarshallingTest.java
-https://github.com/kiegroup/drools/blob/master/drools-workbench-models/drools-workbench-models-guided-dtable/src/test/java/org/drools/workbench/models/guided/dtable/backend/BRLRuleModelTest.java
-
-========================================================
-
-package org.openremote.test.rules;
-
-import org.openremote.model.asset.*
-import org.openremote.model.attribute.*
-import org.openremote.model.value.*
-import org.openremote.model.value.Values
-
-global java.util.logging.Logger LOG;
-global org.openremote.model.rules.Assets assets;
-
-rule "Switch room lights off when apartment ALL LIGHTS OFF push-button is pressed"
-when
- // In an asset of type RESIDENCE the All Lights Off push-button is pressed, which sends a 'true' value
- $e: AssetEvent(type == AssetType.RESIDENCE, attributeName == "allLightsOffSwitch", valueAsBoolean == true)
-then
- assets.query() // Execute a query to get "other" assets
- .parent($e.getId()) // Where parent is the apartment in LHS
- .type(AssetType.ROOM) // And the children are of type ROOM
- .applyResults(assetIds -> assetIds.forEach(assetId -> assets.dispatch( // For each asset ID in result...
- new AttributeEvent(assetId, "lightSwitch", Values.create(false)) // Dispatch an event that turns the switch off
- )));
-end
-
-========================================================
- */
-
-class RulesDesignerTest extends Specification implements ManagerContainerTrait {
-/*
- def "Unmarshall DRL into model"() {
-
- when: "some DRL is parsed"
-
- def drl = getClass().getResource("/demo/rules/DemoApartmentAllLightsOff.drl").text
-
- def globals = ["LOG": Logger.class.getName(), "assets": Assets.class.getName()]
- def dmo = new PackageDataModelOracleImpl()
- dmo.addPackageGlobals(globals)
-
- def model = RuleModelDRLPersistenceImpl.getInstance().unmarshal(drl, Collections.emptyList(), dmo)
-
- then: "the result should be ok"
- def rhs0 = model.rhs[0] as ActionCallMethod
- rhs0.methodName == "query"
- rhs0.variable == "assets"
- def drlOut = RuleModelDRLPersistenceImpl.instance.marshal(model)
- println(drlOut)
- // Matchers.equalToIgnoringWhiteSpace(drl).matches(drlOut)
- }
-
- def "Marshall model into DRL"() {
-
- when: "a rules model is build"
-
- def model = new RuleModel()
- model.packageName = "org.openremote.test.rules"
- model.imports.addImport(new Import("org.openremote.model.asset.*"))
- model.imports.addImport(new Import("org.openremote.model.attribute.*"))
- model.imports.addImport(new Import("org.openremote.model.value.*"))
- model.imports.addImport(new Import("org.openremote.model.value.Values"))
-
- def globals = ["LOG": Logger.class.getName(), "assets": Assets.class.getName()]
- def dmo = new PackageDataModelOracleImpl()
- dmo.addPackageGlobals(globals)
- def actionCallMethodBuilder = new ActionCallMethodBuilder(model, dmo, true, new HashMap<String, String>())
-
- model.name = "Switch room lights off when apartment ALL LIGHTS OFF push-button is pressed"
-
- def assetEventFactPattern = new FactPattern(AssetEvent.class.getSimpleName())
- def assetEventFactPatternConstraints = new CompositeFieldConstraint()
- assetEventFactPatternConstraints.setCompositeJunctionType(CompositeFieldConstraint.COMPOSITE_TYPE_AND)
- assetEventFactPattern.addConstraint(assetEventFactPatternConstraints)
- model.addLhsItem(assetEventFactPattern)
- assetEventFactPattern.setBoundName("\$e")
-
- def assetTypeConstraint = new SingleFieldConstraint()
- assetEventFactPatternConstraints.addConstraint(assetTypeConstraint)
- assetTypeConstraint.setFieldName("type")
- assetTypeConstraint.setFieldType(DataType.TYPE_COMPARABLE)
- assetTypeConstraint.setOperator("==")
- assetTypeConstraint.setConstraintValueType(BaseSingleFieldConstraint.TYPE_ENUM)
- assetTypeConstraint.setValue(AssetType.class.getSimpleName() + "." + AssetType.RESIDENCE.name())
-
- def attributeNameConstraint = new SingleFieldConstraint()
- assetEventFactPatternConstraints.addConstraint(attributeNameConstraint)
- attributeNameConstraint.setFieldName("attributeName")
- attributeNameConstraint.setFieldType(DataType.TYPE_STRING)
- attributeNameConstraint.setOperator("==")
- attributeNameConstraint.setConstraintValueType(SingleFieldConstraint.TYPE_LITERAL)
- attributeNameConstraint.setValue("allLightsOffSwitch")
- // TODO Find out how to bind safe values
- // attributeNameConstraint.setValue("allLightsOffSwitch \" && injectionAttack == possible")
-
- def attributeValueConstraint = new SingleFieldConstraint()
- assetEventFactPatternConstraints.addConstraint(attributeValueConstraint)
- attributeValueConstraint.setFieldName("valueAsBoolean")
- attributeValueConstraint.setFieldType(DataType.TYPE_BOOLEAN)
- attributeValueConstraint.setOperator("==")
- attributeValueConstraint.setConstraintValueType(BaseSingleFieldConstraint.TYPE_LITERAL)
- attributeValueConstraint.setValue(Boolean.TRUE.toString())
-
- def dispatchAction = actionCallMethodBuilder.get("assets", "dispatch", "foo")
- model.addRhsItem(new ExpressionGlobalVariable("assets", Assets.class.getName(), Assets.class.getName()))
- model.addRhsItem(dispatchAction)
-
- String drl = RuleModelDRLPersistenceImpl.instance.marshal(model)
- println(drl)
-
- then: "it should be good"
- model.lhs.length == 1
- model.lhs[0] == assetEventFactPattern
- }
- */
-}
diff --git a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy
similarity index 59%
rename from test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy
rename to test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy
index 5c41c4863..dc0f31d23 100644
--- a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentAllLightsOffTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLighgtsOffTest.groovy
@@ -1,4 +1,4 @@
-package org.openremote.test.rules.apartment
+package org.openremote.test.rules.residence
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -18,7 +18,7 @@ import spock.util.concurrent.PollingConditions
import static java.util.concurrent.TimeUnit.SECONDS
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_2
-class ApartmentAllLightsOffTest extends Specification implements ManagerContainerTrait {
+class ResidenceAllLighgtsOffTest extends Specification implements ManagerContainerTrait {
def "Turn all lights off"() {
@@ -37,7 +37,8 @@ class ApartmentAllLightsOffTest extends Specification implements ManagerContaine
Ruleset ruleset = new AssetRuleset(
"Demo Apartment - All Lights Off",
managerDemoSetup.apartment2Id,
- getClass().getResource("/demo/rules/DemoApartmentAllLightsOff.drl").text
+ getClass().getResource("/demo/rules/DemoResidenceAllLightsOff.js").text,
+ Ruleset.Lang.JAVASCRIPT
)
rulesetStorageService.merge(ruleset)
@@ -51,15 +52,17 @@ class ApartmentAllLightsOffTest extends Specification implements ManagerContaine
and: "the demo attributes marked with RULE_STATE = true meta should be inserted into the engines"
conditions.eventually {
assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
- assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2
}
and: "the room lights in an apartment to be on"
- def livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert livingRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean
+ conditions.eventually {
+ def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+ def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
+ assert bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+ }
when: "the ALL LIGHTS OFF push-button is pressed for an apartment"
- setPseudoClocksToRealTime(container, apartment2Engine)
def lightsOffEvent = new AttributeEvent(
managerDemoSetup.apartment2Id, "allLightsOffSwitch", Values.create(true), getClockTimeOf(container)
)
@@ -67,17 +70,28 @@ class ApartmentAllLightsOffTest extends Specification implements ManagerContaine
then: "the room lights in the apartment should be off"
conditions.eventually {
- assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2 + 1
- livingRoomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
- assert !livingRoomAsset.getAttribute("lightSwitch").get().getValueAsBoolean().get()
+ assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
+ assert apartment2Engine.assetEvents.size() == 1
+ def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert !livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
+ def bathRoomAsset = assetStorageService.find(managerDemoSetup.apartment2BathroomId, true)
+ assert !bathRoomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
}
- when: "time advanced"
- advancePseudoClocks(15, SECONDS, container, apartment2Engine)
+ when: "time advanced by 15 seconds"
+ advancePseudoClock(15, SECONDS, container)
- then: "event expired"
- conditions.eventually {
- assert apartment2Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_2
+ and: "we turn the light on again in a room"
+ assetProcessingService.sendAttributeEvent(
+ new AttributeEvent(managerDemoSetup.apartment2LivingroomId, "lightSwitch", Values.create(true))
+ )
+
+ then: "the light should still be on after a few seconds (the all lights off event expires after 3 seconds)"
+ new PollingConditions(initialDelay: 3).eventually {
+ assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2
+ assert apartment2Engine.assetEvents.size() == 0
+ def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)
+ assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()
}
cleanup: "stop the container"
diff --git a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
similarity index 92%
rename from test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotifyAlarmTriggerTest.groovy
rename to test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 87e5b1ee0..50dc48ab8 100644
--- a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -1,4 +1,4 @@
-package org.openremote.test.rules.apartment
+package org.openremote.test.rules.residence
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -26,7 +26,7 @@ import java.util.concurrent.TimeUnit
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1
import static org.openremote.model.Constants.KEYCLOAK_CLIENT_ID
-class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerContainerTrait {
+class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerContainerTrait {
def "Trigger notification when presence is detected and alarm enabled"() {
@@ -56,7 +56,8 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
Ruleset ruleset = new AssetRuleset(
"Demo Apartment - Notify Alarm Trigger",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentNotifyAlarmTrigger.drl").text
+ getClass().getResource("/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -66,7 +67,6 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
assert apartment1Engine != null
assert apartment1Engine.isRunning()
assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1
- assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
}
and: "the alarm enabled, presence detected flag of room should not be set"
@@ -95,7 +95,6 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
notificationService.findDeviceToken("device123", keycloakDemoSetup.testuser3Id).get().token == "token123"
when: "the alarm is enabled"
- setPseudoClocksToRealTime(container, apartment1Engine)
assetProcessingService.sendAttributeEvent(new AttributeEvent(
managerDemoSetup.apartment1Id, "alarmEnabled", Values.create(true), getClockTimeOf(container)
))
@@ -130,7 +129,7 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
}
when: "time moves on and other events happen that trigger evaluation in the rule engine"
- advancePseudoClocks(20, TimeUnit.MINUTES, container, apartment1Engine)
+ advancePseudoClock(20, TimeUnit.MINUTES, container)
assetProcessingService.sendAttributeEvent(new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "co2Level", Values.create(444), getClockTimeOf(container)
))
@@ -144,7 +143,7 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
}
when: "time moves on"
- advancePseudoClocks(30, TimeUnit.MINUTES, container, apartment1Engine)
+ advancePseudoClock(30, TimeUnit.MINUTES, container)
then: "we notify again and now have two notifications pending"
conditions.eventually {
@@ -153,7 +152,7 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
}
when: "the presence os no longer in Living room of apartment 1"
- advancePseudoClocks(5, TimeUnit.SECONDS, container, apartment1Engine)
+ advancePseudoClock(5, TimeUnit.SECONDS, container)
assetProcessingService.sendAttributeEvent(new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "presenceDetected", Values.create(false), getClockTimeOf(container)
))
@@ -165,7 +164,7 @@ class ApartmentNotifyAlarmTriggerTest extends Specification implements ManagerCo
}
when: "time moves on"
- advancePseudoClocks(40, TimeUnit.MINUTES, container, apartment1Engine)
+ advancePseudoClock(40, TimeUnit.MINUTES, container)
then: "we have still only two notifications pending"
conditions.eventually {
diff --git a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
similarity index 51%
rename from test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy
rename to test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
index a9166b831..23ec74004 100644
--- a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentPresenceDetectionTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy
@@ -1,4 +1,4 @@
-package org.openremote.test.rules.apartment
+package org.openremote.test.rules.residence
import org.openremote.agent.protocol.simulator.SimulatorProtocol
import org.openremote.manager.asset.AssetProcessingService
@@ -8,7 +8,6 @@ import org.openremote.manager.rules.RulesService
import org.openremote.manager.rules.RulesetStorageService
import org.openremote.manager.setup.SetupService
import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.asset.AssetEvent
import org.openremote.model.attribute.AttributeEvent
import org.openremote.model.rules.AssetRuleset
import org.openremote.model.rules.Ruleset
@@ -17,16 +16,16 @@ import org.openremote.test.ManagerContainerTrait
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
-import static java.util.concurrent.TimeUnit.*
+import static java.util.concurrent.TimeUnit.MINUTES
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1
import static org.openremote.model.attribute.AttributeEvent.Source.SENSOR
-class ApartmentPresenceDetectionTest extends Specification implements ManagerContainerTrait {
+class ResidencePresenceDetectionTest extends Specification implements ManagerContainerTrait {
def "Presence detection with motion sensor"() {
given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 100, delay: 1)
+ def conditions = new PollingConditions(timeout: 20, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
@@ -38,9 +37,10 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
and: "some rules"
Ruleset ruleset = new AssetRuleset(
- "Demo Apartment - Presence Detection with motion sensor",
+ "Demo Apartment - Presence Detection with motion and CO2 sensors",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentPresenceDetection.drl").text
+ getClass().getResource("/demo/rules/DemoResidencePresenceDetection.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -49,67 +49,106 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)
assert apartment1Engine != null
assert apartment1Engine.isRunning()
- assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
+ assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1
}
and: "the presence detected flag and timestamp should not be set"
- def apartmentAsset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert !apartmentAsset.getAttribute("presenceDetected").get().getValue().isPresent()
- def roomAsset = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
- assert !roomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
- assert !roomAsset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert !apartment.getAttribute("presenceDetected").get().getValue().isPresent()
+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
+ assert !kitchen.getAttribute("presenceDetected").get().getValue().isPresent()
+ assert !kitchen.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ def hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId, true)
+ assert !hallway.getAttribute("presenceDetected").get().getValue().isPresent()
+ assert !hallway.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ }
- when: "motion sensor is triggered"
- double expectedLastPresenceDetected = getClockTimeOf(apartment1Engine)
- def motionSensorTrigger = new AttributeEvent(
+ when: "motion sensor is triggered in all rooms"
+ double expectedLastPresenceDetected = getClockTimeOf(container)
+ def kitchenMotionSensorEvent = new AttributeEvent(
managerDemoSetup.apartment1KitchenId, "motionSensor", Values.create(1)
)
- simulatorProtocol.putValue(motionSensorTrigger)
+ simulatorProtocol.putValue(kitchenMotionSensorEvent)
+ def hallwayMotionSensorEvent = new AttributeEvent(
+ managerDemoSetup.apartment1HallwayId, "motionSensor", Values.create(1)
+ )
+ simulatorProtocol.putValue(hallwayMotionSensorEvent)
- then: "presence should be detected"
+ then: "presence should be detected in all rooms"
conditions.eventually {
- apartmentAsset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert apartmentAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- roomAsset = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
- assert roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
+ assert kitchen.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert kitchen.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ def hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId, true)
+ assert hallway.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert hallway.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
}
when: "time advances"
- advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ advancePseudoClock(5, MINUTES, container)
- and: "motion sensor is triggered"
- expectedLastPresenceDetected = getClockTimeOf(apartment1Engine)
- motionSensorTrigger = new AttributeEvent(
+ and: "motion sensor is triggered a room again"
+ double expectedLastPresenceDetected2 = getClockTimeOf(container)
+ kitchenMotionSensorEvent = new AttributeEvent(
managerDemoSetup.apartment1KitchenId, "motionSensor", Values.create(1)
)
- simulatorProtocol.putValue(motionSensorTrigger)
+ simulatorProtocol.putValue(kitchenMotionSensorEvent)
- then: "presence should be detected and timestamp updated"
+ then: "presence should be detected in all rooms and timestamp should be updated of one room"
conditions.eventually {
- apartmentAsset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert apartmentAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- roomAsset = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
- assert roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
+ assert kitchen.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert kitchen.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected2
+ def hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId, true)
+ assert hallway.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert hallway.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
}
when: "time advances"
- advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ advancePseudoClock(5, MINUTES, container)
- and: "motion sensor is not triggered"
- def motionSensorNoTrigger = new AttributeEvent(
+ and: "motion sensor is not triggered in a room"
+ kitchenMotionSensorEvent = new AttributeEvent(
managerDemoSetup.apartment1KitchenId, "motionSensor", Values.create(0)
)
- simulatorProtocol.putValue(motionSensorNoTrigger)
+ simulatorProtocol.putValue(kitchenMotionSensorEvent)
+
+ then: "some presence should still be detected and timestamps are still available"
+ conditions.eventually {
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert apartment.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
+ assert !kitchen.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert kitchen.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected2
+ def hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId, true)
+ assert hallway.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert hallway.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ }
+
+ when: "time advances"
+ advancePseudoClock(5, MINUTES, container)
+
+ and: "motion sensor is not triggered in another room"
+ hallwayMotionSensorEvent = new AttributeEvent(
+ managerDemoSetup.apartment1HallwayId, "motionSensor", Values.create(0)
+ )
+ simulatorProtocol.putValue(hallwayMotionSensorEvent)
then: "no presence should be detected but the last timestamp still available"
conditions.eventually {
- apartmentAsset = assetStorageService.find(managerDemoSetup.apartment1Id, true)
- assert !apartmentAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- roomAsset = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
- assert !roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ def apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)
+ assert !apartment.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId, true)
+ assert !kitchen.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert kitchen.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected2
+ def hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId, true)
+ assert !hallway.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert hallway.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
}
cleanup: "the server should be stopped"
@@ -119,7 +158,7 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
def "Presence detection with motion sensor and confirmation with CO2 level"() {
given: "the container environment is started"
- def conditions = new PollingConditions(timeout: 10, delay: 1)
+ def conditions = new PollingConditions(timeout: 20, delay: 1)
def serverPort = findEphemeralPort()
def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
@@ -129,13 +168,13 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
def rulesetStorageService = container.getService(RulesetStorageService.class)
def simulatorProtocol = container.getService(SimulatorProtocol.class)
RulesEngine apartment1Engine = null
- List<AssetEvent> insertedAssetEvents = []
and: "some rules"
Ruleset ruleset = new AssetRuleset(
"Demo Apartment - Presence Detection with motion sensor",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentPresenceDetection.drl").text
+ getClass().getResource("/demo/rules/DemoResidencePresenceDetection.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -144,19 +183,18 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)
assert apartment1Engine != null
assert apartment1Engine.isRunning()
- assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
- apartment1Engine.assetEventsConsumer = { assetEvent ->
- insertedAssetEvents << assetEvent
- }
+ assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1
}
and: "the presence detected flag and timestamp of the room should not be set"
- def roomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !roomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
- assert !roomAsset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ conditions.eventually {
+ def roomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !roomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
+ assert !roomAsset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ }
when: "motion sensor is triggered"
- double expectedLastPresenceDetected = getClockTimeOf(apartment1Engine)
+ double expectedLastPresenceDetected = getClockTimeOf(container)
def motionSensorTrigger = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "motionSensor", Values.create(1)
)
@@ -164,16 +202,15 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
then: "presence should not be detected"
new PollingConditions(initialDelay: 3, timeout: 5, delay: 1).eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !asset.getAttribute("presenceDetected").get().getValue().isPresent()
- assert !asset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
+ def roomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !roomAsset.getAttribute("presenceDetected").get().getValue().isPresent()
+ assert !roomAsset.getAttribute("lastPresenceDetected").get().getValue().isPresent()
}
when: "time advances"
- advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ advancePseudoClock(5, MINUTES, container)
and: "the CO2 level increases"
- insertedAssetEvents = []
// The CO2 level increments 3 times, 5 minutes apart
for (i in 1..3) {
@@ -182,52 +219,45 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
)
simulatorProtocol.putValue(co2LevelIncrement)
- // Wait for event and rule consequences to be processed
- new PollingConditions(timeout: 5, delay: 0.5).eventually {
- assert insertedAssetEvents.any() {
+ // Wait for event to be processed
+ conditions.eventually {
+ assert apartment1Engine.assetEvents.any() {
it.matches(co2LevelIncrement, SENSOR, true)
}
assert noEventProcessedIn(assetProcessingService, 500)
}
- advancePseudoClocks(5, MINUTES, container, apartment1Engine)
+ advancePseudoClock(5, MINUTES, container)
}
then: "presence should be detected and the last motion sensor trigger is the last detected timestamp"
conditions.eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
+ def roomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
}
- when: "motion sensor is not triggered"
+ when: "motion sensor is not triggered (nobody moving in the room but maybe present)"
def motionSensorNoTrigger = new AttributeEvent(
managerDemoSetup.apartment1LivingroomId, "motionSensor", Values.create(0)
)
simulatorProtocol.putValue(motionSensorNoTrigger)
- and: "there is no CO2 level increase for a while"
- advancePseudoClocks(20, MINUTES, container, apartment1Engine)
+ and: "there is no CO2 level increase for a while (nobody present in the room)"
+ advancePseudoClock(20, MINUTES, container)
then: "presence should be gone but the last timestamp still available"
conditions.eventually {
- def asset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
- assert !asset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
- assert asset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
- }
-
- when: "time is advanced enough for event expiration"
- advancePseudoClocks(2, HOURS, container, apartment1Engine)
-
- then: "the events should have been expired and retracted automatically from the knowledge session"
- conditions.eventually {
- assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1
+ def roomAsset = assetStorageService.find(managerDemoSetup.apartment1LivingroomId, true)
+ assert !roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()
+ assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected
}
cleanup: "the server should be stopped"
stopContainer(container)
}
+ /* TODO Migrate to JS, didn't compile even with Drools
def "Presence prediction rules compilation"() {
given: "the container environment is started"
@@ -260,5 +290,6 @@ class ApartmentPresenceDetectionTest extends Specification implements ManagerCon
cleanup: "the server should be stopped"
stopContainer(container)
}
+ */
}
diff --git a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy
similarity index 92%
rename from test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy
rename to test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy
index 01cd6de33..c4b408975 100644
--- a/test/src/test/groovy/org/openremote/test/rules/apartment/ApartmentVacationModeTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy
@@ -1,4 +1,4 @@
-package org.openremote.test.rules.apartment
+package org.openremote.test.rules.residence
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
@@ -23,7 +23,7 @@ import static java.util.concurrent.TimeUnit.HOURS
import static org.openremote.manager.setup.SetupTasks.SETUP_IMPORT_DEMO_SCENES
import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES
-class ApartmentVacationModeTest extends Specification implements ManagerContainerTrait {
+class ResidenceVacationModeTest extends Specification implements ManagerContainerTrait {
def "Start and end vacation mode"() {
@@ -42,7 +42,8 @@ class ApartmentVacationModeTest extends Specification implements ManagerContaine
Ruleset ruleset = new AssetRuleset(
"Demo Apartment - Vacation Mode",
managerDemoSetup.apartment1Id,
- getClass().getResource("/demo/rules/DemoApartmentVacationMode.drl").text
+ getClass().getResource("/demo/rules/DemoResidenceVacationMode.groovy").text,
+ Ruleset.Lang.GROOVY
)
rulesetStorageService.merge(ruleset)
@@ -52,8 +53,6 @@ class ApartmentVacationModeTest extends Specification implements ManagerContaine
assert apartment1Engine != null
assert apartment1Engine.isRunning()
assert apartment1Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES
- assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1_WITH_SCENES
- setPseudoClocksToRealTime(container, apartment1Engine)
}
and: "scene timers should be enabled"
@@ -69,7 +68,6 @@ class ApartmentVacationModeTest extends Specification implements ManagerContaine
}
when: "the vacation days are set to 5"
- setPseudoClocksToRealTime(container, apartment1Engine)
double fiveDaysInFuture = getClockTimeOf(container) + (5 * 24 * 60 * 60 * 1000)
assetProcessingService.sendAttributeEvent(new AttributeEvent(
managerDemoSetup.apartment1Id, "vacationUntil", Values.create(fiveDaysInFuture)
@@ -92,7 +90,7 @@ class ApartmentVacationModeTest extends Specification implements ManagerContaine
}
when: "time advanced to the next day"
- advancePseudoClocks(24, HOURS, container, apartment1Engine)
+ advancePseudoClock(24, HOURS, container)
then: "vacation mode is still on"
conditions.eventually {
@@ -108,7 +106,7 @@ class ApartmentVacationModeTest extends Specification implements ManagerContaine
}
when: "time advanced a few days"
- advancePseudoClocks(5, DAYS, container, apartment1Engine)
+ advancePseudoClock(5, DAYS, container)
then: "vacation mode is off and scene timers are enabled"
conditions.eventually {
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.drl b/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.drl
deleted file mode 100644
index e3588fc89..000000000
--- a/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.drl
+++ /dev/null
@@ -1 +0,0 @@
-THIS IS NOT A VALID DRL FILE.
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.groovy b/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.groovy
new file mode 100644
index 000000000..89266baf3
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicBrokenRules.groovy
@@ -0,0 +1 @@
+THIS IS NOT A VALID GROOVY FILE.
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.drl b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.drl
deleted file mode 100644
index d1f80c815..000000000
--- a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.drl
+++ /dev/null
@@ -1,20 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.asset.*;
-
-global java.util.logging.Logger LOG;
-
-rule "All"
-when
- $e: AssetState()
-then
- return;
-end
-
-rule "All changed"
-when
- $e: AssetState(valueChanged)
-then
- return;
-end
\ No newline at end of file
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy
new file mode 100644
index 000000000..dc862aeb4
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates.groovy
@@ -0,0 +1,18 @@
+package org.openremote.test.rules
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+
+RulesBuilder rules = binding.rules
+
+rules.add()
+ .name("All")
+ .when(
+ { facts ->
+ !facts.matchFirst("All").isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery()).isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("All", "fired")
+ })
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.drl b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.drl
deleted file mode 100644
index a44ba1ef1..000000000
--- a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.drl
+++ /dev/null
@@ -1,22 +0,0 @@
-// Renamed rules so they can be deployed again
-
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.asset.*;
-
-global java.util.logging.Logger LOG;
-
-rule "All 2"
-when
- $e: AssetState()
-then
- return;
-end
-
-rule "All changed 2"
-when
- $e: AssetState(valueChanged)
-then
- return;
-end
\ No newline at end of file
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy
new file mode 100644
index 000000000..eb9fdc769
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicMatchAllAssetStates2.groovy
@@ -0,0 +1,20 @@
+// Renamed rules so they can be deployed again
+
+package org.openremote.test.rules
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+
+RulesBuilder rules = binding.rules
+
+rules.add()
+ .name("All")
+ .when(
+ { facts ->
+ !facts.matchFirst("All").isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery()).isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("All", "fired")
+ })
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl
deleted file mode 100644
index 68d039946..000000000
--- a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.drl
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.openremote.test.rules;
-
-import org.openremote.model.*;
-import org.openremote.model.value.ValueType;
-import org.openremote.model.asset.*;
-
-global java.util.logging.Logger LOG;
-
-rule "Living Room All"
-when
- $e: AssetState(name == "Living Room")
-then
- return;
-end
-
-rule "Kitchen All"
-when
- $e: AssetState(name == "Kitchen")
-then
- return;
-end
-
-rule "Kitchen Number Attributes"
-when
- $e: AssetState(name == "Kitchen", attributeType == AttributeType.NUMBER)
-then
- return;
-end
-
-rule "Living Room as Parent"
-when
- AssetState(parentName == "Living Room")
-then
- return;
-end
-
-rule "Boolean Attributes"
-when
- AssetState(attributeType == AttributeType.BOOLEAN)
-then
- return;
-end
-
-rule "String Attributes"
-when
- AssetState(attributeType == AttributeType.STRING)
-then
- return;
-end
-
-rule "Number value types"
-when
- AssetState(value != null, value.type == ValueType.NUMBER)
-then
- return;
-end
-
-rule "Current Asset Update"
-when
- AssetState(processingStatus != AssetState.ProcessingStatus.COMPLETED)
-then
- return;
-end
-
-rule "Parent Type Residence"
-when
- AssetState(parentType == AssetType.RESIDENCE)
-then
- return;
-end
-
-rule "Asset Type Room"
-when
- AssetState(type == AssetType.ROOM)
-then
- return;
-end
\ No newline at end of file
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
new file mode 100644
index 000000000..8a2311946
--- /dev/null
+++ b/test/src/test/resources/org/openremote/test/rules/BasicSmartHomeMatchAllAssetStates.groovy
@@ -0,0 +1,144 @@
+package org.openremote.test.rules
+
+import org.openremote.manager.rules.RulesBuilder
+import org.openremote.model.asset.AssetQuery
+import org.openremote.model.asset.AssetState
+import org.openremote.model.asset.AssetType
+import org.openremote.model.attribute.AttributeType
+
+RulesBuilder rules = binding.rules
+
+rules.add()
+ .name("Living Room All")
+ .when(
+ { facts ->
+ !facts.matchFirst("Living Room All").isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().name("Living Room")).isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Living Room All", "fired")
+ })
+
+rules.add()
+ .name("Kitchen All")
+ .when(
+ { facts ->
+ !facts.matchFirst("Kitchen All").isPresent() &&
+ facts.matchFirstAssetState(new AssetQuery().name("Kitchen")).isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Kitchen All", "fired")
+ })
+
+rules.add()
+ .name("Kitchen Number Attributes")
+ .when(
+ { facts ->
+ !facts.matchFirst("Kitchen Number Attributes").isPresent() &&
+ facts.matchAssetState(new AssetQuery().name("Kitchen"))
+ .filter({ assetState -> assetState.attributeType == AttributeType.NUMBER })
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Kitchen Number Attributes", "fired")
+ })
+
+rules.add()
+ .name("Boolean attributes")
+ .when(
+ { facts ->
+ !facts.matchFirst("Boolean attributes").isPresent() &&
+ facts.matchAssetState(new AssetQuery())
+ .filter({ assetState -> assetState.attributeType == AttributeType.BOOLEAN })
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Boolean attributes", "fired")
+ })
+
+rules.add()
+ .name("String attributes")
+ .when(
+ { facts ->
+ !facts.matchFirst("String Attributes").isPresent() &&
+ facts.matchAssetState(new AssetQuery())
+ .filter({ assetState -> assetState.attributeType == AttributeType.STRING })
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("String Attributes", "fired")
+ })
+
+rules.add()
+ .name("Number value types")
+ .when(
+ { facts ->
+ !facts.matchFirst("Number value types").isPresent() &&
+ facts.matchAssetState(new AssetQuery())
+ .filter({ assetState -> assetState.valueAsNumber.isPresent() })
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Number value types", "fired")
+ })
+
+rules.add()
+ .name("Current Asset Update")
+ .when(
+ { facts ->
+ !facts.matchFirst("Current Asset Update").isPresent() &&
+ facts.matchAssetState(new AssetQuery())
+ .filter({ assetState -> assetState.processingStatus != AssetState.ProcessingStatus.COMPLETED })
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Current Asset Update", "fired")
+ })
+
+rules.add()
+ .name("Parent Type Residence")
+ .when(
+ { facts ->
+ !facts.matchFirst("Parent Type Residence").isPresent() &&
+ facts.matchAssetState(new AssetQuery().parent(AssetType.RESIDENCE))
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Parent Type Residence", "fired")
+ })
+
+rules.add()
+ .name("Asset Type Room")
+ .when(
+ { facts ->
+ !facts.matchFirst("Asset Type Room").isPresent() &&
+ facts.matchAssetState(new AssetQuery().type(AssetType.ROOM))
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Asset Type Room", "fired")
+ })
+
+// This is never matched, living room doesn't have child assets - testing negative
+rules.add()
+ .name("Living Room as Parent")
+ .when(
+ { facts ->
+ !facts.matchFirst("Living Room as Parent").isPresent() &&
+ facts.matchAssetState(new AssetQuery())
+ .filter({ assetState -> assetState.parentName == "Living Room"})
+ .findFirst().isPresent()
+ })
+ .then(
+ { facts ->
+ facts.put("Living Room as Parent", "fired")
+ })