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 Turner7501bee15c8c
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
index 221bd27b9..6f0ee1c68 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationResourceImpl.java
@@ -65,7 +65,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
try {
return notificationService.getNotifications(types, timestamp, tenantIds, userIds, assetIds).toArray(new SentNotification[0]);
} catch (IllegalArgumentException e) {
- throw new WebApplicationException("Invalid criteria set", NOT_ACCEPTABLE);
+ throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);
}
}
@@ -74,7 +74,7 @@ public class NotificationResourceImpl extends WebResource implements Notificatio
try {
notificationService.removeNotifications(types, timestamp, tenantIds, userIds, assetIds);
} catch (IllegalArgumentException e) {
- throw new WebApplicationException("Invalid criteria set", NOT_ACCEPTABLE);
+ throw new WebApplicationException("Invalid criteria set", BAD_REQUEST);
}
}
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 205d70923..a2cd0450a 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -37,13 +37,16 @@ import org.openremote.model.Constants;
import org.openremote.model.asset.Asset;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
+import org.openremote.model.notification.RepeatFrequency;
import org.openremote.model.notification.SentNotification;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.TimeUtil;
import javax.persistence.Query;
import javax.persistence.TypedQuery;
+import java.time.ZoneId;
import java.time.ZonedDateTime;
+import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalField;
import java.time.temporal.WeekFields;
import java.util.*;
@@ -222,19 +225,16 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
// Filter targets based on repeat frequency
- Long timestamp = getRepeatAfterTimestamp(notification);
-
- if (timestamp != null) {
+ if (!TextUtil.isNullOrEmpty(notification.getName()) && (!TextUtil.isNullOrEmpty(notification.getRepeatInterval()) || notification.getRepeatFrequency() != null)) {
mappedTargetsList.forEach(
targets ->
targets.setIds(
Arrays.stream(targets.getIds()).filter(
- targetId -> !okToSendNotification(source,
- sourceId.get(),
- targets.getType(),
- targetId,
- notification.getName(),
- timestamp))
+ targetId -> okToSendNotification(source,
+ sourceId.get(),
+ targets.getType(),
+ targetId,
+ notification))
.toArray(String[]::new)
));
}
@@ -257,7 +257,9 @@ public class NotificationService extends RouteBuilder implements ContainerServic
.setSource(source)
.setSourceId(sourceId.get())
.setTarget(targets.getType())
- .setTargetId(targetId);
+ .setTargetId(targetId)
+ .setSentOn(Date.from(timerService.getNow().toInstant()));
+
sentNotification = em.merge(sentNotification);
long id = sentNotification.getId();
@@ -352,7 +354,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
public void removeNotification(Long id) {
persistenceService.doTransaction(entityManager -> entityManager
- .createQuery("delete SentNotification n where n.id = :id")
+ .createQuery("delete SentNotification where id = :id")
.setParameter("id", id)
.executeUpdate()
);
@@ -361,13 +363,12 @@ 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 SentNotification n where 1=1");
+ builder.append("delete from SentNotification n where 1=1");
List<Object> parameters = new ArrayList<>();
processCriteria(builder, parameters, types, timestamp, tenantIds, userIds, assetIds);
persistenceService.doTransaction(entityManager -> {
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+1, parameters.get(i)));
query.executeUpdate();
@@ -399,12 +400,8 @@ public class NotificationService extends RouteBuilder implements ContainerServic
throw new IllegalArgumentException("No criteria specified");
}
- if (counter > 1) {
- throw new IllegalArgumentException("Too many criteria specified");
- }
-
if (hasTypes) {
- builder.append(" AND n.target IN ?")
+ builder.append(" AND n.type IN ?")
.append(parameters.size() + 1);
parameters.add(types);
}
@@ -439,48 +436,42 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
if (timestamp != null) {
- builder.append(" n.sentOn <= ?")
+ builder.append(" AND n.sentOn <= ?")
.append(parameters.size() + 1);
- parameters.add(timestamp);
+ parameters.add(new Date(timestamp));
}
}
- protected Long getRepeatAfterTimestamp(Notification notification) {
- Long timestamp = null;
+ protected ZonedDateTime getRepeatAfterTimestamp(Notification notification, ZonedDateTime lastSend) {
+ ZonedDateTime timestamp = null;
if (TextUtil.isNullOrEmpty(notification.getName())) {
return null;
}
if (notification.getRepeatFrequency() != null) {
- ZonedDateTime dateTime = timerService.getNow()
- .withMinute(0)
- .withHour(0)
- .withSecond(0);
switch (notification.getRepeatFrequency()) {
- case ALWAYS:
- break;
- case ONCE:
- timestamp = 0L;
+ case HOURLY:
+ timestamp = lastSend.truncatedTo(ChronoUnit.HOURS).plusHours(1);
break;
case DAILY:
- timestamp = dateTime.toInstant().toEpochMilli();
+ timestamp = lastSend.truncatedTo(ChronoUnit.DAYS).plusDays(1);
break;
case WEEKLY:
- timestamp = dateTime.with(WEEK_FIELD_ISO, 1).toInstant().toEpochMilli();
+ timestamp = lastSend.truncatedTo(ChronoUnit.WEEKS).plusWeeks(1);
break;
case MONTHLY:
- timestamp = dateTime.withDayOfMonth(1).toInstant().toEpochMilli();
+ timestamp = lastSend.truncatedTo(ChronoUnit.MONTHS).plusMonths(1);
break;
case ANNUALLY:
- timestamp = dateTime.withDayOfYear(1).toInstant().toEpochMilli();
+ timestamp = lastSend.truncatedTo(ChronoUnit.YEARS).plusYears(1);
break;
}
} else if (!TextUtil.isNullOrEmpty(notification.getRepeatInterval())) {
- timestamp = timerService.getCurrentTimeMillis() - TimeUtil.parseTimeString(notification.getRepeatInterval());
+ timestamp = lastSend.plus(TimeUtil.parseTimeString(notification.getRepeatInterval()), ChronoUnit.MILLIS);
}
return timestamp;
@@ -538,16 +529,26 @@ 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 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)
+ protected boolean okToSendNotification(Notification.Source source, String sourceId, Notification.TargetType target, String targetId, Notification notification) {
+
+ if (notification.getRepeatFrequency() == RepeatFrequency.ALWAYS) {
+ return true;
+ }
+
+ Date lastSend = persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(
+ "SELECT n.sentOn FROM SentNotification n WHERE n.source =:source AND n.sourceId =:sourceId AND n.target =:target AND n.targetId =:targetId AND n.name =:name ORDER BY n.sentOn DESC", Date.class)
.setParameter("source", source)
.setParameter("sourceId", sourceId)
.setParameter("target", target)
.setParameter("targetId", targetId)
- .setParameter("name", name)
- .setParameter("timestamp", timestamp)
- .getSingleResult() == 0L);
+ .setParameter("name", notification.getName())
+ .setMaxResults(1)
+ .getResultList()).stream().findFirst().orElse(null);
+
+ return lastSend == null ||
+ (notification.getRepeatFrequency() != RepeatFrequency.ONCE &&
+ timerService.getNow().plusSeconds(1).isAfter(getRepeatAfterTimestamp(notification, ZonedDateTime.ofInstant(lastSend.toInstant(),
+ ZoneId.systemDefault()))));
}
protected static Processor handleNotificationProcessingException(Logger logger) {
diff --git a/model/src/main/java/org/openremote/model/notification/Notification.java b/model/src/main/java/org/openremote/model/notification/Notification.java
index b2fa631d9..bef54a80d 100644
--- a/model/src/main/java/org/openremote/model/notification/Notification.java
+++ b/model/src/main/java/org/openremote/model/notification/Notification.java
@@ -124,7 +124,12 @@ public class Notification {
return repeatFrequency;
}
+ /**
+ * This applies a fixed time window to a notification i.e. {@link RepeatFrequency#HOURLY} would mean that a
+ * notification sent at 10:59 can then be resent at 11:00.
+ */
public Notification setRepeatFrequency(RepeatFrequency repeatFrequency) {
+ this.repeatInterval = null;
this.repeatFrequency = repeatFrequency;
return this;
}
@@ -133,7 +138,12 @@ public class Notification {
return repeatInterval;
}
+ /**
+ * This applies a sliding time window to a notification i.e. a value of 1h would mean has it been at least 1hr
+ * since the notification was last sent.
+ */
public Notification setRepeatInterval(String repeatInterval) {
+ this.repeatFrequency = null;
this.repeatInterval = repeatInterval;
return this;
}
diff --git a/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java b/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
index 996337514..dc4b2b359 100644
--- a/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
+++ b/model/src/main/java/org/openremote/model/notification/RepeatFrequency.java
@@ -22,6 +22,7 @@ package org.openremote.model.notification;
public enum RepeatFrequency {
ALWAYS,
ONCE,
+ HOURLY,
DAILY,
WEEKLY,
MONTHLY,
diff --git a/model/src/main/java/org/openremote/model/notification/SentNotification.java b/model/src/main/java/org/openremote/model/notification/SentNotification.java
index bad7b93d7..1dda2fe46 100644
--- a/model/src/main/java/org/openremote/model/notification/SentNotification.java
+++ b/model/src/main/java/org/openremote/model/notification/SentNotification.java
@@ -72,7 +72,6 @@ public class SentNotification {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "SENT_ON", updatable = false, nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
- @org.hibernate.annotations.CreationTimestamp
protected Date sentOn;
@Temporal(TemporalType.TIMESTAMP)
diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
index 32264dcef..58965b473 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -14,12 +14,20 @@ 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.notification.RepeatFrequency
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 java.time.Instant
+import java.time.LocalDateTime
+import java.time.Period
+import java.time.ZoneId
+import java.time.ZonedDateTime
+import java.time.temporal.ChronoUnit
+import java.util.concurrent.TimeUnit
import static org.openremote.container.util.MapAccess.getString
import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASSWORD
@@ -174,6 +182,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
when: "the admin user sends a notification to a user in a different realm"
notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)
+ advancePseudoClock(1, TimeUnit.HOURS, container)
adminNotificationResource.sendNotification(null, notification)
then: "the notification should have been sent"
@@ -208,6 +217,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
testuser3Console1.id,
testuser3Console2.id,
anonymousConsole.id)
+ advancePseudoClock(1, TimeUnit.HOURS, container)
adminNotificationResource.sendNotification(null, notification)
then: "the notification should have been sent"
@@ -221,6 +231,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
ex.response.status == 403
when: "a regular user sends a push notification to the console assets in the same realm"
+ advancePseudoClock(1, TimeUnit.HOURS, container)
testuser2NotificationResource.sendNotification(null, notification)
then: "the notification should have been sent"
@@ -249,6 +260,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
notificationIds.size() == 13
when: "a restricted user sends a push notification to some consoles linked to them"
+ advancePseudoClock(1, TimeUnit.HOURS, container)
notification.targets = new Notification.Targets(Notification.TargetType.ASSET,
testuser3Console1.id,
testuser3Console2.id)
@@ -257,8 +269,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "the notifications should have been sent"
notificationIds.size() == 15
-
-
// -----------------------------------------------
// Check notification resource
// -----------------------------------------------
@@ -322,6 +332,115 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
assert notifications.size() == 15
assert notifications.count {n -> n.targetId == anonymousConsole.id && n.deliveredOn != null} == 1
+ when: "a regular user tries to remove notifications"
+ testuser1NotificationResource.removeNotifications(null, [PushNotificationMessage.TYPE], null, [MASTER_REALM], null, null)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "a restricted user tries to remove notifications"
+ testuser3NotificationResource.removeNotifications(null, [PushNotificationMessage.TYPE], null, [realm], null, null)
+
+ then: "access should be forbidden"
+ ex = thrown()
+ ex.response.status == 403
+
+ when: "the admin user removes notifications by timestamp and the notifications are retrieved again"
+ notifications = notifications.sort {n -> n.sentOn}
+ adminNotificationResource.removeNotifications(null, [PushNotificationMessage.TYPE], notifications[0].sentOn.getTime(), null, null, null)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "notifications sent before or at that time should have been removed"
+ assert notifications.size() == 11
+
+ when: "the admin user removes notifications sent to specific console assets without other constraints and the notifications are retrieved again"
+ adminNotificationResource.removeNotifications(null, null, null, null, null, [testuser3Console1.id, testuser3Console2.id])
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "all notifications sent to those consoles should have been removed"
+ assert notifications.size() == 5
+ assert notifications.count {n -> n.targetId == testuser3Console1.id || n.targetId == testuser3Console2.id} == 0
+
+ when: "the admin user removes notifications by type and the notifications are retrieved again"
+ adminNotificationResource.removeNotifications(null, [PushNotificationMessage.TYPE], null, null, null, null)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "one notification should have been removed"
+ assert notifications.size() == 0
+
+ when: "the admin user removes notifications without sufficient constraints"
+ adminNotificationResource.removeNotifications(null, null, null, null, null, null)
+
+ then: "request should not be allowed"
+ ex = thrown()
+ ex.response.status == 400
+
+ // -----------------------------------------------
+ // Check notification repeat frequency
+ // -----------------------------------------------
+
+ when: "a repeat frequency is set and a notification is sent"
+ // Move clock to beginning of next hour
+ def advancement = Instant.ofEpochMilli(getClockTimeOf(container)).atZone(ZoneId.systemDefault())
+ .truncatedTo(ChronoUnit.HOURS)
+ .plusMinutes(59)
+
+ advancePseudoClock(ChronoUnit.MILLIS.between(Instant.ofEpochMilli(getClockTimeOf(container)).atZone(ZoneId.systemDefault()), advancement), TimeUnit.MILLISECONDS, container)
+ notification.setRepeatFrequency(RepeatFrequency.HOURLY)
+ testuser3NotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "the notifications should have been sent"
+ assert notifications.size() == 2
+
+ when: "a repeat frequency is set and a notification with the same name and scope as a previous notification is sent within the repeat window"
+ testuser3NotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "no new notifications should have been sent"
+ assert notifications.size() == 2
+
+ when: "a repeat frequency is set and a notification with the same name but different scope is sent within the repeat window"
+ adminNotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "new notifications should have been sent"
+ assert notifications.size() == 4
+
+ when: "time advances less than the repeat frequency and the notification is sent again"
+ advancePseudoClock(30, TimeUnit.SECONDS, container)
+ adminNotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "no new notifications should have been sent"
+ assert notifications.size() == 4
+
+ when: "time advances more than the repeat frequency and the notification is sent again"
+ advancePseudoClock(2, TimeUnit.MINUTES, container)
+ adminNotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "new notifications should have been sent"
+ assert notifications.size() == 6
+
+ when: "a repeat interval is used and a notification with the same name and scope is sent within the repeat window"
+ notification.setRepeatInterval("1mn")
+ advancePseudoClock(10, TimeUnit.DAYS, container)
+ adminNotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "no new notifications should have been sent"
+ assert notifications.size() == 6
+
+ when: "time advances more than the repeat interval and the notification is sent again"
+ advancePseudoClock(30, TimeUnit.DAYS, container)
+ adminNotificationResource.sendNotification(null, notification)
+ notifications = adminNotificationResource.getNotifications(null, null, null, null, null, [testuser2Console.id, testuser3Console1.id, testuser3Console2.id, anonymousConsole.id])
+
+ then: "new notifications should have been sent"
+ assert notifications.size() == 8
+
cleanup: "the server should be stopped"
stopContainer(container)
}