Skip to content

armgit / core

Public Imported from GitHub
0

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

Improved push notification target filtering and made NotificationFacade async (#1102)

Rich Turner9a95ad4cc1d2
diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
index 26262f56a..ec2cecc8f 100644
--- a/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
+++ b/manager/src/main/java/org/openremote/manager/asset/AssetStorageService.java
@@ -880,13 +880,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return false;
});
- //noinspection ConstantConditions
if (gatewayIdAssetIdMap.isEmpty() && ids.isEmpty()) {
return true;
}
// This is not atomic across gateways
- //noinspection ConstantConditions
if (!gatewayIdAssetIdMap.isEmpty()) {
for (Map.Entry<String, List<String>> gatewayIdAssetIds : gatewayIdAssetIdMap.entrySet()) {
String gatewayId = gatewayIdAssetIds.getKey();
@@ -1416,23 +1414,21 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected void publishModificationEvents(PersistenceEvent<Asset<?>> persistenceEvent) {
Asset<?> asset = persistenceEvent.getEntity();
switch (persistenceEvent.getCause()) {
- case CREATE:
+ case CREATE -> {
// Fully load the asset
Asset<?> loadedAsset = find(new AssetQuery().ids(asset.getId()));
-
if (loadedAsset == null) {
return;
}
-
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Asset created: " + loadedAsset.toStringAll());
} else {
LOG.fine("Asset created: " + loadedAsset);
}
-
clientEventService.publishEvent(
new AssetEvent(AssetEvent.Cause.CREATE, loadedAsset, null)
);
+ }
// // Raise attribute event for each attribute
// asset.getAttributes().forEach(newAttribute ->
@@ -1443,9 +1439,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// newAttribute.getTimestamp().orElse(timerService.getCurrentTimeMillis()))
// .setParentId(asset.getParentId()).setRealm(asset.getRealm())
// ));
- break;
- case UPDATE:
-
+ case UPDATE -> {
boolean attributesChanged = persistenceEvent.hasPropertyChanged("attributes");
// String[] updatedProperties = Arrays.stream(persistenceEvent.getPropertyNames()).filter(propertyName -> {
@@ -1455,14 +1449,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// }).toArray(String[]::new);
// Fully load the asset
- loadedAsset = find(new AssetQuery().ids(asset.getId()));
-
+ Asset<?> loadedAsset = find(new AssetQuery().ids(asset.getId()));
if (loadedAsset == null) {
return;
}
-
LOG.finest("Asset updated: " + persistenceEvent);
-
clientEventService.publishEvent(
new AssetEvent(AssetEvent.Cause.UPDATE, loadedAsset, persistenceEvent.getPropertyNames().toArray(String[]::new))
);
@@ -1490,15 +1481,13 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
publishAttributeEvent(asset, newOrModifiedAttribute)
);
}
- break;
- case DELETE:
-
+ }
+ case DELETE -> {
if (LOG.isLoggable(Level.FINEST)) {
LOG.finest("Asset deleted: " + asset.toStringAll());
} else {
LOG.fine("Asset deleted: " + asset);
}
-
clientEventService.publishEvent(
new AssetEvent(AssetEvent.Cause.DELETE, asset, null)
);
@@ -1509,7 +1498,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
clientEventService.publishEvent(
AttributeEvent.deletedAttribute(asset.getId(), obsoleteAttribute.getName())
));
- break;
+ }
}
}
@@ -1645,21 +1634,11 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(" order by ");
switch (query.orderBy.property) {
- case CREATED_ON:
- sb.append(" A.CREATED_ON ");
- break;
- case ASSET_TYPE:
- sb.append(" A.TYPE ");
- break;
- case NAME:
- sb.append(" A.NAME ");
- break;
- case PARENT_ID:
- sb.append(" A.PARENT_ID ");
- break;
- case REALM:
- sb.append(" A.REALM ");
- break;
+ case CREATED_ON -> sb.append(" A.CREATED_ON ");
+ case ASSET_TYPE -> sb.append(" A.TYPE ");
+ case NAME -> sb.append(" A.NAME ");
+ case PARENT_ID -> sb.append(" A.PARENT_ID ");
+ case REALM -> sb.append(" A.REALM ");
}
sb.append(query.orderBy.descending ? "desc " : "asc ");
}
@@ -1674,7 +1653,6 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
return "";
}
- @SuppressWarnings("unchecked")
protected static boolean appendWhereClause(StringBuilder sb, AssetQuery query, int level, List<ParameterBinder> binders, Supplier<Long> timeProvider) {
// level = 1 is main query
// level = 2 is union
@@ -1864,8 +1842,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
sb.append(buildNameValuePredicateFilter(nameValuePredicate, jsonObjName, binders, timeProvider));
- if (nameValuePredicate instanceof AttributePredicate) {
- AttributePredicate attributePredicate = (AttributePredicate)nameValuePredicate;
+ if (nameValuePredicate instanceof AttributePredicate attributePredicate) {
if (attributePredicate.meta != null && attributePredicate.meta.length > 0) {
String metaJsonObjName = jsonObjName + "_AM" + metaIndex++;
@@ -1919,46 +1896,52 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
// Inserts the SQL string and adds the parameters
BiConsumer<StringBuilder, List<ParameterBinder>> valuePathInserter;
boolean isAttributePredicate = nameValuePredicate instanceof AttributePredicate;
+ boolean isTextCompare = (nameValuePredicate.value instanceof ValueEmptyPredicate) || (nameValuePredicate.value instanceof StringPredicate);
+ final String operator = isTextCompare ? "#>>" : "#>";
if (nameValuePredicate.path == null || nameValuePredicate.path.getPaths().length == 0) {
- valuePathInserter = (sb, b) ->
- sb.append(isAttributePredicate ? "(" + jsonObjName + ".VALUE #> '{value}')" : jsonObjName + ".VALUE");
+ valuePathInserter = (sb, b) -> {
+ if (isAttributePredicate) {
+ sb.append("(").append(jsonObjName).append(".VALUE ").append(operator).append(" '{value}')");
+ } else {
+ sb.append(jsonObjName).append(".VALUE");
+ if (isTextCompare) {
+ sb.append(" #>> '{}'");
+ }
+ }
+ };
} else {
List<String> paths = new ArrayList<>();
if (isAttributePredicate) {
paths.add("value");
}
- paths.addAll(Arrays.stream(nameValuePredicate.path.getPaths()).map(Object::toString).collect(Collectors.toList()));
+ paths.addAll(Arrays.stream(nameValuePredicate.path.getPaths()).map(Object::toString).toList());
valuePathInserter = (sb, b) -> {
final int pos = binders.size() + 1;
- sb.append("(").append(jsonObjName).append(".VALUE #> ?").append(pos).append(")");
+ sb.append("(").append(jsonObjName).append(".VALUE ").append(operator).append(" ?").append(pos).append(")");
binders.add((em, st) -> st.setParameter(pos, paths.toArray(new String[0]), StringArrayType.INSTANCE));
};
}
- if (nameValuePredicate.value instanceof StringPredicate) {
- StringPredicate stringPredicate = (StringPredicate) nameValuePredicate.value;
+ if (nameValuePredicate.value instanceof StringPredicate stringPredicate) {
if (!stringPredicate.caseSensitive) {
attributeBuilder.append("upper(");
}
valuePathInserter.accept(attributeBuilder, binders);
- attributeBuilder.append(" #>> '{}'");
if (!stringPredicate.caseSensitive) {
attributeBuilder.append(")");
}
final int pos = binders.size() + 1;
attributeBuilder.append(StringPredicate.toSQLParameter(stringPredicate, pos, false));
binders.add((em, st) -> st.setParameter(pos, stringPredicate.prepareValue()));
- } else if (nameValuePredicate.value instanceof BooleanPredicate) {
- BooleanPredicate booleanPredicate = (BooleanPredicate) nameValuePredicate.value;
+ } else if (nameValuePredicate.value instanceof BooleanPredicate booleanPredicate) {
valuePathInserter.accept(attributeBuilder, binders);
attributeBuilder
.append(" = to_jsonb(")
.append(booleanPredicate.value)
.append(")");
- } else if (nameValuePredicate.value instanceof DateTimePredicate) {
- DateTimePredicate dateTimePredicate = (DateTimePredicate) nameValuePredicate.value;
+ } else if (nameValuePredicate.value instanceof DateTimePredicate dateTimePredicate) {
attributeBuilder.append("(");
valuePathInserter.accept(attributeBuilder, binders);
attributeBuilder
@@ -1974,8 +1957,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
final int pos2 = binders.size() + 1;
binders.add((em, st) -> st.setParameter(pos2, new java.sql.Timestamp(fromAndTo.value != null ? fromAndTo.value : Long.MAX_VALUE)));
}
- } else if (nameValuePredicate.value instanceof NumberPredicate) {
- NumberPredicate numberPredicate = (NumberPredicate) nameValuePredicate.value;
+ } else if (nameValuePredicate.value instanceof NumberPredicate numberPredicate) {
attributeBuilder.append("(");
valuePathInserter.accept(attributeBuilder, binders);
attributeBuilder
@@ -1987,8 +1969,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
final int pos2 = binders.size() + 1;
binders.add((em, st) -> st.setParameter(pos2, numberPredicate.rangeValue));
}
- } else if (nameValuePredicate.value instanceof ArrayPredicate) {
- ArrayPredicate arrayPredicate = (ArrayPredicate) nameValuePredicate.value;
+ } else if (nameValuePredicate.value instanceof ArrayPredicate arrayPredicate) {
if (arrayPredicate.negated) {
attributeBuilder.append("NOT(");
}
@@ -2032,8 +2013,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
attributeBuilder.append(")");
}
} else if (nameValuePredicate.value instanceof GeofencePredicate) {
- if (nameValuePredicate.value instanceof RadialGeofencePredicate) {
- RadialGeofencePredicate location = (RadialGeofencePredicate) nameValuePredicate.value;
+ if (nameValuePredicate.value instanceof RadialGeofencePredicate location) {
attributeBuilder.append("ST_DistanceSphere(ST_MakePoint((");
valuePathInserter.accept(attributeBuilder, binders);
attributeBuilder
@@ -2048,8 +2028,7 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
.append(location.lat)
.append(location.negated ? ")) > " : ")) <= ")
.append(location.radius);
- } else if (nameValuePredicate.value instanceof RectangularGeofencePredicate) {
- RectangularGeofencePredicate location = (RectangularGeofencePredicate) nameValuePredicate.value;
+ } else if (nameValuePredicate.value instanceof RectangularGeofencePredicate location) {
if (location.negated) {
attributeBuilder.append("NOT");
}
@@ -2073,8 +2052,9 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
.append("))");
}
} else if (nameValuePredicate.value instanceof ValueEmptyPredicate) {
+ // Two situations - key is present and not null (cannot use IS NULL for this) or key is not present at all (have to use IS NULL for this)
valuePathInserter.accept(attributeBuilder, binders);
- attributeBuilder.append(((ValueEmptyPredicate) nameValuePredicate.value).negate ? "\\:\\:text IS NOT NULL" : "\\:\\:text IS NULL");
+ attributeBuilder.append(((ValueEmptyPredicate) nameValuePredicate.value).negate ? " IS NOT NULL" : " IS NULL");
} else if (nameValuePredicate.value instanceof CalendarEventPredicate) {
final int pos = binders.size() + 1;
java.sql.Timestamp when = new java.sql.Timestamp(((CalendarEventPredicate)nameValuePredicate.value).timestamp.getTime());
@@ -2118,36 +2098,42 @@ public class AssetStorageService extends RouteBuilder implements ContainerServic
protected static String buildOperatorFilter(AssetQuery.Operator operator, boolean negate, int pos) {
switch (operator) {
- case EQUALS:
+ case EQUALS -> {
if (negate) {
return " <> ?" + pos + " ";
}
return " = ?" + pos + " ";
- case GREATER_THAN:
+ }
+ case GREATER_THAN -> {
if (negate) {
return " <= ?" + pos + " ";
}
return " > ?" + pos + " ";
- case GREATER_EQUALS:
+ }
+ case GREATER_EQUALS -> {
if (negate) {
return " < ?" + pos + " ";
}
return " >= ?" + pos + " ";
- case LESS_THAN:
+ }
+ case LESS_THAN -> {
if (negate) {
return " >= ?" + pos + " ";
}
return " < ?" + pos + " ";
- case LESS_EQUALS:
+ }
+ case LESS_EQUALS -> {
if (negate) {
return " > ?" + pos + " ";
}
return " <= ?" + pos + " ";
- case BETWEEN:
+ }
+ case BETWEEN -> {
if (negate) {
- return " NOT BETWEEN ?" + pos + " AND ?" + (pos+1) + " ";
+ return " NOT BETWEEN ?" + pos + " AND ?" + (pos + 1) + " ";
}
- return " BETWEEN ?" + pos + " AND ?" + (pos+1) + " ";
+ return " BETWEEN ?" + pos + " AND ?" + (pos + 1) + " ";
+ }
}
throw new IllegalArgumentException("Unsupported operator: " + operator);
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 2fc114920..b5afe5342 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -61,7 +61,6 @@ import static org.openremote.manager.notification.NotificationProcessingExceptio
import static org.openremote.model.notification.Notification.HEADER_SOURCE;
import static org.openremote.model.notification.Notification.Source.*;
-// TODO Implement notification purging - configurable MAX_AGE for notifications?
public class NotificationService extends RouteBuilder implements ContainerService {
public static final String NOTIFICATION_QUEUE = "seda://NotificationQueue?waitForTaskToComplete=IfReplyExpected&timeout=10000&purgeWhenStopping=true&discardIfNoConsumers=false&size=25000";
@@ -73,7 +72,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
protected MessageBrokerService messageBrokerService;
protected Map<String, NotificationHandler> notificationHandlerMap = new HashMap<>();
- protected static Processor handleNotificationProcessingException(Logger logger) {
+ protected static Processor handleNotificationProcessingException() {
return exchange -> {
Notification notification = exchange.getIn().getBody(Notification.class);
Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
@@ -91,14 +90,13 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
// TODO Better exception handling - dead letter queue?
- if (exception instanceof NotificationProcessingException) {
- NotificationProcessingException processingException = (NotificationProcessingException) exception;
+ if (exception instanceof NotificationProcessingException processingException) {
error.append(" - ").append(processingException.getReasonPhrase());
error.append(": ").append(notification.toString());
- logger.warning(error.toString());
+ NotificationService.LOG.warning(error.toString());
} else {
error.append(": ").append(notification.toString());
- logger.log(Level.WARNING, error.toString(), exception);
+ NotificationService.LOG.log(Level.WARNING, error.toString(), exception);
}
exchange.getMessage().setBody(false);
@@ -186,40 +184,30 @@ public class NotificationService extends RouteBuilder implements ContainerServic
boolean isRestrictedUser = false;
switch (source) {
- case INTERNAL:
- isSuperUser = true;
- break;
-
- case CLIENT:
-
+ case INTERNAL -> isSuperUser = true;
+ case CLIENT -> {
AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);
if (authContext == null) {
// Anonymous clients cannot send notifications
throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
}
-
realm = authContext.getAuthenticatedRealmName();
userId = authContext.getUserId();
sourceId.set(userId);
isSuperUser = authContext.isSuperUser();
isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext);
- break;
-
- case GLOBAL_RULESET:
- isSuperUser = true;
- break;
-
- case REALM_RULESET:
+ }
+ case GLOBAL_RULESET -> isSuperUser = true;
+ case REALM_RULESET -> {
realm = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);
sourceId.set(realm);
- break;
-
- case ASSET_RULESET:
+ }
+ case ASSET_RULESET -> {
assetId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);
sourceId.set(assetId);
Asset<?> asset = assetStorageService.find(assetId, false);
realm = asset.getRealm();
- break;
+ }
}
LOG.fine("Sending " + notification.getMessage().getType() + " notification '" + notification.getName() + "': '" + source + ":" + sourceId.get() + "' -> " + notification.getTargets());
@@ -298,13 +286,20 @@ public class NotificationService extends RouteBuilder implements ContainerServic
})
.endDoTry()
.doCatch(NotificationProcessingException.class)
- .process(handleNotificationProcessingException(LOG));
+ .process(handleNotificationProcessingException());
}
public boolean sendNotification(Notification notification) {
return sendNotification(notification, INTERNAL, "");
}
+ public void sendNotificationAsync(Notification notification, Notification.Source source, String sourceId) {
+ Map<String, Object> headers = new HashMap<>();
+ headers.put(Notification.HEADER_SOURCE, source);
+ headers.put(Notification.HEADER_SOURCE_ID, sourceId);
+ messageBrokerService.getFluentProducerTemplate().withBody(notification).withHeaders(headers).to(NotificationService.NOTIFICATION_QUEUE).send();
+ }
+
public boolean sendNotification(Notification notification, Notification.Source source, String sourceId) {
Map<String, Object> headers = new HashMap<>();
headers.put(Notification.HEADER_SOURCE, source);
@@ -475,22 +470,11 @@ public class NotificationService extends RouteBuilder implements ContainerServic
if (notification.getRepeatFrequency() != null) {
switch (notification.getRepeatFrequency()) {
-
- case HOURLY:
- timestamp = lastSend.truncatedTo(HOURS).plus(1, HOURS);
- break;
- case DAILY:
- timestamp = lastSend.truncatedTo(DAYS).plus(1, DAYS);
- break;
- case WEEKLY:
- timestamp = lastSend.truncatedTo(WEEKS).plus(1, WEEKS);
- break;
- case MONTHLY:
- timestamp = lastSend.truncatedTo(MONTHS).plus(1, MONTHS);
- break;
- case ANNUALLY:
- timestamp = lastSend.truncatedTo(YEARS).plus(1, YEARS);
- break;
+ case HOURLY -> timestamp = lastSend.truncatedTo(HOURS).plus(1, HOURS);
+ case DAILY -> timestamp = lastSend.truncatedTo(DAYS).plus(1, DAYS);
+ case WEEKLY -> timestamp = lastSend.truncatedTo(WEEKS).plus(1, WEEKS);
+ case MONTHLY -> timestamp = lastSend.truncatedTo(MONTHS).plus(1, MONTHS);
+ case ANNUALLY -> timestamp = lastSend.truncatedTo(YEARS).plus(1, YEARS);
}
} else if (!TextUtil.isNullOrEmpty(notification.getRepeatInterval())) {
timestamp = lastSend.plus(TimeUtil.parseTimeDuration(notification.getRepeatInterval()), ChronoUnit.MILLIS);
@@ -499,7 +483,6 @@ public class NotificationService extends RouteBuilder implements ContainerServic
return timestamp;
}
- @SuppressWarnings("unchecked")
protected void checkAccess(Notification.Source source, String sourceId, List<Notification.Target> targets, String realm, String userId, boolean isSuperUser, boolean isRestrictedUser, String assetId) throws NotificationProcessingException {
if (isSuperUser) {
diff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
index f81384986..664ca455d 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -43,10 +43,7 @@ import org.openremote.model.notification.NotificationSendResult;
import org.openremote.model.notification.PushNotificationMessage;
import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.UserQuery;
-import org.openremote.model.query.filter.AttributePredicate;
-import org.openremote.model.query.filter.NameValuePredicate;
-import org.openremote.model.query.filter.RealmPredicate;
-import org.openremote.model.query.filter.StringPredicate;
+import org.openremote.model.query.filter.*;
import org.openremote.model.security.User;
import org.openremote.model.util.TextUtil;
import org.openremote.model.util.ValueUtil;
@@ -135,7 +132,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
.select(new AssetQuery.Select().attributes(ConsoleAsset.CONSOLE_PROVIDERS.getName()))
.types(ConsoleAsset.class)
.attributes(
- new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE))
+ new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, new ValueEmptyPredicate().negate(true), false, new NameValuePredicate.Path(PushNotificationMessage.TYPE, "data", "token"))
))
.stream()
.map(asset -> (ConsoleAsset) asset)
@@ -171,12 +168,11 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
@Override
public boolean isMessageValid(AbstractNotificationMessage message) {
- if (!(message instanceof PushNotificationMessage)) {
+ if (!(message instanceof PushNotificationMessage pushMessage)) {
LOG.warning("Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of PushNotificationMessage");
return false;
}
- PushNotificationMessage pushMessage = (PushNotificationMessage) message;
if (TextUtil.isNullOrEmpty(pushMessage.getTitle()) && pushMessage.getData() == null) {
LOG.warning("Invalid message: must either contain a title and/or data");
return false;
@@ -213,6 +209,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
.filter(target -> {
boolean isConsoleAsset = consoleAssets.contains(target.getId());
if (isConsoleAsset) {
+ // Don't filter out consoles without FCM here so we can record the failure in the actual send
mappedTargets.add(new Notification.Target(Notification.TargetType.ASSET, target.getId()));
}
return !isConsoleAsset;
@@ -227,7 +224,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
AssetQuery assetQuery = new AssetQuery()
.select(new AssetQuery.Select().excludeAttributes())
.types(ConsoleAsset.class)
- .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, null, false, new NameValuePredicate.Path(PushNotificationMessage.TYPE)));
+ .attributes(new AttributePredicate(ConsoleAsset.CONSOLE_PROVIDERS, new ValueEmptyPredicate().negate(true), false, new NameValuePredicate.Path(PushNotificationMessage.TYPE, "data", "token")));
switch (targetType) {
case REALM ->
@@ -242,6 +239,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
assetStorageService.findUserAssetLinks(null, null, targetId)
.stream()
.map(ual -> ual.getId().getUserId())
+ .collect(Collectors.toSet())
.toArray(String[]::new));
}
@@ -316,7 +314,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
String fcmToken = consoleFCMTokenMap.get(targetId);
if (TextUtil.isNullOrEmpty(fcmToken)) {
- LOG.warning("No FCM token found for console: " + targetId);
+ LOG.finer("No FCM token found for console: " + targetId);
return NotificationSendResult.failure("No FCM token found for console: " + targetId);
}
@@ -397,15 +395,9 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
boolean dataOnly = TextUtil.isNullOrEmpty(pushMessage.getTitle());
switch (pushMessage.getTargetType()) {
- case DEVICE:
- builder.setToken(pushMessage.getTarget());
- break;
- case TOPIC:
- builder.setTopic(pushMessage.getTarget());
- break;
- case CONDITION:
- builder.setCondition(pushMessage.getTarget());
- break;
+ case DEVICE -> builder.setToken(pushMessage.getTarget());
+ case TOPIC -> builder.setTopic(pushMessage.getTarget());
+ case CONDITION -> builder.setCondition(pushMessage.getTarget());
}
AndroidConfig.Builder androidConfigBuilder = AndroidConfig.builder();
@@ -491,7 +483,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
return asset.getConsoleProviders().flatMap(consoleProviders ->
Optional.ofNullable(consoleProviders.get(PushNotificationMessage.TYPE))
.map(ConsoleProvider::getData)
- .map(data -> data.get("token") != null ? data.get("token").asText() : null));
+ .map(data -> data.get("token") != null && !data.get("token").isNull() && !data.get("token").asText().isEmpty() ? data.get("token").asText() : null));
}
protected void processConsoleAssetChange(ConsoleAsset asset, PersistenceEvent<ConsoleAsset> persistenceEvent) {
@@ -501,11 +493,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
}
switch (persistenceEvent.getCause()) {
-
- case CREATE:
- case UPDATE:
- getFcmToken(asset).ifPresent(token -> consoleFCMTokenMap.put(asset.getId(), token));
- break;
+ case CREATE, UPDATE -> getFcmToken(asset).ifPresent(token -> consoleFCMTokenMap.put(asset.getId(), token));
}
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java b/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java
index 096d2c777..3e633c649 100644
--- a/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java
+++ b/manager/src/main/java/org/openremote/manager/rules/facade/NotificationsFacade.java
@@ -41,7 +41,6 @@ public class NotificationsFacade<T extends Ruleset> extends Notifications {
this.notificationService = notificationService;
}
- // TODO: Priority NotificationService.sendNotification can throw ExchangeTimedOutException: The OUT message was not received within: 10000 millis
public void send(Notification notification) {
Notification.Source source;
String sourceId = null;
@@ -56,6 +55,6 @@ public class NotificationsFacade<T extends Ruleset> extends Notifications {
sourceId = rulesEngineId.getAssetId().orElseThrow(() -> new IllegalStateException("Asset ruleset must have an asset ID"));
}
- notificationService.sendNotification(notification, source, sourceId);
+ notificationService.sendNotificationAsync(notification, source, sourceId);
}
}
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 00bb736a7..efa9e3ccb 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -1,5 +1,6 @@
package org.openremote.test.notification
+import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.fasterxml.jackson.databind.node.TextNode
import jakarta.mail.Message
@@ -15,6 +16,7 @@ import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapter
import org.openremote.manager.security.ManagerIdentityService
import org.openremote.manager.setup.SetupService
import org.openremote.manager.web.ManagerWebService
+import org.openremote.model.asset.impl.ConsoleAsset
import org.openremote.model.attribute.AttributeRef
import org.openremote.model.console.ConsoleProvider
import org.openremote.model.console.ConsoleRegistration
@@ -56,6 +58,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def managerTestSetup = container.getService(SetupService.class).getTaskOfType(ManagerTestSetup.class)
def notificationService = container.getService(NotificationService.class)
def pushNotificationHandler = container.getService(PushNotificationHandler.class)
+ def assetStorageService = container.getService(AssetStorageService.class)
def consoleResource = (ConsoleResourceImpl)container.getService(ManagerWebService.class).apiSingletons.find {it instanceof ConsoleResourceImpl}
and: "a mock push notification handler"
@@ -326,6 +329,30 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
assert notificationTargetIds.contains(testuser3Console2.id)
}
+ when: "the FCM token is set to null for a console asset"
+ notificationIds.clear()
+ notificationTargetIds.clear()
+ def testUser3Console1Asset = assetStorageService.find(testuser3Console1.id) as ConsoleAsset
+ testUser3Console1Asset.getConsoleProviders().map{it.get(PushNotificationMessage.TYPE)}.get().getData().set("token", null)
+ testUser3Console1Asset = assetStorageService.merge(testUser3Console1Asset)
+
+ then: "the cached FCM token should be removed from the handler"
+ conditions.eventually {
+ assert pushNotificationHandler.consoleFCMTokenMap.get(testUser3Console1Asset.id) == null
+ }
+
+ when: "the admin user sends a notification to a user linked to the console without an FCM token"
+ notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakTestSetup.testuser3Id)]
+ advancePseudoClock(1, TimeUnit.HOURS, container)
+ adminNotificationResource.sendNotification(null, notification)
+
+ then: "the notification should have been sent"
+ conditions.eventually {
+ assert notificationIds.size() == 1
+ assert notificationTargetIds.contains(testuser3Console2.id)
+ assert !notificationTargetIds.contains(testuser3Console1.id)
+ }
+
// -----------------------------------------------
// Check notification resource
// -----------------------------------------------
@@ -343,7 +370,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
n.deliveredOn == null &&
n.acknowledgedOn == null
}
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 6
+ assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 7
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, anonymousConsole.id).length == 4
}
@@ -461,12 +488,12 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
.plus(59, ChronoUnit.MINUTES)
advancePseudoClock(ChronoUnit.MILLIS.between(Instant.ofEpochMilli(getClockTimeOf(container)), advancement), TimeUnit.MILLISECONDS, container)
+ notification.targets = [new Notification.Target(Notification.TargetType.ASSET, testuser3Console2.id)]
notification.setRepeatFrequency(RepeatFrequency.HOURLY)
testuser3NotificationResource.sendNotification(null, notification)
- then: "the notifications should have been sent (to testuser3 consoles)"
+ then: "the notification should have been sent to the console"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 1
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 1
}
@@ -475,7 +502,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 1
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 1
}
@@ -484,7 +510,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 2
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 2
}
@@ -494,7 +519,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 2
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 2
}
@@ -504,7 +528,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 3
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 3
}
@@ -515,7 +538,6 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "no new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 3
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 3
}
@@ -525,19 +547,16 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
then: "new notifications should have been sent"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console1.id).length == 4
assert adminNotificationResource.getNotifications(null, null, null, null, null, null, null, testuser3Console2.id).length == 4
}
and: "notifications are retrieved only for the past day only the relevant notifications should have been returned"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000*24), null, null, null, testuser3Console1.id).length == 1
assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000*24), null, null, null, testuser3Console2.id).length == 1
}
and: "notifications are retrieved only for the past 40 days only the relevant notifications should have been returned"
conditions.eventually {
- assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000L*24*40), null, null, null, testuser3Console1.id).length == 4
assert adminNotificationResource.getNotifications(null, null, null, getClockTimeOf(container)-(3600000L*24*40), null, null, null, testuser3Console2.id).length == 4
}