100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Improvements for groovy rules making it easier to create new groovy rules in the Manager UI
Rich Turner24bc956b777d
diff --git a/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java b/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.javaindex f74bbe65a..3aec5f963 100644--- a/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java+++ b/manager/src/main/java/org/openremote/manager/mqtt/MqttBrokerService.java@@ -221,7 +221,7 @@ public class MqttBrokerService extends RouteBuilder implements ContainerService,Tenant tenant = identityProvider.getTenant(realm);- if (tenant == null || !tenant.getEnabled()) {+ if (tenant == null || !tenant.isActive(timerService.getCurrentTimeMillis())) {LOG.warning("Realm not found or is inactive: " + realm);return false;}diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.javaindex bea9beedd..3b65e7bdb 100644--- a/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java+++ b/manager/src/main/java/org/openremote/manager/security/ManagerIdentityProvider.java@@ -275,7 +275,7 @@ public interface ManagerIdentityProvider extends IdentityProvider {static Tenant getTenantFromDb(PersistenceService persistenceService, String realm) {return persistenceService.doReturningTransaction(em -> {- List<Tenant> tenants = em.createQuery("select t from Tenant t where t.realm = :realm and t.enabled = true and (t.notBefore is null or t.notBefore = 0 or to_timestamp(t.notBefore) <= now())", Tenant.class)+ List<Tenant> tenants = em.createQuery("select t from Tenant t where t.realm = :realm", Tenant.class).setParameter("realm", realm).getResultList();return tenants.size() == 1 ? tenants.get(0) : null;}diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.javaindex 578ab4890..333e19bbf 100644--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java@@ -779,13 +779,14 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider imTenant existingTenant = getTenant(realm);// Tenant only has a subset of realm representation so overlay on actual realm representation- realmRepresentation.setRealm(tenant.getRealm());realmRepresentation.setDisplayName(tenant.getDisplayName());realmRepresentation.setAccountTheme(tenant.getAccountTheme());realmRepresentation.setAdminTheme(tenant.getAdminTheme());realmRepresentation.setEmailTheme(tenant.getEmailTheme());realmRepresentation.setLoginTheme(tenant.getLoginTheme());realmRepresentation.setRememberMe(tenant.getRememberMe());+ realmRepresentation.setVerifyEmail(tenant.getVerifyEmail());+ realmRepresentation.setLoginWithEmailAllowed(tenant.getLoginWithEmail());realmRepresentation.setRegistrationAllowed(tenant.getRegistrationAllowed());realmRepresentation.setRegistrationEmailAsUsername(tenant.getRegistrationEmailAsUsername());realmRepresentation.setEnabled(tenant.getEnabled());diff --git a/model/src/main/java/org/openremote/model/notification/Notification.java b/model/src/main/java/org/openremote/model/notification/Notification.javaindex 2be34dc4d..1470fcea6 100644--- a/model/src/main/java/org/openremote/model/notification/Notification.java+++ b/model/src/main/java/org/openremote/model/notification/Notification.java@@ -93,6 +93,9 @@ public class Notification {protected String repeatInterval;protected List<Target> targets;+ public Notification() {+ }+@JsonCreatorpublic Notification(@JsonProperty("name") String name, @JsonProperty("message") AbstractNotificationMessage message, @JsonProperty("targets") List<Target> targets, @JsonProperty("repeatFrequency") RepeatFrequency repeatFrequency, @JsonProperty("repeatInterval") String repeatInterval) {this.name = name;diff --git a/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.javaindex 306b8a480..1e611bd58 100644--- a/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/AttributePredicate.java@@ -70,6 +70,18 @@ public class AttributePredicate extends NameValuePredicate {return this;}+ @Override+ public AttributePredicate name(String name) {+ this.name = new StringPredicate(name);+ return this;+ }++ @Override+ public AttributePredicate name(NameHolder name) {+ this.name = new StringPredicate(name);+ return this;+ }+@Overridepublic AttributePredicate value(ValuePredicate value) {this.value = value;diff --git a/model/src/main/java/org/openremote/model/query/filter/GeofencePredicate.java b/model/src/main/java/org/openremote/model/query/filter/GeofencePredicate.javaindex 5f277072f..3dff9e9f3 100644--- a/model/src/main/java/org/openremote/model/query/filter/GeofencePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/GeofencePredicate.java@@ -29,7 +29,7 @@ public abstract class GeofencePredicate extends ValuePredicate {public abstract double[] getCentrePoint();public GeofencePredicate negate() {- negated = true;+ negated = !negated;return this;}}diff --git a/model/src/main/java/org/openremote/model/query/filter/NameValuePredicate.java b/model/src/main/java/org/openremote/model/query/filter/NameValuePredicate.javaindex 4670a8dd1..2a90d0028 100644--- a/model/src/main/java/org/openremote/model/query/filter/NameValuePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/NameValuePredicate.java@@ -123,6 +123,16 @@ public class NameValuePredicate {return this;}+ public NameValuePredicate name(String name) {+ this.name = new StringPredicate(name);+ return this;+ }++ public NameValuePredicate name(NameHolder name) {+ this.name = new StringPredicate(name);+ return this;+ }+public NameValuePredicate value(ValuePredicate value) {this.value = value;return this;diff --git a/model/src/main/java/org/openremote/model/query/filter/RadialGeofencePredicate.java b/model/src/main/java/org/openremote/model/query/filter/RadialGeofencePredicate.javaindex 37a921bef..f1590b9d9 100644--- a/model/src/main/java/org/openremote/model/query/filter/RadialGeofencePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/RadialGeofencePredicate.java@@ -45,6 +45,9 @@ public class RadialGeofencePredicate extends GeofencePredicate {public double lat;public double lng;+ public RadialGeofencePredicate() {+ }+@JsonCreatorpublic RadialGeofencePredicate(@JsonProperty("radius") int radius,@JsonProperty("lat") double lat,@@ -64,7 +67,22 @@ public class RadialGeofencePredicate extends GeofencePredicate {@Overridepublic RadialGeofencePredicate negate() {- negated = true;+ negated = !negated;+ return this;+ }++ public RadialGeofencePredicate radius(int radius) {+ this.radius = radius;+ return this;+ }++ public RadialGeofencePredicate lat(double lat) {+ this.lat = lat;+ return this;+ }++ public RadialGeofencePredicate lng(double lng) {+ this.lng = lng;return this;}diff --git a/model/src/main/java/org/openremote/model/query/filter/RectangularGeofencePredicate.java b/model/src/main/java/org/openremote/model/query/filter/RectangularGeofencePredicate.javaindex d62184751..32dd284f1 100644--- a/model/src/main/java/org/openremote/model/query/filter/RectangularGeofencePredicate.java+++ b/model/src/main/java/org/openremote/model/query/filter/RectangularGeofencePredicate.java@@ -46,6 +46,9 @@ public class RectangularGeofencePredicate extends GeofencePredicate {public double latMax;public double lngMax;+ public RectangularGeofencePredicate() {+ }+@JsonCreatorpublic RectangularGeofencePredicate(@JsonProperty("latMin") double latMin,@JsonProperty("lngMin") double lngMin,@@ -68,7 +71,7 @@ public class RectangularGeofencePredicate extends GeofencePredicate {@Overridepublic RectangularGeofencePredicate negate() {- negated = true;+ negated = !negated;return this;}diff --git a/model/src/main/java/org/openremote/model/rules/Ruleset.java b/model/src/main/java/org/openremote/model/rules/Ruleset.javaindex 2dbaa5821..1ecb43d24 100644--- a/model/src/main/java/org/openremote/model/rules/Ruleset.java+++ b/model/src/main/java/org/openremote/model/rules/Ruleset.java@@ -32,7 +32,6 @@ import javax.persistence.*;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_JSON_VALUE_TYPE;import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;@@ -52,110 +51,13 @@ import static org.openremote.model.Constants.PERSISTENCE_SEQUENCE_ID_GENERATOR;})public abstract class Ruleset {- 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().types(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" +- "import org.openremote.model.rules.*\n" +- "import java.util.logging.*\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.matchFirstAssetState(\n" +- " new AssetQuery().types(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" +- " })"),- JSON(".json",- "locations: [],\n" +- "rules: [\n" +- " {\n" +- " name: \"Test Rule\",\n" +- " when: {\n" +- " operator: \"AND\",\n" +- " predicates: [\n" +- " {\n" +- " query: {\n" +- "\n" +- " }\n" +- " }\n" +- " ],\n" +- " conditions: []\n" +- " },\n" +- " then: {\n" +- " notifications: [],\n" +- " attributeEvents: []\n" +- " },\n" +- " reset: null // Only trigger once ever\n" +- " }\n" +- "]"- ),- FLOW(".json", "{\"name\":\"\", \"description\": \"\", \"nodes\":[], \"connections\":[]}");-- public static final MetaItemDescriptor<Boolean> SHOW_ON_LIST = new MetaItemDescriptor<>("showOnList", ValueType.BOOLEAN);-- final String fileExtension;- final String emptyRulesExample;-- Lang(String fileExtension, String emptyRulesExample) {- this.fileExtension = fileExtension;- this.emptyRulesExample = emptyRulesExample;- }-- public String getFileExtension() {- return fileExtension;- }+ public static final MetaItemDescriptor<Boolean> SHOW_ON_LIST = new MetaItemDescriptor<>("showOnList", ValueType.BOOLEAN);- 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();- }+ public enum Lang {+ JAVASCRIPT,+ GROOVY,+ JSON,+ FLOW}@Iddiff --git a/model/src/main/java/org/openremote/model/security/Tenant.java b/model/src/main/java/org/openremote/model/security/Tenant.javaindex e893c8224..565143975 100644--- a/model/src/main/java/org/openremote/model/security/Tenant.java+++ b/model/src/main/java/org/openremote/model/security/Tenant.java@@ -57,35 +57,40 @@ public class Tenant {@Column(name = "NOT_BEFORE")protected Double notBefore; // This will explode in 2038- // We allow password reset by default- @Transient- protected Boolean resetPasswordAllowed = true;+ @Column(name = "reset_password_allowed")+ protected Boolean resetPasswordAllowed;- @Transient+ @Column(name = "duplicate_emails_allowed")protected Boolean duplicateEmailsAllowed;- @Transient+ @Column(name = "remember_me")protected Boolean rememberMe;- @Transient+ @Column(name = "registration_allowed")protected Boolean registrationAllowed;- @Transient+ @Column(name = "reg_email_as_username")protected Boolean registrationEmailAsUsername;- @Transient+ @Column(name = "verify_email")+ protected Boolean verifyEmail;++ @Column(name = "login_with_email_allowed")+ protected Boolean loginWithEmail;++ @Column(name = "login_theme")protected String loginTheme;- @Transient+ @Column(name = "account_theme")protected String accountTheme;- @Transient+ @Column(name = "admin_theme")protected String adminTheme;- @Transient+ @Column(name = "email_theme")protected String emailTheme;- @Transient+ @Column(name = "access_token_lifespan")protected Integer accessTokenLifespan;@OneToMany(fetch = FetchType.EAGER)@@ -93,7 +98,6 @@ public class Tenant {protected Set<RealmRole> realmRoles;public Tenant() {- this(null, null, null, null);}public Tenant(String id, String realm, String displayName, Boolean enabled) {@@ -153,7 +157,8 @@ public class Tenant {}public Boolean getResetPasswordAllowed() {- return resetPasswordAllowed;+ // We allow password reset by default+ return resetPasswordAllowed != null ? resetPasswordAllowed : true;}public Tenant setResetPasswordAllowed(Boolean resetPasswordAllowed) {@@ -162,7 +167,7 @@ public class Tenant {}public Boolean getDuplicateEmailsAllowed() {- return duplicateEmailsAllowed;+ return duplicateEmailsAllowed != null && duplicateEmailsAllowed;}public Tenant setDuplicateEmailsAllowed(Boolean duplicateEmailsAllowed) {@@ -170,8 +175,35 @@ public class Tenant {return this;}+ public Boolean getVerifyEmail() {+ return verifyEmail != null && verifyEmail;+ }++ public Tenant setVerifyEmail(Boolean verifyEmail) {+ this.verifyEmail = verifyEmail;+ return this;+ }++ public Boolean getLoginWithEmail() {+ return loginWithEmail != null && loginWithEmail;+ }++ public Tenant setLoginWithEmail(Boolean loginWithEmail) {+ this.loginWithEmail = loginWithEmail;+ return this;+ }++ public Integer getAccessTokenLifespan() {+ return accessTokenLifespan;+ }++ public Tenant setAccessTokenLifespan(Integer accessTokenLifespan) {+ this.accessTokenLifespan = accessTokenLifespan;+ return this;+ }+public Boolean getRememberMe() {- return rememberMe;+ return rememberMe != null && rememberMe;}public Tenant setRememberMe(Boolean rememberMe) {@@ -180,7 +212,7 @@ public class Tenant {}public Boolean getRegistrationAllowed() {- return registrationAllowed;+ return registrationAllowed != null && registrationAllowed;}public Tenant setRegistrationAllowed(Boolean registrationAllowed) {@@ -189,7 +221,7 @@ public class Tenant {}public Boolean getRegistrationEmailAsUsername() {- return registrationEmailAsUsername;+ return registrationEmailAsUsername != null && registrationEmailAsUsername;}public Tenant setRegistrationEmailAsUsername(Boolean registrationEmailAsUsername) {@@ -259,7 +291,7 @@ public class Tenant {public static Field[] getPropertyFields() {if (propertyFields == null) {propertyFields = Arrays.stream(Tenant.class.getDeclaredFields())- .filter(field -> field.isAnnotationPresent(Column.class))+ .filter(field -> field.isAnnotationPresent(Column.class) || field.isAnnotationPresent(JoinColumn.class) || field.isAnnotationPresent(Formula.class)).toArray(Field[]::new);}return propertyFields;@@ -293,6 +325,19 @@ public class Tenant {", displayName='" + displayName + '\'' +", enabled=" + enabled +", notBefore=" + notBefore ++ ", resetPasswordAllowed=" + resetPasswordAllowed ++ ", duplicateEmailsAllowed=" + duplicateEmailsAllowed ++ ", rememberMe=" + rememberMe ++ ", registrationAllowed=" + registrationAllowed ++ ", registrationEmailAsUsername=" + registrationEmailAsUsername ++ ", verifyEmail=" + verifyEmail ++ ", loginWithEmail=" + loginWithEmail ++ ", loginTheme='" + loginTheme + '\'' ++ ", accountTheme='" + accountTheme + '\'' ++ ", adminTheme='" + adminTheme + '\'' ++ ", emailTheme='" + emailTheme + '\'' ++ ", accessTokenLifespan=" + accessTokenLifespan ++ ", realmRoles=" + realmRoles +'}';}}diff --git a/test/src/main/java/org/openremote/test/setup/RulesTestSetup.java b/test/src/main/java/org/openremote/test/setup/RulesTestSetup.javaindex 8d20434ef..35042657a 100644--- a/test/src/main/java/org/openremote/test/setup/RulesTestSetup.java+++ b/test/src/main/java/org/openremote/test/setup/RulesTestSetup.java@@ -32,7 +32,7 @@ import java.nio.charset.StandardCharsets;import java.util.logging.Logger;import static org.openremote.model.rules.Ruleset.Lang.GROOVY;-import static org.openremote.model.rules.Ruleset.Lang.SHOW_ON_LIST;+import static org.openremote.model.rules.Ruleset.SHOW_ON_LIST;public class RulesTestSetup extends ManagerSetup {diff --git a/test/src/main/resources/org/openremote/test/rules/ConsoleLocation.groovy b/test/src/main/resources/org/openremote/test/rules/ConsoleLocation.groovyindex b786fd0af..f4bd8c1e0 100644--- a/test/src/main/resources/org/openremote/test/rules/ConsoleLocation.groovy+++ b/test/src/main/resources/org/openremote/test/rules/ConsoleLocation.groovy@@ -1,17 +1,15 @@package org.openremote.test.rulesimport org.openremote.manager.rules.RulesBuilder+import org.openremote.model.notification.*import org.openremote.test.setup.ManagerTestSetupimport org.openremote.model.asset.Assetimport org.openremote.model.asset.impl.*-import org.openremote.model.notification.Notification-import org.openremote.model.notification.PushNotificationMessage-import org.openremote.model.query.AssetQuery-import org.openremote.model.query.filter.LocationAttributePredicate-import org.openremote.model.query.filter.RadialGeofencePredicate-import org.openremote.model.query.filter.ValueEmptyPredicate+import org.openremote.model.query.*+import org.openremote.model.query.filter.*import org.openremote.model.rules.Assetsimport org.openremote.model.rules.Notifications+import org.openremote.model.rules.Usersimport java.util.logging.Loggerimport java.util.stream.Collectors@@ -19,6 +17,7 @@ import java.util.stream.CollectorsLogger LOG = binding.LOGRulesBuilder rules = binding.rulesNotifications notifications = binding.notifications+Users users = binding.usersAssets assets = binding.assetsrules.add()diff --git a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovyindex 4775b6eb5..520f809b0 100644--- a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy@@ -55,7 +55,7 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTradef "Check UDP client protocol and linked attribute deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 5, delay: 0.2)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container starts"def container = startContainer(defaultConfig(), defaultServices())diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovyindex d65e7104a..268242d0c 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy@@ -13,7 +13,7 @@ import org.openremote.model.rules.Rulesetimport org.openremote.model.rules.TenantRulesetimport static org.openremote.model.rules.Ruleset.Lang.GROOVY-import static org.openremote.model.rules.Ruleset.Lang.SHOW_ON_LIST+import static org.openremote.model.rules.Ruleset.SHOW_ON_LISTimport static org.openremote.model.rules.RulesetStatus.DEPLOYEDclass BasicRulesImport {diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovyindex 2852a49f1..96727150f 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy@@ -19,7 +19,7 @@ import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIimport static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULTimport static org.openremote.model.Constants.*import static org.openremote.model.rules.Ruleset.Lang.GROOVY-import static org.openremote.model.rules.Ruleset.Lang.SHOW_ON_LIST+import static org.openremote.model.rules.Ruleset.SHOW_ON_LISTclass BasicRulesetResourceTest extends Specification implements ManagerContainerTrait {diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovyindex 76a15fd90..4f3ab9fd5 100644--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy@@ -195,21 +195,4 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {writeRole.compositeRoleIds.length == 1writeRole.compositeRoleIds.contains(roles.find {it.name == ClientRole.READ_ASSETS.value}.id)}-- def "Get realm roles"() {-- when: "a request is made for the realm roles in the building realm by the admin user"- def roles = adminUserResource.getRealmRoles(null, keycloakTestSetup.tenantBuilding.realm)-- then: "the standard realm roles should have been returned"- roles.size() == 4- def restrictedUser = roles.find {it.name == RESTRICTED_USER_REALM_ROLE }- restrictedUser != null-- when: "a request is made for the realm roles in the building realm by a regular user"- regularUserResource.getRealmRoles(null, keycloakTestSetup.tenantBuilding.realm)-- then: "a not allowed exception should be thrown"- thrown(ForbiddenException.class)- }}diff --git a/ui/component/or-rules/src/index.ts b/ui/component/or-rules/src/index.tsindex 26122fc41..eb942b959 100644--- a/ui/component/or-rules/src/index.ts+++ b/ui/component/or-rules/src/index.ts@@ -1,4 +1,4 @@-import {css, html, LitElement, unsafeCSS} from "lit";+import {css, html, LitElement, TemplateResult, unsafeCSS} from "lit";import {customElement, property, query} from "lit/decorators.js";import manager, {AssetModelUtil,@@ -117,6 +117,7 @@ export interface RulesConfig {when?: RulesDescriptorSection;action?: RulesDescriptorSection;};+ rulesetTemplates?: {[key in RulesetLang]?: string};rulesetAddHandler?: (ruleset: RulesetUnion) => boolean;rulesetDeleteHandler?: (ruleset: RulesetUnion) => boolean;rulesetCopyHandler?: (ruleset: RulesetUnion) => boolean;@@ -171,6 +172,175 @@ export interface RuleView {config?: RulesConfig;}+export interface RuleViewInfo {+ viewTemplateProvider: (ruleset:RulesetUnion, config: RulesConfig | undefined, readonly: boolean) => TemplateResult;+ viewRulesetTemplate?: string;+}++export const RuleViewInfoMap: {[key in RulesetLang]: RuleViewInfo} = {+ JSON: {+ viewTemplateProvider: (ruleset, config, readonly) => html`<or-rule-json-viewer id="rule-view" .ruleset="${ruleset}" .config="${config}" .readonly="${readonly}"></or-rule-json-viewer>`,+ },+ FLOW: {+ viewTemplateProvider: (ruleset, config, readonly) => html`<flow-editor id="rule-view" .ruleset="${ruleset}" .readonly="${readonly}"></flow-editor>`+ },+ GROOVY: {+ viewTemplateProvider: (ruleset, config, readonly) => html`+ <or-rule-text-viewer id="rule-view" .ruleset="${ruleset}" .config="${config}" .readonly="${readonly}"></or-rule-text-viewer>+ `,+ viewRulesetTemplate: "package demo.rules\n" ++ "\n" ++ "import org.openremote.manager.rules.RulesBuilder\n" ++ "import org.openremote.model.notification.*\n" ++ "import org.openremote.model.rules.AssetState\n" ++ "import org.openremote.model.asset.Asset\n" ++ "import org.openremote.model.asset.impl.*\n" ++ "import org.openremote.model.query.*\n" ++ "import org.openremote.model.query.filter.*\n" ++ "import org.openremote.model.rules.Assets\n" ++ "import org.openremote.model.rules.Notifications\n" ++ "import org.openremote.model.rules.Users\n" ++ "import org.simplejavamail.email.Email\n" ++ "\n" ++ "import java.util.logging.Logger\n" ++ "import java.util.stream.Collectors\n" ++ "\n" ++ "Logger LOG = binding.LOG\n" ++ "RulesBuilder rules = binding.rules\n" ++ "Notifications notifications = binding.notifications\n" ++ "Users users = binding.users\n" ++ "Assets assets = binding.assets\n" ++ "\n" ++ "/*\n" ++ "* A groovy rule is made up of a when closure (LHS) which must return a boolean indicating whether the then closure (RHS)\n" ++ "* should be executed. The rule engine will periodically evaluate the when closure and if it evaluates to true then the\n" ++ "* rule then closure will execute.\n" ++ "*\n" ++ "* NOTE: DO NOT MODIFY THE FACTS IN THE WHEN CLOSURE THIS SHOULD BE DONE IN THE THEN CLOSURE\n" ++ "*\n" ++ "* To avoid an infinite rule loop the when closure should not continually return true for subsequent executions\n" ++ "* so either the then closure should perform an action that prevents the when closure from matching on subsequent\n" ++ "* evaluations, or custom facts should be used, some ideas:\n" ++ "*\n" ++ "* - Change the value of an attribute being matched in the when closure (which will prevent it matching on subsequent evaluations)\n" ++ "* - Insert a custom fact on first match and test this fact in the when closure to determine when the rule should match again (for\n" ++ "* example if a rule should match whenever the asset state changes the asset state timestamp can be used)\n" ++ "*/\n" ++ "\n" ++ "rules.add()\n" ++ " .name(\"Example rule\")\n" ++ " .when({\n" ++ " facts ->\n" ++ "\n" ++ " // Find first matching asset state using an asset query\n" ++ "\n" ++ " facts.matchFirstAssetState(\n" ++ "\n" ++ " // Find asset state by asset type and attribute name\n" ++ " new AssetQuery().types(ThingAsset).attributeNames(\"someAttribute\")\n" ++ "\n" ++ " // Find asset state by asset ID and attribute name\n" ++ " //new AssetQuery().ids(\"7CaBoyiDhtdf2kn1Xso1w5\").attributeNames(\"someAttribute\")\n" ++ "\n" ++ " // Find asset state by asset type, attribute name and value string predicate\n" ++ " //new AssetQuery().types(ThingAsset).attributes(\n" ++ " // new AttributePredicate()\n" ++ " // .name(\"someAttribute\")\n" ++ " // .value(new StringPredicate()\n" ++ " // .value(\"someValue\")\n" ++ " // .match(AssetQuery.Match.EXACT)\n" ++ " // .caseSensitive(true)))\n" ++ "\n" ++ " // Find asset state by asset type and location attribute predicate\n" ++ " //new AssetQuery().types(ThingAsset).attributes(\n" ++ " // new AttributePredicate()\n" ++ " // .name(Asset.LOCATION)\n" ++ " // .value(new RadialGeofencePredicate()\n" ++ " // .radius(100)\n" ++ " // .lat(50.0)\n" ++ " // .lng(0.0)))\n" ++ "\n" ++ " ).map { assetState ->\n" ++ "\n" ++ " // Use logging to help with debugging if needed" ++ " //LOG.info(\"ATTRIBUTE FOUND\")\n" ++ "\n" ++ " // Check if this rule really should fire this time\n" ++ " Optional<Long> lastFireTimestamp = facts.getOptional(\"someAttribute\")\n" ++ " if (lastFireTimestamp.isPresent() && assetState.getTimestamp() <= lastFireTimestamp.get()) {\n" ++ " return false\n" ++ " }\n" ++ "\n" ++ " // OK to fire if we reach here\n" ++ "\n" ++ " // Compute and bind any facts required for the then closure\n" ++ " facts.bind(\"assetState\", assetState)\n" ++ " true\n" ++ " }.orElseGet {\n" ++ " // Asset state didn't match so clear out any custom facts to allow the rule to fire next time the when closure matches\n" ++ " facts.remove(\"someAttribute\")\n" ++ " false\n" ++ " }\n" ++ "\n" ++ "})\n" ++ " .then({\n" ++ " facts ->\n" ++ "\n" ++ " // Extract any binded facts\n" ++ " AssetState assetState = facts.bound(\"assetState\")\n" ++ "\n" ++ " // Insert the custom fact to prevent rule loop\n" ++ " facts.put(\"someAttribute\", assetState.getTimestamp())\n" ++ "\n" ++ " // Write to attributes\n" ++ " def otherAttributeValue = null\n" ++ " if (assetState.getValue().orElse{null} == \"Value 1\") {\n" ++ " otherAttributeValue = \"Converted Value 1\"\n" ++ " } else if (assetState.getValue().orElse{null} == \"Value 2\") {\n" ++ " otherAttributeValue = \"Converted Value 2\"\n" ++ " } else {\n" ++ " otherAttributeValue = \"Unknown\"\n" ++ " }\n" ++ " assets.dispatch(assetState.id, \"otherAttribute\", otherAttributeValue)\n" ++ "\n" ++ " // Generate notifications (useful for rules that check if an attribute is out of range)\n" ++ " //notifications.send(new Notification()\n" ++ " // .setName(\"Attribute alert\")\n" ++ " // .setMessage(new EmailNotificationMessage()\n" ++ " // .setTo(\"[email protected]\")\n" ++ " // .setSubject(\"Attribute out of range: Attribute=${assetState.name} Asset ID=${assetState.id}\")\n" ++ " // .setText(\"Some text body\")\n" ++ " // .setHtml(\"<p>Or some HTML body</p>\")\n" ++ " // )\n" ++ " //)\n" ++ "})"+ },+ JAVASCRIPT: {+ viewTemplateProvider: (ruleset, config, readonly) => html`+ <or-rule-text-viewer id="rule-view" .ruleset="${ruleset}" .config="${config}" .readonly="${readonly}"></or-rule-text-viewer>+ `,+ viewRulesetTemplate: "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().types(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" ++ "]"+ }+}+function getAssetDescriptorFromSection(assetType: string, config: RulesConfig | undefined, useActionConfig: boolean): RulesConfigAsset | undefined {if (!config || !config.descriptors) {return;diff --git a/ui/component/or-rules/src/or-rule-list.ts b/ui/component/or-rules/src/or-rule-list.tsindex bd445bb21..2a9e10941 100644--- a/ui/component/or-rules/src/or-rule-list.ts+++ b/ui/component/or-rules/src/or-rule-list.ts@@ -14,7 +14,7 @@ import {OrRulesRequestSelectionEvent,OrRulesSelectionEvent,RulesConfig,- RulesetNode+ RulesetNode, RuleViewInfoMap} from "./index";import "@openremote/or-mwc-components/or-mwc-menu";import {getContentWithMenuTemplate} from "@openremote/or-mwc-components/or-mwc-menu";@@ -460,6 +460,12 @@ export class OrRuleList extends translate(i18next)(LitElement) {return;}+ if (this.config && this.config.rulesetTemplates && this.config.rulesetTemplates[lang]) {+ ruleset.rules = this.config.rulesetTemplates[lang];+ } else {+ ruleset.rules = RuleViewInfoMap[lang].viewRulesetTemplate;+ }+// Ensure config hasn't messed with certain valuesif (type === "tenant") {(ruleset as TenantRuleset).realm = realm;diff --git a/ui/component/or-rules/src/or-rule-viewer.ts b/ui/component/or-rules/src/or-rule-viewer.tsindex e529076ff..2741ab93b 100644--- a/ui/component/or-rules/src/or-rule-viewer.ts+++ b/ui/component/or-rules/src/or-rule-viewer.ts@@ -1,15 +1,16 @@import {css, html, LitElement, PropertyValues, TemplateResult} from "lit";import {customElement, property, query} from "lit/decorators.js";import {+ OrRulesRequestSaveEvent,OrRulesRuleChangedEvent,OrRulesRuleUnsupportedEvent,OrRulesSaveEvent,- OrRulesRequestSaveEvent,RulesConfig,- RuleView+ RuleView,+ RuleViewInfoMap} from "./index";-import {ClientRole, RulesetLang, RulesetUnion} from "@openremote/model";-import manager, { Util } from "@openremote/core";+import {ClientRole, RulesetUnion} from "@openremote/model";+import manager, {Util} from "@openremote/core";import "./json-viewer/or-rule-json-viewer";import "./or-rule-text-viewer";import "./or-rule-validity";@@ -18,8 +19,8 @@ import "@openremote/or-mwc-components/or-mwc-input";import {translate} from "@openremote/or-translate";import {InputType, OrInputChangedEvent, OrMwcInput} from "@openremote/or-mwc-components/or-mwc-input";import i18next from "i18next";-import { GenericAxiosResponse } from "@openremote/rest";-import { showErrorDialog } from "@openremote/or-mwc-components/or-mwc-dialog";+import {GenericAxiosResponse} from "@openremote/rest";+import {showErrorDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {project} from "./flow-viewer/components/flow-editor";// language=CSS@@ -159,25 +160,8 @@ export class OrRuleViewer extends translate(i18next)(LitElement) {return html`<div class="wrapper" style="justify-content: center"><or-translate value="noRuleSelected"></or-translate></div>`;}- let viewer: TemplateResult | string = ``;- if (!this._supported || this.ruleset.lang === RulesetLang.GROOVY || this.ruleset.lang === RulesetLang.JAVASCRIPT) {- viewer = html`- <or-rule-text-viewer id="rule-view" .ruleset="${this.ruleset}" .config="${this.config}" .readonly="${this.readonly}"></or-rule-text-viewer>- `;- } else {- switch (this.ruleset.lang!) {- case RulesetLang.JSON:- viewer = html`<or-rule-json-viewer id="rule-view" .ruleset="${this.ruleset}" .config="${this.config}" .readonly="${this.readonly}"></or-rule-json-viewer>`;- break;- case RulesetLang.FLOW:- viewer = html`<flow-editor id="rule-view" .ruleset="${this.ruleset}" .readonly="${this.readonly}"></flow-editor>`;- break;- default:- viewer = html`<div class="wrapper"><or-translate value="notSupported"></or-translate></div>`;- }- }+ let viewer = RuleViewInfoMap[this.ruleset!.lang!].viewTemplateProvider(this.ruleset, this.config, this.readonly);- // TODO: load the appropriate viewer depending on state and ruleset languagereturn html`<div id="main-wrapper" class="wrapper"><div id="rule-header">