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
Add assetid templates (#1497)
Mihaela Aleksandrova77e015a96787
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.javaindex d9f9d9821..9419dcba7 100644--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java@@ -20,6 +20,7 @@package org.openremote.manager.rules;import jakarta.ws.rs.core.MediaType;+import org.openremote.container.timer.TimerService;import org.openremote.manager.asset.AssetStorageService;import org.openremote.model.PersistenceEvent;@@ -535,6 +536,7 @@ public class JsonRulesBuilder extends RulesBuilder {public static final String PLACEHOLDER_RULESET_ID = "%RULESET_ID%";public static final String PLACEHOLDER_RULESET_NAME = "%RULESET_NAME%";public static final String PLACEHOLDER_TRIGGER_ASSETS = "%TRIGGER_ASSETS%";+ public static final String PLACEHOLDER_ASSET_ID = "%ASSET_ID%";final static String TIMER_TEMPORAL_FACT_NAME_PREFIX = "TimerTemporalFact-";final static String LOG_PREFIX = "JSON Rule '";final protected AssetStorageService assetStorageService;@@ -791,15 +793,47 @@ public class JsonRulesBuilder extends RulesBuilder {boolean isPush = Objects.equals(notification.getMessage().getType(), PushNotificationMessage.TYPE);boolean isHtml;- if (isEmail) {+ if (isLocalized) {+ LocalizedNotificationMessage localizedMsg = (LocalizedNotificationMessage) notification.getMessage();+ isHtml = false;+ localizedMsg.getMessages().forEach((lang, msg) -> {+ if (msg instanceof PushNotificationMessage pushMsg) {+ PushNotificationAction action = pushMsg.getAction();+ if (action != null && action.getUrl() != null) {+ String newUrl = replaceAssetIdPlaceholder(action.getUrl(), ruleState, useUnmatched, "notification URL", true);+ action.setUrl(newUrl);+ pushMsg.setAction(action);+ }++ if (pushMsg.getBody() != null) {+ String newBody = replaceAssetIdPlaceholder(pushMsg.getBody(), ruleState, useUnmatched, "notification body", false);+ pushMsg.setBody(newBody);+ }+ }+ });+ body = null;+ } else if (isEmail) {EmailNotificationMessage email = (EmailNotificationMessage) notification.getMessage();isHtml = !TextUtil.isNullOrEmpty(email.getHtml());body = isHtml ? email.getHtml() : email.getText();} else {isHtml = false;if (isPush) {- PushNotificationMessage pushNotificationMessage = (PushNotificationMessage) notification.getMessage();- body = pushNotificationMessage.getBody();+ PushNotificationMessage pushMsg = (PushNotificationMessage) notification.getMessage();+ PushNotificationAction action;+ body = pushMsg.getBody();+ action = pushMsg.getAction();++ if (action != null && action.getUrl() != null) {+ String newUrl = replaceAssetIdPlaceholder(action.getUrl(), ruleState, useUnmatched, "notification URL", true);+ action.setUrl(newUrl);+ pushMsg.setAction(action);+ }++ if (body!= null) {+ String newBody = replaceAssetIdPlaceholder(body, ruleState, useUnmatched, "notification body", false);+ pushMsg.setBody(newBody);+ }} else {body = null;}@@ -1201,6 +1235,27 @@ public class JsonRulesBuilder extends RulesBuilder {return sourceText.replace(PLACEHOLDER_TRIGGER_ASSETS, sb.toString());}+ protected String replaceAssetIdPlaceholder(String text, RuleState ruleState, boolean useUnmatched, String context, boolean firstOnly) {+ if (TextUtil.isNullOrEmpty(text) || !text.contains(PLACEHOLDER_ASSET_ID)) {+ return text;+ }++ Set<String> matchedIds = useUnmatched ? ruleState.otherwiseMatchedAssetIds : ruleState.thenMatchedAssetIds;++ if (matchedIds != null && !matchedIds.isEmpty()) {+ String replacement = firstOnly ? matchedIds.iterator().next() : String.join(",", matchedIds);+++ String result = text.replace(PLACEHOLDER_ASSET_ID, replacement);+ log(Level.FINEST, "Replaced asset ID(s) in " + context + ": " + result);+ return result;+ } else {+ log(Level.WARNING, "Asset ID placeholder used but no matched assets found for " + context);+ return text;+ }+ }++protected String insertTriggeredAssetInfo(String sourceText, Map<String, Set<AttributeInfo>> assetStates, boolean isHtml, boolean isJson) {StringBuilder sb = new StringBuilder();diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovyindex cf727cbb2..7505ce5b4 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy@@ -384,22 +384,94 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {and: "an localized email notification should have been sent with the triggered asset in the body but only containing the triggered asset states"String expectedHtml = "<table cellpadding=\"30\"><tr><th>Asset ID</th><th>Asset Name</th><th>Attribute</th><th>Value</th></tr><tr><td>${consoleRegistration.id}</td><td>Test Console</td><td>location</td><td>" + ValueUtil.asJSON(outsideLocation).orElse("") + "</td></tr></table>"conditions.eventually {- assert localizedMessages.size() == 5- assert localizedMessages.stream().allMatch {+ assert localizedMessages.size() == 7+ // Get only email messages+ emailMessages = localizedMessages.findAll { localizedMsg ->+ localizedMsg.getMessages().values().stream().allMatch { message ->+ message.type == EmailNotificationMessage.TYPE+ }+ }++ // Verify email content+ assert emailMessages.stream().allMatch {it.getMessages().values().stream().allMatch(m -> {- m.type == EmailNotificationMessage.TYPE && ((EmailNotificationMessage) m).getHtml() == expectedHtml+ ((EmailNotificationMessage) m).getHtml() == expectedHtml})}- assert localizedMessages.stream().filter {++ assert emailMessages.stream().filter {it.getMessages().values().stream().allMatch {((EmailNotificationMessage) it).getSubject() == "Demo Apartment - All Lights Off"}}.count() == 3- assert localizedMessages.stream().filter {++ assert emailMessages.stream().filter {it.getMessages().values().stream().allMatch {((EmailNotificationMessage) it).getSubject() == "Linked user localized user test"}}.count() == 2++ // Get push messages+ def pushMessages = localizedMessages.findAll { localizedMsg ->+ localizedMsg.getMessages().values().stream().allMatch { message ->+ message.type == PushNotificationMessage.TYPE+ }+ }++ // Verify push notifications+ def assetIdPushNotification = pushMessages.find { localizedMsg ->+ localizedMsg.getMessages().get("en") instanceof PushNotificationMessage &&+ ((PushNotificationMessage) localizedMsg.getMessages().get("en")).getBody()?.contains(consoleRegistration.id)+ }++ assert assetIdPushNotification != null+ assert ((PushNotificationMessage) assetIdPushNotification.getMessages().get("en")).getBody() == "English: Asset ${consoleRegistration.id} has moved"+ assert ((PushNotificationMessage) assetIdPushNotification.getMessages().get("nl")).getBody() == "Nederlands: Asset ${consoleRegistration.id} is verplaatst"++ // Verify no unprocessed placeholders remain+ assert pushMessages.every { localizedMsg ->+ localizedMsg.getMessages().values().every { msg ->+ !((PushNotificationMessage) msg).getBody()?.contains("%ASSET_ID%")+ }+ }+ }++ and: "a push notification with asset ID should have been sent to both linked users"+ conditions.eventually {+ // Count notifications for users with test-realm-role+ def linkedNotifications = pushTargetsAndMessages.findAll {+ it.v2.title == "Linked Asset ID Test" &&+ it.v2.body == "This notification is about asset: ${consoleRegistration.id}"+ }+ assert linkedNotifications.size() == 2 // should be sent to both linked users+ }++ and: "the action URL should contain the corect asset ID"+ conditions.eventually {+ // First find the relevant message+ def targetMessage = pushTargetsAndMessages.find { it.v2.title == "URL Asset ID Test" }+ assert targetMessage != null++ // Then verify URL+ assert targetMessage.v2.action?.url == "/assets/${consoleRegistration.id}/details"+ }++ and: "notifications should still contain asset ID even for user without access"+ conditions.eventually {+ assetStorageService.storeUserAssetLinks([+ new UserAssetLink(keycloakTestSetup.realmBuilding.getName(), keycloakTestSetup.testuser3Id, consoleRegistration.id)+ ])+ // Print debug info+ println "Available notifications:"+ pushTargetsAndMessages.each { target, msg ->+ println "Target: ${target}, Message: title='${msg.title}', body='${msg.body}'"+ }++ assert pushTargetsAndMessages.any {+ it.v1.type == Notification.TargetType.ASSET &&+ it.v2.title == "Asset ID Test" &&+ it.v2.body == "Your asset ID is: ${consoleRegistration.id}"+ }}and: "after a few seconds the rule should not have fired again"diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.jsonindex 9a5de0280..d54bf9aa3 100644--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json@@ -187,6 +187,83 @@}}},+ {+ "action": "notification",+ "target": {+ "linkedUsers": true+ },+ "notification": {+ "name": "localizedAssetIdTest",+ "message": {+ "type": "localized",+ "defaultLanguage": "en",+ "languages": {+ "en": {+ "type": "push",+ "title": "Asset Location Change",+ "body": "English: Asset %ASSET_ID% has moved"+ },+ "nl": {+ "type": "push",+ "title": "Asset Locatie Verandering",+ "body": "Nederlands: Asset %ASSET_ID% is verplaatst"+ }+ }+ }+ }+ },+ {+ "action": "notification",+ "target": {+ "linkedUsers": true+ },+ "notification": {+ "name": "assetIdTest",+ "message": {+ "type": "push",+ "title": "Asset ID Test",+ "body": "Your asset ID is: %ASSET_ID%"+ }+ }+ },+ {+ "action": "notification",+ "target": {+ "linkedUsers": true,+ "users": {+ "realmRoles": [+ {+ "predicateType": "string",+ "match": "BEGIN",+ "value": "test-realm-role"+ }+ ]+ }+ },+ "notification": {+ "name": "linkedAssetIdTest",+ "message": {+ "type": "push",+ "title": "Linked Asset ID Test",+ "body": "This notification is about asset: %ASSET_ID%"+ }+ }+ },+ {+ "action": "notification",+ "notification": {+ "name": "urlAssetIdTest",+ "message": {+ "type": "push",+ "title": "URL Asset ID Test",+ "body": "Click here",+ "action": {+ "url": "/assets/%ASSET_ID%/details",+ "httpMethod": "GET"+ }+ }+ }+ },{"action": "write-attribute","target": {