Skip to content

armgit / core

Public Imported from GitHub
0

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

Notification testing and fixes

Rich Turner7c4cdd1e9b65
diff --git a/container/src/main/java/org/openremote/container/web/WebResource.java b/container/src/main/java/org/openremote/container/web/WebResource.java
index 1b47bf6ef..1f8e0f7c0 100644
--- a/container/src/main/java/org/openremote/container/web/WebResource.java
+++ b/container/src/main/java/org/openremote/container/web/WebResource.java
@@ -99,26 +99,26 @@ public class WebResource implements AuthContext {
@Override
public String getAuthenticatedRealm() {
- return getAuthContext().getAuthenticatedRealm();
+ return isAuthenticated() ? getAuthContext().getAuthenticatedRealm() : null;
}
@Override
public String getUsername() {
- return getAuthContext().getUsername();
+ return isAuthenticated() ? getAuthContext().getUsername() : null;
}
@Override
public String getUserId() {
- return getAuthContext().getUserId();
+ return isAuthenticated() ? getAuthContext().getUserId() : null;
}
@Override
public boolean hasRealmRole(String role) {
- return getAuthContext().hasRealmRole(role);
+ return isAuthenticated() && getAuthContext().hasRealmRole(role);
}
@Override
public boolean hasResourceRole(String role, String resource) {
- return getAuthContext().hasResourceRole(role, resource);
+ return isAuthenticated() && getAuthContext().hasResourceRole(role, resource);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
index a25f43cf5..205d70923 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -311,9 +311,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
public void setNotificationDelivered(long id, long timestamp) {
persistenceService.doTransaction(entityManager -> {
- Query query = entityManager.createQuery("UPDATE Notification SET deliveryOn=:timestamp WHERE id =:id");
+ Query query = entityManager.createQuery("UPDATE SentNotification SET deliveredOn=:timestamp WHERE id =:id");
query.setParameter("id", id);
- query.setParameter("timestamp", timestamp);
+ query.setParameter("timestamp", new Date(timestamp));
query.executeUpdate();
});
}
@@ -324,9 +324,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
public void setNotificationAcknowleged(long id, String acknowledgement, long timestamp) {
persistenceService.doTransaction(entityManager -> {
- Query query = entityManager.createQuery("UPDATE Notification SET acknowledgedOn=:timestamp, acknowledgement=:acknowledgement WHERE id =:id");
+ Query query = entityManager.createQuery("UPDATE SentNotification SET acknowledgedOn=:timestamp, acknowledgement=:acknowledgement WHERE id =:id");
query.setParameter("id", id);
- query.setParameter("timestamp", timestamp);
+ query.setParameter("timestamp", new Date(timestamp));
query.setParameter("acknowledgement", acknowledgement);
query.executeUpdate();
});
@@ -338,22 +338,21 @@ public class NotificationService extends RouteBuilder implements ContainerServic
public List<SentNotification> getNotifications(List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {
StringBuilder builder = new StringBuilder();
- builder.append("select Notification n where 1=1");
+ builder.append("select n from SentNotification n where 1=1");
List<Object> parameters = new ArrayList<>();
processCriteria(builder, parameters, types, timestamp, tenantIds, userIds, assetIds);
return persistenceService.doReturningTransaction(entityManager -> {
TypedQuery<SentNotification> query = entityManager.createQuery(builder.toString(), SentNotification.class);
- // Parameters should be 1 based but bug in hibernate means 0 based
IntStream.range(0, parameters.size())
- .forEach(i -> query.setParameter(i, parameters.get(i)));
+ .forEach(i -> query.setParameter(i+1, parameters.get(i)));
return query.getResultList();
});
}
public void removeNotification(Long id) {
persistenceService.doTransaction(entityManager -> entityManager
- .createQuery("delete Notification n where n.id = :id")
+ .createQuery("delete SentNotification n where n.id = :id")
.setParameter("id", id)
.executeUpdate()
);
@@ -362,7 +361,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
public void removeNotifications(List<String> types, Long timestamp, List<String> tenantIds, List<String> userIds, List<String> assetIds) throws IllegalArgumentException {
StringBuilder builder = new StringBuilder();
- builder.append("delete Notification n where 1=1");
+ builder.append("delete SentNotification n where 1=1");
List<Object> parameters = new ArrayList<>();
processCriteria(builder, parameters, types, timestamp, tenantIds, userIds, assetIds);
@@ -370,7 +369,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
Query query = entityManager.createQuery(builder.toString());
// Parameters should be 1 based but bug in hibernate means 0 based
IntStream.range(0, parameters.size())
- .forEach(i -> query.setParameter(i, parameters.get(i)));
+ .forEach(i -> query.setParameter(i+1, parameters.get(i)));
query.executeUpdate();
});
}
@@ -413,7 +412,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
if (hasTenants) {
builder.append(" AND n.target = ?")
.append(parameters.size() + 1)
- .append(" AND n.target_id IN ?")
+ .append(" AND n.targetId IN ?")
.append(parameters.size() + 2);
parameters.add(Notification.TargetType.TENANT);
parameters.add(tenantIds);
@@ -422,7 +421,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
if (hasUsers) {
builder.append(" AND n.target = ?")
.append(parameters.size() + 1)
- .append(" AND n.target_id IN ?")
+ .append(" AND n.targetId IN ?")
.append(parameters.size() + 2);
parameters.add(Notification.TargetType.USER);
@@ -432,7 +431,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
if (hasAssets) {
builder.append(" AND n.target = ?")
.append(parameters.size() + 1)
- .append("AND n.target_id ANY ?")
+ .append(" AND n.targetId IN ?")
.append(parameters.size() + 2);
parameters.add(Notification.TargetType.ASSET);
@@ -440,7 +439,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
if (timestamp != null) {
- builder.append(" n.sent_on <= ?")
+ builder.append(" n.sentOn <= ?")
.append(parameters.size() + 1);
parameters.add(timestamp);
@@ -541,7 +540,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
protected boolean okToSendNotification(Notification.Source source, String sourceId, Notification.TargetType target, String targetId, String name, long timestamp) {
return persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
- "SELECT COUNT(n) FROM NOTIFICATION n WHERE n.source =:source AND n.source_id =:sourceId AND n.target =:target AND n.target_id =:targetId AND n.name =:name AND n.sent_on >=:timestamp", Long.class)
+ "SELECT COUNT(n) FROM SentNotification n WHERE n.source =:source AND n.sourceId =:sourceId AND n.target =:target AND n.targetId =:targetId AND n.name =:name AND n.sentOn >=:timestamp", Long.class)
.setParameter("source", source)
.setParameter("sourceId", sourceId)
.setParameter("target", target)
@@ -583,10 +582,4 @@ public class NotificationService extends RouteBuilder implements ContainerServic
exchange.getOut().setBody(exception);
};
}
-
- protected List<String> findAllUsersWithToken() {
- return persistenceService.doReturningTransaction(entityManager ->
- entityManager.createQuery("SELECT DISTINCT dnt.id.userId FROM DeviceNotificationToken dnt", String.class).getResultList()
- );
- }
}
\ No newline at end of file
diff --git a/model/src/main/java/org/openremote/model/notification/NotificationResource.java b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
index e1bbb42a3..3ff07da67 100644
--- a/model/src/main/java/org/openremote/model/notification/NotificationResource.java
+++ b/model/src/main/java/org/openremote/model/notification/NotificationResource.java
@@ -120,6 +120,7 @@ public interface NotificationResource {
*/
@PUT
@Path("{notificationId}/acknowledged")
+ @Consumes(APPLICATION_JSON)
@SuccessStatusCode(204)
@SuppressWarnings("unusable-by-js")
void notificationAcknowledged(@BeanParam RequestParams requestParams,
diff --git a/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java b/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java
index d544f921a..b71c4075e 100644
--- a/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java
+++ b/model/src/main/java/org/openremote/model/notification/PushNotificationAction.java
@@ -19,6 +19,8 @@
*/
package org.openremote.model.notification;
+import com.fasterxml.jackson.annotation.JsonCreator;
+import com.fasterxml.jackson.annotation.JsonProperty;
import org.openremote.model.attribute.AttributeRef;
import org.openremote.model.util.TextUtil;
import org.openremote.model.value.ObjectValue;
@@ -41,7 +43,12 @@ public class PushNotificationAction {
this.url = url;
}
- public PushNotificationAction(String url, Value data, boolean silent, boolean openInBrowser, String httpMethod) {
+ @JsonCreator
+ public PushNotificationAction(@JsonProperty("url") String url,
+ @JsonProperty("data") Value data,
+ @JsonProperty("silent") boolean silent,
+ @JsonProperty("openInBrowser") boolean openInBrowser,
+ @JsonProperty("httpMethod") String httpMethod) {
this.url = url;
this.data = data;
this.silent = silent;
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationResourceTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationResourceTest.groovy
deleted file mode 100644
index 1bfe4e436..000000000
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationResourceTest.groovy
+++ /dev/null
@@ -1,313 +0,0 @@
-package org.openremote.test.notification
-
-import org.openremote.container.timer.TimerService
-import org.openremote.manager.notification.NotificationService
-import org.openremote.manager.notification.PushNotificationHandler
-import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
-import org.openremote.manager.setup.SetupService
-import org.openremote.manager.setup.builtin.KeycloakDemoSetup
-import org.openremote.manager.setup.builtin.ManagerDemoSetup
-import org.openremote.model.attribute.AttributeRef
-import org.openremote.model.console.ConsoleProvider
-import org.openremote.model.console.ConsoleRegistration
-import org.openremote.model.console.ConsoleResource
-import org.openremote.model.notification.Notification
-import org.openremote.model.notification.NotificationResource
-import org.openremote.model.notification.NotificationSendResult
-import org.openremote.model.notification.PushNotificationMessage
-import org.openremote.model.query.UserQuery
-import org.openremote.model.query.filter.UserAssetPredicate
-import org.openremote.model.value.ObjectValue
-import org.openremote.model.value.Values
-import org.openremote.test.ManagerContainerTrait
-import spock.lang.Ignore
-import spock.lang.Specification
-
-import javax.ws.rs.WebApplicationException
-
-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.notification.PushNotificationAction.writeAttributeValueAction
-import static org.openremote.model.value.Values.parse
-
-@Ignore
-class NotificationResourceTest extends Specification implements ManagerContainerTrait {
-
- def "Check full notification resource behaviour"() {
-
- def notificationIds = []
- def targetTypes = []
- def targetIds = []
- def messages = []
-
- given: "a mock push notification handler"
- PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
- isValid() >> true
-
- // Assume sent to FCM
- sendMessage(*_) >> {
- id, targetType, targetId, message ->
- notificationIds << id
- targetTypes << targetType
- targetIds << targetId
- messages << message
- return NotificationSendResult.success()
- }
- }
-
- and: "the container environment is started with the mock handler"
- def serverPort = findEphemeralPort()
- def services = defaultServices()
- ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
- def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)
- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
- def notificationService = container.getService(NotificationService.class)
-
- and: "an authenticated test user"
- def realm = keycloakDemoSetup.customerATenant.realm
- def testuser3AccessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- "testuser3",
- "testuser3"
- ).token
- def testuser2AccessToken = authenticate(
- container,
- realm,
- KEYCLOAK_CLIENT_ID,
- "testuser2",
- "testuser2"
- ).token
-
- and: "an authenticated superuser"
- def adminAccessToken = authenticate(
- container,
- MASTER_REALM,
- KEYCLOAK_CLIENT_ID,
- MASTER_REALM_ADMIN_USER,
- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
- ).token
-
- def notification = new Notification("TestAction",
- new PushNotificationMessage("Test Action",
- "Click to cancel",
- writeAttributeValueAction(
- new AttributeRef(
- managerDemoSetup.apartment1LivingroomId,
- "alarmEnabled"
- ),
- Values.create(false)),null, null), null)
-
- and: "the notification resource"
- def testuser2NotificationResource = getClientTarget(serverUri(serverPort), realm, testuser2AccessToken).proxy(NotificationResource.class)
- def testuser3NotificationResource = getClientTarget(serverUri(serverPort), realm, testuser3AccessToken).proxy(NotificationResource.class)
- def adminNotificationResource = getClientTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(NotificationResource.class)
- def anonymousNotificationResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm).proxy(NotificationResource.class)
- def testuser2ConsoleResource = getClientTarget(serverUri(serverPort), realm, testuser2AccessToken).proxy(ConsoleResource.class)
- def testuser3ConsoleResource = getClientTarget(serverUri(serverPort), realm, testuser3AccessToken).proxy(ConsoleResource.class)
- def adminConsoleResource = getClientTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(ConsoleResource.class)
- def anonymousConsoleResource = getClientTarget(serverUri(serverPort), realm).proxy(ConsoleResource.class)
-
- when: "various consoles are registered"
- def consoleRegistration = new ConsoleRegistration(null,
- "Test Console",
- "1.0",
- "Android 7.0",
- new HashMap<String, ConsoleProvider>() {
- {
- put("geofence", new ConsoleProvider(
- ORConsoleGeofenceAssetAdapter.NAME,
- true,
- false,
- false,
- null
- ))
- put("push", new ConsoleProvider(
- "fcm",
- true,
- true,
- false,
- (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)
- ))
- }
- })
- def testuser2Console = testuser2ConsoleResource.register(null, consoleRegistration)
- def testuser3Console = testuser3ConsoleResource.register(null, consoleRegistration)
- def adminConsole = adminConsoleResource.register(null, consoleRegistration)
- def anonymousConsole = anonymousConsoleResource.register(null, consoleRegistration)
-
- then: "the consoles should have been created"
- testuser2Console.id != null
- testuser3Console.id != null
- adminConsole.id != null
- anonymousConsole.id != null
-
- when: "the admin user sends a push notification to an entire realm"
-
- then: "all consoles in that realm should have been sent a notification"
-
- when: "a regular user sends a push notification to an entire realm"
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "the admin user sends a notification to testuser2"
- notification.setTargets(new Notification.Targets(User))
- adminNotificationResource.sendNotification(null, notification)
-
- then: "the notification should have been sent"
- notificationIds.size() == 1
-
- when: "a regular user sends a push notification to another realm user"
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "a restricted user sends a push notification to another realm user"
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "the admin user sends a push notification to the Consoles asset in customerA realm"
-
- then: "the notification should have been sent"
-
- when: "a regular user sends a push notification to the Consoles asset in customerA realm"
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "a restricted user sends a push notification to the Consoles asset in customerA realm"
-
- then: "access should be forbidden"
- ex = thrown()
- ex.response.status == 403
-
- when: "a regular user is linked to the Consoles asset in customerA realm and they send a notification to this asset"
-
- then: "the notification should have been sent"
-
-
-
-
-
-
-
- and: ""
-
- expect: "there should be no user registered to receive notifications"
- notificationService.findAllUsersWithToken().isEmpty()
-
- when: "the notification tokens of some devices are stored"
- testuser3NotificationResource.storeDeviceToken(null, "device123", "token123", "ANDROID")
- testuser3NotificationResource.storeDeviceToken(null, "device456", "token456", "ANDROID")
-
- then: "the tokens should be in the database"
- def tokens = adminNotificationResource.getDeviceTokens(null, keycloakDemoSetup.testuser3Id)
- tokens.size() == 2
- tokens[0].id.deviceId == "device456"
- tokens[0].deviceType == "ANDROID"
- tokens[0].token == "token456"
- tokens[0].updatedOn.time <= container.getService(TimerService.class).currentTimeMillis
- tokens[1].id.deviceId == "device123"
- tokens[1].deviceType == "ANDROID"
- tokens[1].token == "token123"
- tokens[1].updatedOn.time <= container.getService(TimerService.class).currentTimeMillis
-
- and: "test user must be registered to receive notifications"
- notificationService.findAllUsersWithToken().size() == 1
- def foundUser = notificationService.findAllUsersWithToken().first()
- foundUser == keycloakDemoSetup.testuser3Id
-//
-// and: "must find registered test user if limiting to same tenant"
-// notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).size() == 1
-// def foundUser2 = notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerATenant.id))).first()
-// foundUser2 == keycloakDemoSetup.testuser3Id
-//
-// and: "must not find registered test user if limiting to different tenant"
-// notificationService.findAllUsersWithToken(new UserQuery().tenant(new UserQuery.TenantPredicate().realmId(keycloakDemoSetup.customerBTenant.id))).isEmpty()
-
- and: "must find registered test user if limiting to asset user has access to"
- notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment1Id))).size() == 1
- def foundUser3 = notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment1Id))).first()
- foundUser3 == keycloakDemoSetup.testuser3Id
-
- and: "must not find registered test user if limiting to asset user has not access to"
- notificationService.findAllUsersWithToken(new UserQuery().asset(new UserAssetPredicate().id(managerDemoSetup.apartment3Id))).isEmpty()
-
- when: "the notification token of some device is updated"
- testuser3NotificationResource.storeDeviceToken(null, "device456", "token789", "ANDROID")
-
- then: "the updated token should be in the database"
- def thirdToken = notificationService.findDeviceToken("device456", keycloakDemoSetup.testuser3Id)
- thirdToken.get().token == "token789"
- notificationService.findAllTokenForUser(keycloakDemoSetup.testuser3Id).size() == 2
-
- when: "the notification is stored"
- testuser3NotificationResource.sendNotification(null, notification)
- def alerts = testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null)
-
- then: "it should be one notification pending"
- alerts.size() == 1
-
- when: "a user tries to store a notification for another user"
- testuser2NotificationResource.storeNotificationForUser(null, keycloakDemoSetup.testuser3Id, notification)
-
- then: "an exception should be thrown"
- WebApplicationException ex = thrown()
- ex.response.status == 403
-
- when: "a user tries to acknowledge a notification she doesn't own"
- testuser2NotificationResource.notificationAcknowledged(null, alerts.get(0).id)
-
- then: "an exception should be thrown"
- ex = thrown()
- ex.response.status == 403
-
- when: "the notification is acknowledged"
- testuser3NotificationResource.notificationAcknowledged(null, alerts.get(0).id)
-
- then: "there should be no alert"
- testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null).size() == 0
-
- when: "the notification is stored"
- testuser3NotificationResource.sendNotification(null, notification)
- alerts = adminNotificationResource.getNotificationsOfUser(null, keycloakDemoSetup.testuser3Id)
-
- then: "it should be one notification queued"
- alerts.size() == 2
- alerts.any {
- it.deliveryStatus == DeliveryStatus.ACKNOWLEDGED
- }
- alerts.any {
- it.deliveryStatus == DeliveryStatus.QUEUED
- }
-
- when: "all notifications of the user are removed"
- adminNotificationResource.removeNotifications(null, keycloakDemoSetup.testuser3Id)
-
- then: "there should be no alert"
- testuser3NotificationResource.getQueuedNotificationsOfCurrentUser(null).size() == 0
-
- when: "a device registration is removed"
- adminNotificationResource.deleteDeviceToken(null, keycloakDemoSetup.testuser3Id, "device456")
- tokens = adminNotificationResource.getDeviceTokens(null, keycloakDemoSetup.testuser3Id)
-
- then: "only the other registration should be present"
- tokens.size() == 1
- tokens[0].id.deviceId == "device123"
- tokens[0].deviceType == "ANDROID"
- tokens[0].token == "token123"
-
- cleanup: "the server should be stopped"
- stopContainer(container)
- }
-}
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
new file mode 100644
index 000000000..32264dcef
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -0,0 +1,328 @@
+package org.openremote.test.notification
+
+import org.openremote.manager.notification.NotificationService
+import org.openremote.manager.notification.PushNotificationHandler
+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
+import org.openremote.manager.setup.SetupService
+import org.openremote.manager.setup.builtin.KeycloakDemoSetup
+import org.openremote.manager.setup.builtin.ManagerDemoSetup
+import org.openremote.model.attribute.AttributeRef
+import org.openremote.model.console.ConsoleProvider
+import org.openremote.model.console.ConsoleRegistration
+import org.openremote.model.console.ConsoleResource
+import org.openremote.model.notification.Notification
+import org.openremote.model.notification.NotificationResource
+import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.notification.PushNotificationMessage
+import org.openremote.model.value.ObjectValue
+import org.openremote.model.value.Values
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+
+import javax.ws.rs.WebApplicationException
+
+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.notification.PushNotificationAction.writeAttributeValueAction
+import static org.openremote.model.value.Values.parse
+
+class NotificationTest extends Specification implements ManagerContainerTrait {
+
+ def "Check push notification functionality"() {
+
+ def notificationIds = []
+ def notificationTargetTypes = []
+ def notificationTargetIds = []
+ def notificationMessages = []
+
+ given: "a mock push notification handler"
+ PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
+ isValid() >> true
+
+ // Assume sent to FCM
+ sendMessage(*_) >> {
+ id, targetType, targetId, message ->
+ notificationIds << id
+ notificationTargetTypes << targetType
+ notificationTargetIds << targetId
+ notificationMessages << message
+ return NotificationSendResult.success()
+ }
+ }
+
+ and: "the container environment is started with the mock handler"
+ def serverPort = findEphemeralPort()
+ def services = defaultServices()
+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)
+ def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)
+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
+ def notificationService = container.getService(NotificationService.class)
+
+ and: "an authenticated test user"
+ def realm = keycloakDemoSetup.customerATenant.realm
+ def testuser1AccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ "testuser1",
+ "testuser1"
+ ).token
+ def testuser2AccessToken = authenticate(
+ container,
+ realm,
+ KEYCLOAK_CLIENT_ID,
+ "testuser2",
+ "testuser2"
+ ).token
+ def testuser3AccessToken = authenticate(
+ container,
+ realm,
+ KEYCLOAK_CLIENT_ID,
+ "testuser3",
+ "testuser3"
+ ).token
+
+ and: "an authenticated superuser"
+ def adminAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ MASTER_REALM_ADMIN_USER,
+ getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)
+ ).token
+
+ def notification = new Notification("TestAction",
+ new PushNotificationMessage("Test Action",
+ "Click to cancel",
+ writeAttributeValueAction(
+ new AttributeRef(
+ managerDemoSetup.apartment1LivingroomId,
+ "alarmEnabled"
+ ),
+ Values.create(false)),null, null), null)
+
+ and: "the notification resource"
+ def testuser1NotificationResource = getClientTarget(serverUri(serverPort), MASTER_REALM, testuser1AccessToken).proxy(NotificationResource.class)
+ def testuser2NotificationResource = getClientTarget(serverUri(serverPort), realm, testuser2AccessToken).proxy(NotificationResource.class)
+ def testuser3NotificationResource = getClientTarget(serverUri(serverPort), realm, testuser3AccessToken).proxy(NotificationResource.class)
+ def adminNotificationResource = getClientTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(NotificationResource.class)
+ def anonymousNotificationResource = getClientTarget(serverUri(serverPort), keycloakDemoSetup.customerATenant.realm).proxy(NotificationResource.class)
+ def testuser1ConsoleResource = getClientTarget(serverUri(serverPort), MASTER_REALM, testuser1AccessToken).proxy(ConsoleResource.class)
+ def testuser2ConsoleResource = getClientTarget(serverUri(serverPort), realm, testuser2AccessToken).proxy(ConsoleResource.class)
+ def testuser3ConsoleResource = getClientTarget(serverUri(serverPort), realm, testuser3AccessToken).proxy(ConsoleResource.class)
+ def adminConsoleResource = getClientTarget(serverUri(serverPort), MASTER_REALM, adminAccessToken).proxy(ConsoleResource.class)
+ def anonymousConsoleResource = getClientTarget(serverUri(serverPort), realm).proxy(ConsoleResource.class)
+
+ when: "various consoles are registered"
+ def consoleRegistration = new ConsoleRegistration(null,
+ "Test Console",
+ "1.0",
+ "Android 7.0",
+ new HashMap<String, ConsoleProvider>() {
+ {
+ put("geofence", new ConsoleProvider(
+ ORConsoleGeofenceAssetAdapter.NAME,
+ true,
+ false,
+ false,
+ null
+ ))
+ put("push", new ConsoleProvider(
+ "fcm",
+ true,
+ true,
+ false,
+ (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)
+ ))
+ }
+ })
+ def testuser2Console = testuser2ConsoleResource.register(null, consoleRegistration)
+ def testuser3Console1 = testuser3ConsoleResource.register(null, consoleRegistration)
+ def testuser3Console2 = testuser3ConsoleResource.register(null, consoleRegistration)
+ def adminConsole = adminConsoleResource.register(null, consoleRegistration)
+ def anonymousConsole = anonymousConsoleResource.register(null, consoleRegistration)
+
+ then: "the consoles should have been created"
+ testuser2Console.id != null
+ testuser3Console1.id != null
+ testuser3Console2.id != null
+ adminConsole.id != null
+ anonymousConsole.id != null
+
+ when: "the admin user sends a push notification to an entire realm"
+ notification.targets = new Notification.Targets(Notification.TargetType.TENANT, keycloakDemoSetup.customerATenant.id)
+ adminNotificationResource.sendNotification(null, notification)
+
+ then: "all consoles in that realm should have been sent a notification"
+ assert notificationIds.size() == 4
+ assert notificationTargetTypes.count {t -> t == Notification.TargetType.ASSET} == 4
+ assert notificationTargetIds.contains(testuser2Console.id)
+ assert notificationTargetIds.contains(testuser3Console1.id)
+ assert notificationTargetIds.contains(testuser3Console2.id)
+ assert notificationTargetIds.contains(anonymousConsole.id)
+ assert notificationMessages.count {m -> m instanceof PushNotificationMessage && m.title == "Test Action" && m.body == "Click to cancel" && m.action != null} == 4
+
+ when: "a regular user sends a push notification to an entire realm"
+ testuser2NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ WebApplicationException ex = thrown()
+ ex.response.status == 403
+
+ when: "the admin user sends a notification to a user in a different realm"
+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)
+ adminNotificationResource.sendNotification(null, notification)
+
+ then: "the notification should have been sent"
+ notificationIds.size() == 5
+
+ when: "a regular user sends a push notification to a user in a different realm"
+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)
+ testuser1NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a restricted user sends a push notification to another user in the same realm"
+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)
+ testuser3NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "an anonymous user sends a push notification to a user"
+ anonymousNotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "the admin user sends a push notification to the console assets in customerA realm"
+ notification.targets = new Notification.Targets(Notification.TargetType.ASSET,
+ testuser2Console.id,
+ testuser3Console1.id,
+ testuser3Console2.id,
+ anonymousConsole.id)
+ adminNotificationResource.sendNotification(null, notification)
+
+ then: "the notification should have been sent"
+ notificationIds.size() == 9
+
+ when: "a regular user sends a push notification to the console assets in a different realm"
+ testuser1NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a regular user sends a push notification to the console assets in the same realm"
+ testuser2NotificationResource.sendNotification(null, notification)
+
+ then: "the notification should have been sent"
+ notificationIds.size() == 13
+
+ when: "a restricted user sends a push notification to the console assets in the same realm"
+ testuser3NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a restricted user sends a push notification to some consoles linked to them and some not linked to them"
+ notification.targets = new Notification.Targets(Notification.TargetType.ASSET,
+ testuser2Console.id,
+ testuser3Console1.id,
+ testuser3Console2.id,
+ anonymousConsole.id)
+ testuser3NotificationResource.sendNotification(null, notification)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ and: "no new notifications should have been sent"
+ notificationIds.size() == 13
+
+ when: "a restricted user sends a push notification to some consoles linked to them"
+ notification.targets = new Notification.Targets(Notification.TargetType.ASSET,
+ testuser3Console1.id,
+ testuser3Console2.id)
+ testuser3NotificationResource.sendNotification(null, notification)
+
+ then: "the notifications should have been sent"
+ notificationIds.size() == 15
+
+
+
+ // -----------------------------------------------
+ // Check notification resource
+ // -----------------------------------------------
+
+ when: "the admin user requests the notifications for customer A consoles"
+ def notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "all notifications sent to these consoles should be returned"
+ assert notifications.size() == 15
+ assert notifications.count {n ->
+ n.message.getString("title").orElse(null) == "Test Action" &&
+ n.message.getString("body").orElse(null) == "Click to cancel" &&
+ n.message.getObject("action").isPresent() &&
+ n.deliveredOn == null &&
+ n.acknowledgedOn == null
+ } == 15
+
+ when: "the admin user marks a customer A console notification as delivered and requests the notifications for customer A consoles"
+ adminNotificationResource.notificationDelivered(null, testuser2Console.id, notifications.find {n -> n.targetId == testuser2Console.id}.id)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "the notification should have been updated"
+ assert notifications.size() == 15
+ assert notifications.count {n -> n.deliveredOn != null} == 1
+
+ when: "the admin user marks a customer A console notification as delivered and requests the notifications for customer A consoles"
+ adminNotificationResource.notificationAcknowledged(null, testuser2Console.id, notifications.find {n -> n.targetId == testuser2Console.id && n.deliveredOn != null}.id, Values.create("dismissed"))
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "the notification should have been updated"
+ assert notifications.size() == 15
+ assert notifications.count {n -> n.deliveredOn != null && n.acknowledgedOn != null && n.acknowledgement == "dismissed"} == 1
+
+ when: "a regular user marks a console notification from another realm as delivered"
+ testuser1NotificationResource.notificationDelivered(null, testuser3Console1.id, notifications.find {n -> n.targetId == testuser3Console1.id}.id)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a regular user marks a console notification for their own console as delivered"
+ testuser3NotificationResource.notificationDelivered(null, testuser3Console1.id, notifications.find {n -> n.targetId == testuser3Console1.id}.id)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "the notification should have been updated"
+ assert notifications.size() == 15
+ assert notifications.count {n -> n.targetId == testuser3Console1.id && n.deliveredOn != null} == 1
+
+ when: "an anonymous user marks a console notification from another console as delivered"
+ anonymousNotificationResource.notificationDelivered(null, testuser3Console1.id, notifications.find {n -> n.targetId == testuser3Console1.id}.id)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "an anonymous user marks a console notification for their own console as delivered"
+ anonymousNotificationResource.notificationDelivered(null, anonymousConsole.id, notifications.find {n -> n.targetId == anonymousConsole.id}.id)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "the notification should have been updated"
+ assert notifications.size() == 15
+ assert notifications.count {n -> n.targetId == anonymousConsole.id && n.deliveredOn != null} == 1
+
+ cleanup: "the server should be stopped"
+ stopContainer(container)
+ }
+}