Skip to content

armgit / core

Public Imported from GitHub
0

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

Fix broken tests and notification changes to allow CUSTOM targets to be extracted from the message

Rich Turner35eec84d2b05
diff --git a/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java b/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
index 327d55d81..5bcd1f3ae 100644
--- a/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
+++ b/client/src/main/java/org/openremote/app/client/notifications/NotificationsActivity.java
@@ -41,7 +41,6 @@ import org.openremote.model.event.bus.EventBus;
import org.openremote.model.event.bus.EventRegistration;
import org.openremote.model.notification.*;
import org.openremote.model.query.AssetQuery;
-import org.openremote.model.query.AssetQuery;
import org.openremote.model.query.filter.TenantPredicate;
import org.openremote.model.security.Tenant;
import org.openremote.model.security.TenantResource;
@@ -437,6 +436,6 @@ public class NotificationsActivity extends AssetBrowsingActivity<NotificationsPl
}
protected Notification buildNotification() {
- return new Notification("Manager Message", sendOptions.getMessage(), new Notification.Targets(sendOptions.selectedTargetType, sendOptions.selectedTarget), null, null);
+ return new Notification("Manager Message", sendOptions.getMessage(), Collections.singletonList(new Notification.Target(sendOptions.selectedTargetType, sendOptions.selectedTarget)), null, null);
}
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
index 295945256..682b3b278 100644
--- a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java
@@ -149,70 +149,106 @@ public class EmailNotificationHandler implements NotificationHandler {
}
@Override
- public Notification.Targets mapTarget(Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
- switch (targetType) {
-
- case TENANT:
- // Find all users in this tenant
- User[] users = managerIdentityService
- .getIdentityProvider()
- .getUsers(new UserQuery().tenant(new TenantPredicate(targetId)));
-
- if (users.length == 0) {
- LOG.fine("No users found in target realm: " + targetId);
- return null;
- }
-
- Arrays.stream(users).forEach(user -> {
- EmailNotificationMessage.Recipient recipient =
- new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail());
- userEmails.put(user.getId(), recipient);
- });
-
- return new Notification.Targets(
- Notification.TargetType.USER,
- Arrays.stream(users).map(User::getId).collect(Collectors.toList()));
-
- case USER:
- // Nothing to do here
- return new Notification.Targets(targetType, targetId);
-
- case ASSET:
- // Find descendant assets with email attribute
- List<Asset> assets = assetStorageService.findAll(
- new AssetQuery()
+ public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> targets, AbstractNotificationMessage message) {
+
+ List<Notification.Target> mappedTargets = new ArrayList<>();
+
+ if (targets != null) {
+
+ targets.forEach(target -> {
+ Notification.TargetType targetType = target.getType();
+ String targetId = target.getId();
+
+ switch (targetType) {
+
+ case TENANT:
+ // Find all users in this tenant
+ User[] users = managerIdentityService
+ .getIdentityProvider()
+ .getUsers(new UserQuery().tenant(new TenantPredicate(targetId)));
+
+ if (users.length == 0) {
+ LOG.fine("No users found in target realm: " + targetId);
+ return;
+ }
+
+ Arrays.stream(users).forEach(user -> {
+ EmailNotificationMessage.Recipient recipient =
+ new EmailNotificationMessage.Recipient(user.getFullName(), user.getEmail());
+ userEmails.put(user.getId(), recipient);
+ });
+
+ mappedTargets.addAll(
+ Arrays.stream(users)
+ .map(user -> new Notification.Target(Notification.TargetType.USER, user.getId()))
+ .collect(Collectors.toList()));
+ break;
+ case USER:
+ // Nothing to do here
+ mappedTargets.add(new Notification.Target(targetType, targetId));
+ break;
+ case ASSET:
+ // Find descendant assets with email attribute
+ List<Asset> assets = assetStorageService.findAll(
+ new AssetQuery()
.select(AssetQuery.Select.selectExcludePathAndParentAndRealm()
.attributes(AttributeType.EMAIL.getAttributeName()))
.paths(new PathPredicate(targetId))
.attributes(new AttributePredicate(
- new StringPredicate(AttributeType.EMAIL.getAttributeName()),
- new ValueNotEmptyPredicate())));
+ new StringPredicate(AttributeType.EMAIL.getAttributeName()),
+ new ValueNotEmptyPredicate())));
- if (assets.isEmpty()) {
- LOG.fine("No assets with email attribute descendants of target asset");
- return null;
- }
+ if (assets.isEmpty()) {
+ LOG.fine("No assets with email attribute descendants of target asset");
+ return;
+ }
- assets.forEach(asset -> {
- EmailNotificationMessage.Recipient recipient =
- new EmailNotificationMessage.Recipient(
+ assets.forEach(asset -> {
+ EmailNotificationMessage.Recipient recipient =
+ new EmailNotificationMessage.Recipient(
asset.getName(),
asset.getAttribute(AttributeType.EMAIL)
- .flatMap(AbstractValueHolder::getValueAsString)
- .orElse(null));
- assetEmails.put(asset.getId(), recipient);
- });
-
- return new Notification.Targets(
- Notification.TargetType.ASSET,
- assets.stream().map(Asset::getId).collect(Collectors.toList()));
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .orElse(null));
+ assetEmails.put(asset.getId(), recipient);
+ });
+
+ mappedTargets.addAll(assets.stream()
+ .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
+ .collect(Collectors.toList()));
+ break;
+ }
+ });
+ }
+ EmailNotificationMessage email = (EmailNotificationMessage)message;
+
+ if (email.getTo() != null) {
+ mappedTargets.addAll(
+ email.getTo().stream()
+ .map(recipient ->
+ new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))
+ .collect(Collectors.toList()));
+ }
+ if (email.getCc() != null) {
+ mappedTargets.addAll(
+ email.getCc().stream()
+ .map(recipient ->
+ new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))
+ .collect(Collectors.toList()));
+ }
+ if (email.getBcc() != null) {
+ mappedTargets.addAll(
+ email.getBcc().stream()
+ .map(recipient ->
+ new Notification.Target(Notification.TargetType.CUSTOM, recipient.getAddress()))
+ .collect(Collectors.toList()));
}
- return null;
+ return mappedTargets;
}
@Override
- public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+ public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.Target target, AbstractNotificationMessage message) {
// Check handler is valid
if (!isValid()) {
@@ -220,7 +256,9 @@ public class EmailNotificationHandler implements NotificationHandler {
return NotificationSendResult.failure("SMTP invalid configuration so ignoring");
}
- EmailNotificationMessage.Recipient recipient;
+ EmailNotificationMessage.Recipient recipient = null;
+ Notification.TargetType targetType = target.getType();
+ String targetId = target.getId();
switch (targetType) {
@@ -230,27 +268,34 @@ public class EmailNotificationHandler implements NotificationHandler {
case ASSET:
recipient = getAssetRecipient(targetId);
break;
+ case CUSTOM:
+ // This recipient is in the message already
+ break;
default:
LOG.warning("Target type not supported: " + targetType);
- return NotificationSendResult.failure("Target type not supported: " + targetType);
}
- if (recipient == null || TextUtil.isNullOrEmpty(recipient.getAddress())) {
- LOG.warning("No recipient found for " + targetType.name().toLowerCase() + ": " + targetId);
- return NotificationSendResult.failure("No recipient found for " + targetType.name().toLowerCase() + ": " + targetId);
+ EmailNotificationMessage emailNotificationMessage = (EmailNotificationMessage) message;
+ EmailPopulatingBuilder emailBuilder = buildEmailBuilder(id, emailNotificationMessage);
+
+ if (recipient != null && !TextUtil.isNullOrEmpty(recipient.getAddress())) {
+ emailBuilder.to(convertRecipient(recipient));
}
- EmailNotificationMessage emailNotificationMessage = (EmailNotificationMessage) message;
+ if ((emailNotificationMessage.getTo() == null || emailNotificationMessage.getTo().isEmpty())
+ && (emailNotificationMessage.getCc() == null || emailNotificationMessage.getCc().isEmpty())
+ && (emailNotificationMessage.getBcc() == null || emailNotificationMessage.getBcc().isEmpty())
+ && recipient == null) {
+ LOG.warning("No recipient found for " + targetType.name().toLowerCase() + ": " + targetId);
+ return NotificationSendResult.failure("No recipients set for " + targetType.name().toLowerCase() + ": " + targetId);
+ }
// Set from based on source if not already set
if (emailNotificationMessage.getFrom() == null) {
- emailNotificationMessage.setFrom(defaultFrom);
+ emailBuilder.from(defaultFrom);
}
- // Override any to addresses with target recipient
- emailNotificationMessage.setTo(recipient);
-
- return sendMessage(buildEmail(id, emailNotificationMessage));
+ return sendMessage(emailBuilder.buildEmail());
}
public NotificationSendResult sendMessage(Email email) {
@@ -286,40 +331,43 @@ public class EmailNotificationHandler implements NotificationHandler {
}
return new EmailNotificationMessage.Recipient(asset.getName(), asset.getAttribute(AttributeType.EMAIL)
- .flatMap(AbstractValueHolder::getValueAsString)
- .orElse(null));
+ .flatMap(AbstractValueHolder::getValueAsString)
+ .orElse(null));
}
- protected Email buildEmail(long id, EmailNotificationMessage emailNotificationMessage) {
+ protected EmailPopulatingBuilder buildEmailBuilder(long id, EmailNotificationMessage emailNotificationMessage) {
EmailPopulatingBuilder emailBuilder = EmailBuilder.startingBlank()
- .from(convertRecipient(emailNotificationMessage.getFrom()))
- .withReplyTo(convertRecipient(emailNotificationMessage.getReplyTo()))
- .withSubject(emailNotificationMessage.getSubject())
- .withPlainText(emailNotificationMessage.getText())
- .withHTMLText(emailNotificationMessage.getHtml());
+ .withReplyTo(convertRecipient(emailNotificationMessage.getReplyTo()))
+ .withSubject(emailNotificationMessage.getSubject())
+ .withPlainText(emailNotificationMessage.getText())
+ .withHTMLText(emailNotificationMessage.getHtml());
+
+ if (emailNotificationMessage.getFrom() != null) {
+ emailBuilder.from(convertRecipient(emailNotificationMessage.getFrom()));
+ }
if (emailNotificationMessage.getTo() != null) {
- emailBuilder.to(
- emailNotificationMessage.getTo().stream()
- .map(this::convertRecipient).collect(Collectors.toList()));
+ emailBuilder.to(
+ emailNotificationMessage.getTo().stream()
+ .map(this::convertRecipient).collect(Collectors.toList()));
}
if (emailNotificationMessage.getCc() != null) {
emailBuilder.cc(
- emailNotificationMessage.getCc().stream()
- .map(this::convertRecipient).collect(Collectors.toList()));
+ emailNotificationMessage.getCc().stream()
+ .map(this::convertRecipient).collect(Collectors.toList()));
}
if (emailNotificationMessage.getBcc() != null) {
emailBuilder.bcc(
- emailNotificationMessage.getBcc().stream()
- .map(this::convertRecipient).collect(Collectors.toList()));
+ emailNotificationMessage.getBcc().stream()
+ .map(this::convertRecipient).collect(Collectors.toList()));
}
// Use the notification ID as the message ID
emailBuilder.fixingMessageId("<" + id + "@openremote.io>");
- return emailBuilder.buildEmail();
+ return emailBuilder;
}
protected Recipient convertRecipient(EmailNotificationMessage.Recipient recipient) {
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java
index 489bf6aa0..808065bce 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java
@@ -25,13 +25,15 @@ import org.openremote.model.notification.AbstractNotificationMessage;
import org.openremote.model.notification.Notification;
import org.openremote.model.notification.NotificationSendResult;
+import java.util.List;
+
/**
* A {@link NotificationHandler} is responsible for sending compatible {@link AbstractNotificationMessage} messages to
* the specified target. Before a message is sent:
* <ol>
* <li>The {@link #isMessageValid} method will be called which allows the {@link NotificationHandler} to validate
* that the message is compatible and correctly structured.
- * <li>The {@link #mapTarget} method will be called which allows the {@link NotificationHandler} to map the requested
+ * <li>The {@link #getTargets} method will be called which allows the {@link NotificationHandler} to map the requested
* target to a target that is compatible with this handler.
* </ol>
*/
@@ -54,23 +56,24 @@ public interface NotificationHandler extends ContainerService {
boolean isMessageValid(AbstractNotificationMessage message);
/**
- * Map the requested target to one or more targets that are compatible with this handler; if there are no compatible
+ * Map the requested targets to one or more targets that are compatible with this handler; if there are no compatible
* targets then return null. If the requested target is already compatible then it can just be returned; handlers
* are free to determine how the requested target should be mapped (e.g. if requested {@link Notification.TargetType}
* was {@link Notification.TargetType#TENANT} and this handler only supports targets of type
* {@link Notification.TargetType#ASSET} where {@link AssetType} equals {@link AssetType#CONSOLE} then the handler
- * needs to find all console assets that belong to the specified tenant).
+ * needs to find all console assets that belong to the specified tenant). Handlers can also add extra
+ * {@link org.openremote.model.notification.Notification.TargetType#CUSTOM} handlers extracted from the message.
*/
- Notification.Targets mapTarget(Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);
+ List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> requestedTargets, AbstractNotificationMessage message);
/**
* Send the specified {@link AbstractNotificationMessage} to the target; the target supplied would be a target
- * previously returned by {@link #mapTarget}. It is the responsibility of the {@link NotificationHandler} to
+ * previously returned by {@link #getTargets}. It is the responsibility of the {@link NotificationHandler} to
* maintain any required cache to ensure this call is as performant as possible (i.e. the handler should avoid
* making excessive DB calls if possible).
* <p>
* The ID can be used by the {@link NotificationHandler} to update the delivered and/or acknowledged status of the notification
* by calling {@link NotificationService#setNotificationDelivered} or {@link NotificationService#setNotificationAcknowleged}
*/
- NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);
+ NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.Target target, AbstractNotificationMessage message);
}
diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
index 07195177e..0ccc7073c 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationProcessingException.java
@@ -45,7 +45,7 @@ public class NotificationProcessingException extends RuntimeException {
MISSING_MESSAGE,
/**
- * Missing {@link Notification.Targets}.
+ * Missing {@link Notification.Target}.
*/
MISSING_TARGETS,
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 e3b0d6e79..38037fa46 100644
--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java
@@ -157,10 +157,6 @@ public class NotificationService extends RouteBuilder implements ContainerServic
throw new NotificationProcessingException(MISSING_MESSAGE, "Notification message must be set");
}
- if (notification.getTargets() == null || notification.getTargets().getType() == null || notification.getTargets().getIds() == null || notification.getTargets().getIds().length == 0 || Arrays.stream(notification.getTargets().getIds()).anyMatch(TextUtil::isNullOrEmpty)) {
- throw new NotificationProcessingException(MISSING_TARGETS, "Notification targets must be set");
- }
-
Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Notification.Source.class);
if (source == null) {
@@ -180,7 +176,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
String realm = null;
String userId = null;
String assetId = null;
- AtomicReference<String> sourceId = new AtomicReference<>();
+ AtomicReference<String> sourceId = new AtomicReference<>("");
boolean isSuperUser = false;
boolean isRestrictedUser = false;
@@ -226,94 +222,65 @@ public class NotificationService extends RouteBuilder implements ContainerServic
// Check access permissions
checkAccess(source, sourceId.get(), notification.getTargets(), realm, userId, isSuperUser, isRestrictedUser, assetId);
- // Map targets to handler compatible targets
- List<Notification.Targets> mappedTargetsList = Arrays.stream(notification.getTargets().getIds())
- .map(targetId -> {
- Notification.Targets mappedTargets = handler.mapTarget(source, sourceId.get(), notification.getTargets().getType(), targetId, notification.getMessage());
- if (mappedTargets == null || mappedTargets.getIds() == null || mappedTargets.getIds().length == 0) {
- LOG.fine("Failed to map target using '" + handler.getClass().getSimpleName() + "' handler: "
- + notification.getTargets().getType() + ":" + targetId);
- }
- return mappedTargets;
- })
- .filter(Objects::nonNull)
- .collect(Collectors.toList());
+ // Get the list of notification targets
+ List<Notification.Target> mappedTargetsList = handler.getTargets(source, sourceId.get(), notification.getTargets(), notification.getMessage());
- if (mappedTargetsList.isEmpty()) {
- // TODO: Should the entire notification send request fail if any mappings fail?
- throw new NotificationProcessingException(ERROR_TARGET_MAPPING, "No mapped targets");
+ if (mappedTargetsList == null || mappedTargetsList.isEmpty()) {
+ throw new NotificationProcessingException(MISSING_TARGETS, "Notification targets must be set");
}
// Filter targets based on repeat frequency
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))
- .toArray(String[]::new)
- ));
+ mappedTargetsList = mappedTargetsList.stream()
+ .filter(target -> okToSendNotification(source, sourceId.get(), target, notification))
+ .collect(Collectors.toList());
}
// Send message to each applicable target
mappedTargetsList.forEach(
- targets -> {
-
- if (targets.getIds() != null && targets.getIds().length > 0) {
-
- Arrays.stream(targets.getIds()).forEach(targetId ->
-
- persistenceService.doTransaction(em -> {
-
- // commit the notification first to get the ID
- SentNotification sentNotification = new SentNotification()
- .setName(notification.getName())
- .setType(notification.getMessage().getType())
- .setSource(source)
- .setSourceId(sourceId.get())
- .setTarget(targets.getType())
- .setTargetId(targetId)
- .setSentOn(Date.from(timerService.getNow()));
-
- sentNotification = em.merge(sentNotification);
- long id = sentNotification.getId();
-
- try {
- NotificationSendResult result = handler.sendMessage(
- id,
- source,
- sourceId.get(),
- targets.getType(),
- targetId,
- notification.getMessage());
-
- if (result.isSuccess()) {
- LOG.info("Notification sent '" + id + "': " + targets.getType() + ":" + targetId);
- } else {
- LOG.warning("Notification failed '" + id + "': " + targets.getType() + ":" + targetId + ", reason=" + result.getMessage());
- sentNotification.setError(TextUtil.isNullOrEmpty(result.getMessage()) ? "Unknown error" : result.getMessage());
- }
- // Merge the sent notification again with the message included just in case the handler modified the message
- sentNotification.setMessage(notification.getMessage().toValue());
- em.merge(sentNotification);
- } catch (Exception e) {
- LOG.log(Level.SEVERE,
- "Notification handler threw an exception whilst sending notification '" + id + "'",
- e);
- sentNotification.setError(TextUtil.isNullOrEmpty(e.getMessage()) ? "Unknown error" : e.getMessage());
- em.merge(sentNotification);
- throw e;
- }
- })
- );
- } else {
- LOG.info("Notification target contains no target IDs so ignoring");
+ target ->
+ persistenceService.doTransaction(em -> {
+
+ // commit the notification first to get the ID
+ SentNotification sentNotification = new SentNotification()
+ .setName(notification.getName())
+ .setType(notification.getMessage().getType())
+ .setSource(source)
+ .setSourceId(sourceId.get())
+ .setTarget(target.getType())
+ .setTargetId(target.getId())
+ .setSentOn(Date.from(timerService.getNow()));
+
+ sentNotification = em.merge(sentNotification);
+ long id = sentNotification.getId();
+
+ try {
+ NotificationSendResult result = handler.sendMessage(
+ id,
+ source,
+ sourceId.get(),
+ target,
+ notification.getMessage());
+
+ if (result.isSuccess()) {
+ LOG.info("Notification sent '" + id + "': " + target);
+ } else {
+ LOG.warning("Notification failed '" + id + "': " + target + ", reason=" + result.getMessage());
+ sentNotification.setError(TextUtil.isNullOrEmpty(result.getMessage()) ? "Unknown error" : result.getMessage());
+ }
+ // Merge the sent notification again with the message included just in case the handler modified the message
+ sentNotification.setMessage(notification.getMessage().toValue());
+ em.merge(sentNotification);
+ } catch (Exception e) {
+ LOG.log(Level.SEVERE,
+ "Notification handler threw an exception whilst sending notification '" + id + "'",
+ e);
+ sentNotification.setError(TextUtil.isNullOrEmpty(e.getMessage()) ? "Unknown error" : e.getMessage());
+ em.merge(sentNotification);
+ throw e;
}
- });
+ })
+ );
})
.endDoTry()
.doCatch(NotificationProcessingException.class)
@@ -321,7 +288,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
public void sendNotification(Notification notification) throws NotificationProcessingException {
- sendNotification(notification, INTERNAL, null);
+ sendNotification(notification, INTERNAL, "");
}
public void sendNotification(Notification notification, Notification.Source source, String sourceId) throws NotificationProcessingException {
@@ -519,65 +486,72 @@ public class NotificationService extends RouteBuilder implements ContainerServic
}
@SuppressWarnings("unchecked")
- protected void checkAccess(Notification.Source source, String sourceId, Notification.Targets targets, String realm, String userId, boolean isSuperUser, boolean isRestrictedUser, String assetId) throws NotificationProcessingException {
+ 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) {
return;
}
- switch (targets.getType()) {
-
- case TENANT:
- if (source == CLIENT || source == ASSET_RULESET) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
- }
- case USER:
- if (TextUtil.isNullOrEmpty(realm) || isRestrictedUser) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // Requester must be in the same realm as all target users
- boolean realmMatch = false;
-
- if (targets.getType() == Notification.TargetType.USER) {
- realmMatch = Arrays.stream(identityService.getIdentityProvider().getUsers(Arrays.asList(targets.getIds())))
- .allMatch(user -> realm.equals(user.getRealm()));
- } else {
- // Can only send to the same realm as the requestor realm
- realmMatch = targets.getIds().length == 1 && realm.equals(targets.getIds()[0]);
- }
-
- if (!realmMatch) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
- }
- break;
-
- case ASSET:
- if (TextUtil.isNullOrEmpty(realm)) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
- }
-
- // If requestor is restricted user check all target assets are linked to that user
- if (isRestrictedUser && !assetStorageService.isUserAssets(userId, Arrays.asList(targets.getIds()))) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be linked to the requesting restricted user");
- }
-
- // Target assets must be in the same realm as requestor
- if (!assetStorageService.isRealmAssets(realm, Arrays.asList(targets.getIds()))) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
- }
-
- // Target assets must be descendants of the requesting asset
- if (!TextUtil.isNullOrEmpty(assetId)) {
- if (!assetStorageService.isDescendantAssets(assetId, Arrays.asList(targets.getIds()))) {
- throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be descendants of the requesting asset");
- }
- }
- break;
+ if (targets == null || targets.isEmpty()) {
+ return;
}
+
+ targets.forEach(target -> {
+
+ switch (target.getType()) {
+
+ case TENANT:
+ if (source == CLIENT || source == ASSET_RULESET) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+ case USER:
+ if (TextUtil.isNullOrEmpty(realm) || isRestrictedUser) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // Requester must be in the same realm as all target users
+ boolean realmMatch = false;
+
+ if (target.getType() == Notification.TargetType.USER) {
+ realmMatch = Arrays.stream(identityService.getIdentityProvider().getUsers(Collections.singletonList(target.getId())))
+ .allMatch(user -> realm.equals(user.getRealm()));
+ } else {
+ // Can only send to the same realm as the requestor realm
+ realmMatch = realm.equals(target.getId());
+ }
+
+ if (!realmMatch) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
+ }
+ break;
+
+ case ASSET:
+ if (TextUtil.isNullOrEmpty(realm)) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);
+ }
+
+ // If requestor is restricted user check all target assets are linked to that user
+ if (isRestrictedUser && !assetStorageService.isUserAssets(userId, Collections.singletonList(target.getId()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be linked to the requesting restricted user");
+ }
+
+ // Target assets must be in the same realm as requestor
+ if (!assetStorageService.isRealmAssets(realm, Collections.singletonList(target.getId()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");
+ }
+
+ // Target assets must be descendants of the requesting asset
+ if (!TextUtil.isNullOrEmpty(assetId)) {
+ if (!assetStorageService.isDescendantAssets(assetId, Collections.singletonList(target.getId()))) {
+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be descendants of the requesting asset");
+ }
+ }
+ break;
+ }
+ });
}
- protected boolean okToSendNotification(Notification.Source source, String sourceId, Notification.TargetType target, String targetId, Notification notification) {
+ protected boolean okToSendNotification(Notification.Source source, String sourceId, Notification.Target target, Notification notification) {
if (notification.getRepeatFrequency() == RepeatFrequency.ALWAYS) {
return true;
@@ -587,8 +561,8 @@ public class NotificationService extends RouteBuilder implements ContainerServic
"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("target", target.getType())
+ .setParameter("targetId", target.getId())
.setParameter("name", notification.getName())
.setMaxResults(1)
.getResultList()).stream().findFirst().orElse(null);
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 a8f902d49..b58770815 100644
--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java
@@ -56,8 +56,7 @@ import java.util.stream.Collectors;
import static org.openremote.container.concurrent.GlobalLock.withLock;
import static org.openremote.container.persistence.PersistenceEvent.*;
import static org.openremote.model.asset.AssetType.CONSOLE;
-import static org.openremote.model.notification.PushNotificationMessage.TargetType.DEVICE;
-import static org.openremote.model.notification.PushNotificationMessage.TargetType.TOPIC;
+import static org.openremote.model.notification.PushNotificationMessage.TargetType.*;
public class PushNotificationHandler extends RouteBuilder implements NotificationHandler {
@@ -174,108 +173,95 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
}
@Override
- public Notification.Targets mapTarget(Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+ public List<Notification.Target> getTargets(Notification.Source source, String sourceId, List<Notification.Target> targets, AbstractNotificationMessage message) {
// Check if message is going to a topic if so then filter consoles subscribed to that topic
PushNotificationMessage pushMessage = (PushNotificationMessage) message;
- AssetQuery.Select select;
- boolean forTopic = pushMessage.getTargetType() == TOPIC;
- List<Asset> mappedConsoles;
-
- if (forTopic) {
- select = AssetQuery.Select.selectExcludePathAndParentAndRealm().attributes(AttributeType.CONSOLE_PROVIDERS.getAttributeName());
- } else {
- select = AssetQuery.Select.selectExcludeAll();
- }
-
- switch (targetType) {
-
- case TENANT:
- // Get all console assets with a push provider defined within the specified tenant
- mappedConsoles = assetStorageService.findAll(
- new AssetQuery()
- .select(select)
- .tenant(new TenantPredicate(targetId))
- .types(AssetType.CONSOLE)
- .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
- new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
- );
-
- if (forTopic) {
- mappedConsoles.removeIf(c -> !isConsoleSubscribedToTopic(c, pushMessage.getTarget()));
- }
-
- if (mappedConsoles.isEmpty()) {
- LOG.fine("No console assets linked to target realm");
- return null;
- }
-
- return new Notification.Targets(Notification.TargetType.ASSET,
- mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
-
- case USER:
-
- // Get all console assets linked to the specified user
- String[] ids = assetStorageService.findUserAssets(null, targetId, null)
- .stream()
- .map(userAsset -> userAsset.getId().getAssetId()).toArray(String[]::new);
-
- if (ids.length > 0) {
-
- mappedConsoles = assetStorageService.findAll(
- new AssetQuery()
- .select(select)
- .ids(ids)
- .types(AssetType.CONSOLE)
- .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
- new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
- );
-
- if (forTopic) {
- mappedConsoles.removeIf(c ->
- !isConsoleSubscribedToTopic(c, pushMessage.getTarget())
- );
- }
- } else {
- LOG.fine("No console assets linked to target user");
- return null;
- }
-
- return new Notification.Targets(Notification.TargetType.ASSET,
- mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
-
- case ASSET:
+ List<Notification.Target> mappedTargets = new ArrayList<>();
- // Find all console descendants of the specified asset
- mappedConsoles = assetStorageService.findAll(
- new AssetQuery()
- .select(select)
- .paths(new PathPredicate(targetId))
- .types(AssetType.CONSOLE)
- .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
- new ObjectValueKeyPredicate(PushNotificationMessage.TYPE))
- );
-
- if (forTopic) {
- mappedConsoles.removeIf(c -> !isConsoleSubscribedToTopic(c, pushMessage.getTarget()));
- }
+ if (pushMessage.getTargetType() == TOPIC || pushMessage.getTargetType() == CONDITION) {
+ mappedTargets.add(new Notification.Target(Notification.TargetType.CUSTOM, pushMessage.getTargetType() + ": " + pushMessage.getTarget()));
+ return mappedTargets;
+ }
- if (mappedConsoles.isEmpty()) {
- LOG.fine("No console assets descendants of target asset");
- return null;
+ if (targets != null) {
+
+ targets.forEach(target -> {
+
+ Notification.TargetType targetType = target.getType();
+ String targetId = target.getId();
+
+ switch (targetType) {
+
+ case TENANT:
+ // Get all console assets with a push provider defined within the specified tenant
+ mappedTargets.addAll(
+ assetStorageService.findAll(
+ new AssetQuery()
+ .select(AssetQuery.Select.selectExcludeAll())
+ .tenant(new TenantPredicate(targetId))
+ .types(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE)))
+ .stream()
+ .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
+ .collect(Collectors.toList()));
+ break;
+
+ case USER:
+ // Get all console assets linked to the specified user
+ String[] ids = assetStorageService.findUserAssets(null, targetId, null)
+ .stream()
+ .map(userAsset -> userAsset.getId().getAssetId()).toArray(String[]::new);
+
+ if (ids.length > 0) {
+
+ mappedTargets.addAll(
+ assetStorageService.findAll(
+ new AssetQuery()
+ .select(AssetQuery.Select.selectExcludeAll())
+ .ids(ids)
+ .types(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE)))
+ .stream()
+ .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
+ .collect(Collectors.toList()));
+ } else {
+ LOG.fine("No console assets linked to target user");
+ return;
+ }
+
+ break;
+
+ case ASSET:
+ // Find all console descendants of the specified asset
+ mappedTargets.addAll(
+ assetStorageService.findAll(
+ new AssetQuery()
+ .select(AssetQuery.Select.selectExcludeAll())
+ .paths(new PathPredicate(targetId))
+ .types(AssetType.CONSOLE)
+ .attributeValue(AttributeType.CONSOLE_PROVIDERS.getAttributeName(),
+ new ObjectValueKeyPredicate(PushNotificationMessage.TYPE)))
+ .stream()
+ .map(asset -> new Notification.Target(Notification.TargetType.ASSET, asset.getId()))
+ .collect(Collectors.toList()));
+ break;
}
-
- return new Notification.Targets(Notification.TargetType.ASSET,
- mappedConsoles.stream().map(Asset::getId).collect(Collectors.toList()));
+ });
}
- return null;
+ return mappedTargets;
}
@Override
- public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {
+ public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.Target target, AbstractNotificationMessage message) {
+
+ Notification.TargetType targetType = target.getType();
+ String targetId = target.getId();
- if (targetType != Notification.TargetType.ASSET) {
+ if (targetType != Notification.TargetType.ASSET && targetType != Notification.TargetType.CUSTOM) {
LOG.warning("Target type not supported: " + targetType);
return NotificationSendResult.failure("Target type not supported: " + targetType);
}
@@ -307,12 +293,10 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio
break;
case TOPIC:
// TODO: Decide how to handle FCM topic support (too much power for users to put anything in target)
- LOG.warning("Messages sent to a topic are not supported");
- return NotificationSendResult.failure("Messages sent to a topic are not supported");
+ break;
case CONDITION:
// TODO: Decide how to handle conditions support (too much power for users to put anything in target)
- LOG.warning("Messages sent to conditional targets are not supported");
- return NotificationSendResult.failure("Messages sent to conditional targets are not supported");
+ break;
}
return sendMessage(buildFCMMessage(id, pushMessage));
diff --git a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
index 74d35ca52..3f9bf770e 100644
--- a/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
+++ b/manager/src/main/java/org/openremote/manager/rules/JsonRulesBuilder.java
@@ -647,18 +647,13 @@ public class JsonRulesBuilder extends RulesBuilder {
if (notificationAction.notification != null) {
// Override the notification targets if set in the rule
- Notification.TargetType targetType = Notification.TargetType.ASSET;
+ Notification.TargetType targetType = targetIsNotAssets(ruleAction.target) ? Notification.TargetType.USER : Notification.TargetType.ASSET;
Collection<String> ids = getRuleActionTargetIds(ruleAction.target, useUnmatched, triggerStateMap, assetsFacade, usersFacade, facts);
- if (targetIsNotAssets(ruleAction.target)) {
- targetType = Notification.TargetType.USER;
- }
- if (ids == null || ids.isEmpty()) {
- log(Level.FINEST, "No targets for notification rule action so skipping: " + rule.name + " '" + actionsName + "' action index " + index);
- return null;
+ if (ids != null && !ids.isEmpty()) {
+ notificationAction.notification.setTargets(ids.stream().map(id -> new Notification.Target(targetType, id)).collect(Collectors.toList()));
}
- notificationAction.notification.setTargets(new Notification.Targets(targetType, ids));
log(Level.FINE, "Sending notification for rule action: " + rule.name + " '" + actionsName + "' action index " + index);
return new RuleActionExecution(() -> notificationsFacade.send(notificationAction.notification), 0);
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/RulesService.java b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
index 287e8839c..61cd96374 100644
--- a/manager/src/main/java/org/openremote/manager/rules/RulesService.java
+++ b/manager/src/main/java/org/openremote/manager/rules/RulesService.java
@@ -664,11 +664,12 @@ public class RulesService extends RouteBuilder implements ContainerService, Asse
);
});
+ assetRulesEngine.addRuleset(ruleset);
+
if (created.get()) {
assetRulesEngine.start();
}
- assetRulesEngine.addRuleset(ruleset);
return created.get() ? assetRulesEngine : null;
});
}
diff --git a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
index 0494a6279..0815678e5 100644
--- a/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
+++ b/manager/src/main/java/org/openremote/manager/rules/geofence/ORConsoleGeofenceAssetAdapter.java
@@ -48,6 +48,7 @@ import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.openremote.container.concurrent.GlobalLock.withLock;
@@ -265,9 +266,12 @@ public class ORConsoleGeofenceAssetAdapter extends RouteBuilder implements Geofe
int rows = (int)Math.ceil((((float)ids.size()) / 10));
IntStream.range(0, rows)
.forEach(i -> {
- final List<String> subIds = ids.subList(10 * i, Math.min(10 + (10 * i), ids.size()));
+ final List<Notification.Target> subTargets = ids.subList(10 * i, Math.min(10 + (10 * i), ids.size()))
+ .stream()
+ .map(id -> new Notification.Target(Notification.TargetType.ASSET, id))
+ .collect(Collectors.toList());
final Notification notification = new Notification("GeofenceRefresh", new PushNotificationMessage().setData(data), null, null, null);
- notification.setTargets(new Notification.Targets(Notification.TargetType.ASSET, subIds));
+ notification.setTargets(subTargets);
executorService.schedule(() -> {
LOG.info("Notifiying consoles that geofences have changed: " + notification.getTargets());
diff --git a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
index 7a2ec9336..8c0a71551 100644
--- a/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
+++ b/manager/src/main/resources/demo/rules/DemoConsoleLocation.groovy
@@ -14,6 +14,7 @@ import org.openremote.model.rules.Assets
import org.openremote.model.rules.Notifications
import java.util.logging.Logger
+import java.util.stream.Collectors
Logger LOG = binding.LOG
RulesBuilder rules = binding.rules
@@ -44,17 +45,19 @@ rules.add()
facts ->
List<String> consoleIds = facts.bound("consoleIds")
- Notification notification = new Notification(
+ if (consoleIds != null) {
+ List<Notification.Target> targets = consoleIds.stream().map{new Notification.Target(Notification.TargetType.ASSET, it)}.collect(Collectors.toList())
+ Notification notification = new Notification(
"Welcome Home",
- new PushNotificationMessage("Welcome Home", "No new events to report", null, null, null),
- new Notification.Targets(Notification.TargetType.ASSET, consoleIds), null, null)
+ new PushNotificationMessage("Welcome Home", "No new events to report", null, null, null), targets, null, null)
- notifications.send(notification)
+ notifications.send(notification)
- consoleIds.forEach({
- LOG.info("Welcome Home triggered: $it")
- facts.put("welcomeHome" + "_${it}", it)
- })
+ consoleIds.forEach({
+ LOG.info("Welcome Home triggered: $it")
+ facts.put("welcomeHome" + "_${it}", it)
+ })
+ }
})
rules.add()
diff --git a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
index fa63ad78a..5e7953826 100644
--- a/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
+++ b/manager/src/main/resources/demo/rules/DemoResidenceNotifyAlarmTrigger.groovy
@@ -158,6 +158,7 @@ rules.add()
LOG.info("Alerting users of " + alarmTrigger + ": " + userIds)
+ List<Notification.Target> targets = userIds.stream().map{new Notification.Target(Notification.TargetType.USER, it)}.collect(Collectors.toList())
Notification notification = new Notification(
"ApartmentAlarm",
new PushNotificationMessage()
@@ -167,7 +168,7 @@ rules.add()
new PushNotificationButton("Details", new PushNotificationAction("#security")),
new PushNotificationButton("Alarm uit", PushNotificationAction.writeAttributeValueAction(new AttributeRef(alarmTrigger.residenceId, "alarmEnabled"), Values.create(false)))
]),
- new Notification.Targets(Notification.TargetType.USER, userIds), null, null
+ targets, null, null
)
// Send the notification to all matched users
diff --git a/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql b/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql
index 3856dfc71..b1ec3e03e 100644
--- a/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql
+++ b/manager/src/main/resources/org/openremote/manager/setup/database/V20180720_02__NotificationChanges.sql
@@ -8,7 +8,7 @@ drop table DEVICE_NOTIFICATION_TOKEN cascade;
create table NOTIFICATION (
ID int8 not null,
- NAME varchar(255) not null,
+ NAME varchar(255),
TYPE varchar(50) not null,
TARGET varchar(50) not null,
TARGET_ID varchar(43) not null,
diff --git a/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java
index 864c30053..46480fcb8 100644
--- a/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java
+++ b/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java
@@ -65,6 +65,14 @@ public class EmailNotificationMessage extends AbstractNotificationMessage {
arrayValue.add(Values.create(address));
return arrayValue;
}
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "name='" + name + '\'' +
+ ", address='" + address + '\'' +
+ '}';
+ }
}
public static final String TYPE = "email";
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 8612fd26f..10b9620e3 100644
--- a/model/src/main/java/org/openremote/model/notification/Notification.java
+++ b/model/src/main/java/org/openremote/model/notification/Notification.java
@@ -22,7 +22,8 @@ package org.openremote.model.notification;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import java.util.Collection;
+import java.util.Arrays;
+import java.util.List;
public class Notification {
@@ -37,43 +38,38 @@ public class Notification {
public enum TargetType {
TENANT,
USER,
- ASSET
+ ASSET,
+ CUSTOM
}
- public static class Targets {
+ public static class Target {
protected TargetType type;
- protected String[] ids;
-
- public Targets(TargetType type, Collection<String> ids) {
- this(type, ids.toArray(new String[ids.size()]));
- }
+ protected String id;
@JsonCreator
- public Targets(@JsonProperty("type") TargetType type, @JsonProperty("ids")String...ids) {
+ public Target(@JsonProperty("type") TargetType type, @JsonProperty("id")String id) {
this.type = type;
- this.ids = ids;
+ this.id = id;
}
public TargetType getType() {
return type;
}
- public void setIds(String[] ids) {
- this.ids = ids;
+ public void setId(String id) {
+ this.id = id;
}
- public String[] getIds() {
- return ids;
+ public String getId() {
+ return id;
}
-
-
@Override
public String toString() {
return getClass().getSimpleName()+ "{" +
"type=" + type +
- ", ids=" + (ids != null ? "[" + String.join(",", ids) + "]" : null) +
+ "id=" + id +
'}';
}
}
@@ -85,10 +81,10 @@ public class Notification {
protected AbstractNotificationMessage message;
protected RepeatFrequency repeatFrequency;
protected String repeatInterval;
- protected Targets targets;
+ protected List<Target> targets;
@JsonCreator
- public Notification(@JsonProperty("name") String name, @JsonProperty("message") AbstractNotificationMessage message, @JsonProperty("targets") Targets targets, @JsonProperty("repeatFrequency") RepeatFrequency repeatFrequency, @JsonProperty("repeatInterval") String repeatInterval) {
+ public Notification(@JsonProperty("name") String name, @JsonProperty("message") AbstractNotificationMessage message, @JsonProperty("targets") List<Target> targets, @JsonProperty("repeatFrequency") RepeatFrequency repeatFrequency, @JsonProperty("repeatInterval") String repeatInterval) {
this.name = name;
this.message = message;
this.targets = targets;
@@ -114,11 +110,19 @@ public class Notification {
return this;
}
- public Targets getTargets() {
+ public List<Target> getTargets() {
return targets;
}
- public void setTargets(Targets targets) {
+ public void setTargets(Target...targets) {
+ if (targets == null || targets.length == 0) {
+ this.targets = null;
+ } else {
+ this.targets = Arrays.asList(targets);
+ }
+ }
+
+ public void setTargets(List<Target> targets) {
this.targets = targets;
}
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 1dda2fe46..24c154dc4 100644
--- a/model/src/main/java/org/openremote/model/notification/SentNotification.java
+++ b/model/src/main/java/org/openremote/model/notification/SentNotification.java
@@ -38,8 +38,7 @@ public class SentNotification {
@GeneratedValue(generator = PERSISTENCE_SEQUENCE_ID_GENERATOR)
protected Long id;
- @NotNull
- @Column(name = "NAME", nullable = false)
+ @Column(name = "NAME")
protected String name;
@NotNull
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
index 47080d846..382b85688 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy
@@ -167,7 +167,7 @@ class AssetBrowserPresenterTest extends Specification implements ManagerContaine
assert rowData[1].label == "Building"
assert rowData[1].id == keycloakDemoSetup.tenantBuilding.realm
assert rowData[2] instanceof TenantTreeNode
- assert rowData[2].label == "City"
+ assert rowData[2].label == "Smart City"
assert rowData[2].id == keycloakDemoSetup.tenantCity.realm
}
1 * treeDisplay.setRowCount(3, true)
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy
index f86a9a764..a3c007df8 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy
@@ -30,9 +30,15 @@ import spock.lang.Specification
import static org.openremote.model.Constants.MASTER_REALM
import static org.openremote.model.asset.AssetType.AGENT
+import static org.openremote.model.asset.AssetType.AREA
import static org.openremote.model.asset.AssetType.BUILDING
+import static org.openremote.model.asset.AssetType.CAMERA
+import static org.openremote.model.asset.AssetType.CITY
import static org.openremote.model.asset.AssetType.CONSOLE
+import static org.openremote.model.asset.AssetType.ENVIRONMENT_SENSOR
import static org.openremote.model.asset.AssetType.FLOOR
+import static org.openremote.model.asset.AssetType.LIGHT
+import static org.openremote.model.asset.AssetType.MICROPHONE
import static org.openremote.model.asset.AssetType.RESIDENCE
import static org.openremote.model.asset.AssetType.ROOM
import static org.openremote.model.asset.AssetType.THING
@@ -63,16 +69,22 @@ class AssetModelResourceTest extends Specification implements ManagerContainerTr
def assetDescriptors = assetModelResource.getAssetDescriptors(null)
then: "the default asset types should be present"
- assetDescriptors.size() == 7
+ assetDescriptors.size() == 13
assetDescriptors[0].name == BUILDING.name
assetDescriptors[0].attributeDescriptors.length == 5
assetDescriptors[0].attributeDescriptors.find {it.attributeName == AttributeType.SURFACE_AREA.attributeName}.valueDescriptor.valueType == ValueType.NUMBER
- assetDescriptors[1].name == FLOOR.name
- assetDescriptors[2].name == RESIDENCE.name
- assetDescriptors[3].name == ROOM.name
- assetDescriptors[4].name == AGENT.name
- assetDescriptors[5].name == CONSOLE.name
- assetDescriptors[6].name == THING.name
+ assetDescriptors[1].name == CITY.name
+ assetDescriptors[2].name == AREA.name
+ assetDescriptors[3].name == FLOOR.name
+ assetDescriptors[4].name == RESIDENCE.name
+ assetDescriptors[5].name == ROOM.name
+ assetDescriptors[6].name == AGENT.name
+ assetDescriptors[7].name == CONSOLE.name
+ assetDescriptors[8].name == MICROPHONE.name
+ assetDescriptors[9].name == ENVIRONMENT_SENSOR.name
+ assetDescriptors[10].name == LIGHT.name
+ assetDescriptors[11].name == CAMERA.name
+ assetDescriptors[12].name == THING.name
when: "a request for Attribute types is made"
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
index 4e12dd5aa..3e623cff0 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy
@@ -6,6 +6,7 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.AssetResource
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetAttribute
+import org.openremote.model.attribute.AttributeType
import org.openremote.model.query.AssetQuery
import org.openremote.model.asset.AssetType
import org.openremote.model.attribute.AttributeValueType
@@ -192,18 +193,18 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 404
when: "an asset attribute is written in the authenticated realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 123").toJson())
then: "result should match"
def asset
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert asset.getAttribute("geoStreet").get().getValue().isPresent()
- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().isPresent()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()
}
when: "an non-existent assets attribute is written in the authenticated realm"
- assetResource.writeAttributeValue(null, "doesnotexist", "geoStreet", Values.create("Teststreet 123").toJson())
+ assetResource.writeAttributeValue(null, "doesnotexist", AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 123").toJson())
then: "the attribute should be not found"
ex = thrown()
@@ -217,13 +218,13 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 404
when: "an asset attribute is written in a foreign realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, "geoStreet", Values.create("Teststreet 456").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 456").toJson())
then: "result should match"
conditions.eventually {
asset = assetResource.get(null, managerDemoSetup.smartBuildingId)
- assert asset.getAttribute("geoStreet").get().getValue().isPresent()
- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 456").toJson()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().isPresent()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().get().toJson() == Values.create("Teststreet 456").toJson()
}
cleanup: "the server should be stopped"
@@ -381,17 +382,17 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 403
when: "an asset attribute is written in the authenticated realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 123").toJson())
then: "result should match"
conditions.eventually {
def asset = assetResource.get(null, managerDemoSetup.smartOfficeId)
- assert asset.getAttribute("geoStreet").get().getValue().isPresent()
- assert asset.getAttribute("geoStreet").get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().isPresent()
+ assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().get().toJson() == Values.create("Teststreet 123").toJson()
}
when: "an asset attribute is written in a foreign realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, "geoStreet", Values.create("Teststreet 456").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 456").toJson())
then: "access should be forbidden"
ex = thrown()
@@ -527,14 +528,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 403
when: "an asset attribute is written in the authenticated realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, "geoStreet", Values.create("Teststreet 123").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartBuildingId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 123").toJson())
then: "access should be forbidden"
ex = thrown()
ex.response.status == 403
when: "an asset attribute is written in a foreign realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 456").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 456").toJson())
then: "access should be forbidden"
ex = thrown()
@@ -795,7 +796,7 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTrai
ex.response.status == 403
when: "an asset attribute is written in a foreign realm"
- assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, "geoStreet", Values.create("Teststreet 123").toJson())
+ assetResource.writeAttributeValue(null, managerDemoSetup.smartOfficeId, AttributeType.GEO_STREET.attributeName, Values.create("Teststreet 123").toJson())
then: "access should be forbidden"
ex = thrown()
diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
index fa30d908f..94f03958a 100644
--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy
@@ -10,6 +10,7 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetup
import org.openremote.model.asset.Asset
import org.openremote.model.asset.AssetAttribute
import org.openremote.model.asset.AssetType
+import org.openremote.model.attribute.AttributeType
import org.openremote.model.attribute.AttributeValueType
import org.openremote.model.attribute.MetaItemType
import org.openremote.model.calendar.CalendarEvent
@@ -264,7 +265,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
asset.realm == keycloakDemoSetup.masterTenant.realm
asset.path.length == 1
asset.path[0] == managerDemoSetup.smartOfficeId
- asset.getAttribute("geoStreet").get().getValueAsString().get() == "Torenallee 20"
+ asset.getAttribute(AttributeType.GEO_STREET).get().getValueAsString().get() == "Torenallee 20"
when: "a query is executed"
assets = assetStorageService.findAll(
@@ -308,7 +309,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {
assets.get(0).realm == keycloakDemoSetup.masterTenant.realm
assets.get(0).path.length == 1
assets.get(0).path[0] == managerDemoSetup.smartOfficeId
- assets.get(0).getAttribute("geoStreet").get().getValueAsString().get() == "Torenallee 20"
+ assets.get(0).getAttribute(AttributeType.GEO_STREET).get().getValueAsString().get() == "Torenallee 20"
when: "a query is executed"
assets = assetStorageService.findAll(
diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
index ade0bfaad..02a2d5d64 100644
--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy
@@ -61,11 +61,11 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {
PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
isValid() >> true
- sendMessage(_ as Long, _ as Notification.Source, _, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {
- id, source, sourceId, targetType, targetId, message ->
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
notificationIds << id
- targetTypes << targetType
- targetIds << targetId
+ targetTypes << target.type
+ targetIds << target.id
messages << message
callRealMethod()
}
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 0605100da..64d97ca62 100644
--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy
@@ -51,11 +51,11 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
isValid() >> true
- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {
- id, source, sourceId, targetType, targetId, message ->
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
notificationIds << id
- notificationTargetTypes << targetType
- notificationTargetIds << targetId
+ notificationTargetTypes << target.type
+ notificationTargetIds << target.id
notificationMessages << message
callRealMethod()
}
@@ -175,7 +175,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
anonymousConsole.id != null
when: "the admin user sends a push notification to an entire realm"
- notification.targets = new Notification.Targets(Notification.TargetType.TENANT, keycloakDemoSetup.tenantBuilding.realm)
+ notification.targets = [new Notification.Target(Notification.TargetType.TENANT, keycloakDemoSetup.tenantBuilding.realm)]
adminNotificationResource.sendNotification(null, notification)
then: "all consoles in that realm should have been sent a notification"
@@ -195,7 +195,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
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)
+ notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)]
advancePseudoClock(1, TimeUnit.HOURS, container)
adminNotificationResource.sendNotification(null, notification)
@@ -203,7 +203,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
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)
+ notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)]
testuser1NotificationResource.sendNotification(null, notification)
then: "access should be forbidden"
@@ -211,7 +211,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
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)
+ notification.targets = [new Notification.Target(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)]
testuser3NotificationResource.sendNotification(null, notification)
then: "access should be forbidden"
@@ -226,11 +226,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
ex.response.status == 403
when: "the admin user sends a push notification to the console assets in building realm"
- notification.targets = new Notification.Targets(Notification.TargetType.ASSET,
- testuser2Console.id,
- testuser3Console1.id,
- testuser3Console2.id,
- anonymousConsole.id)
+ notification.targets = [new Notification.Target(Notification.TargetType.ASSET, testuser2Console.id),
+ new Notification.Target(Notification.TargetType.ASSET, testuser3Console1.id),
+ new Notification.Target(Notification.TargetType.ASSET, testuser3Console2.id),
+ new Notification.Target(Notification.TargetType.ASSET, anonymousConsole.id)]
advancePseudoClock(1, TimeUnit.HOURS, container)
adminNotificationResource.sendNotification(null, notification)
@@ -267,11 +266,10 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
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)
+ notification.targets = [new Notification.Target(Notification.TargetType.ASSET, testuser2Console.id),
+ new Notification.Target(Notification.TargetType.ASSET, testuser3Console1.id),
+ new Notification.Target(Notification.TargetType.ASSET, testuser3Console2.id),
+ new Notification.Target(Notification.TargetType.ASSET, anonymousConsole.id)]
testuser3NotificationResource.sendNotification(null, notification)
then: "access should be forbidden"
@@ -283,9 +281,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
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)
+ notification.targets = [new Notification.Target(Notification.TargetType.ASSET, testuser3Console1.id),
+ new Notification.Target(Notification.TargetType.ASSET, testuser3Console2.id)]
testuser3NotificationResource.sendNotification(null, notification)
then: "the notifications should have been sent"
@@ -543,19 +540,22 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
EmailNotificationHandler mockEmailNotificationHandler = Spy(EmailNotificationHandler) {
isValid() >> true
- sendMessage(_ as Long, _ as Notification.Source, _, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {
- id, source, sourceId, targetType, targetId, message ->
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
notificationIds << id
- notificationTargetTypes << targetType
- notificationTargetIds << targetId
+ notificationTargetTypes << target.type
+ notificationTargetIds << target.id
notificationMessages << message
callRealMethod()
}
sendMessage(_ as Email) >> {
email ->
- toAddresses.addAll(((EmailNotificationMessage)notificationMessages.last()).getTo())
- return NotificationSendResult.success()
+ if (email instanceof List) {
+ def e = ((List)email).get(0) as Email
+ e.recipients.forEach {toAddresses.add(it.address)}
+ return NotificationSendResult.success()
+ }
}
}
@@ -577,22 +577,20 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
def notification = new Notification(
"Test",
new EmailNotificationMessage().setSubject("Test").setText("Hello world!"),
- new Notification.Targets(Notification.TargetType.TENANT, managerDemoSetup.realmBuildingTenant), null, null)
+ Collections.singletonList(new Notification.Target(Notification.TargetType.TENANT, managerDemoSetup.realmBuildingTenant)), null, null)
notificationService.sendNotification(notification, Notification.Source.TENANT_RULESET, managerDemoSetup.realmBuildingTenant)
then: "the email should have been sent to all tenant users"
conditions.eventually {
assert notificationMessages.size() == 3
- assert toAddresses.size() == 3
assert ((EmailNotificationMessage) notificationMessages.get(0)).getText() == "Hello world!"
assert ((EmailNotificationMessage) notificationMessages.get(0)).getSubject() == "Test"
- assert ((EmailNotificationMessage) notificationMessages.get(0)).getFrom().getAddress() == mockEmailNotificationHandler.defaultFrom
assert ((EmailNotificationMessage) notificationMessages.get(1)).getText() == "Hello world!"
assert ((EmailNotificationMessage) notificationMessages.get(1)).getSubject() == "Test"
- assert ((EmailNotificationMessage) notificationMessages.get(1)).getFrom().getAddress() == mockEmailNotificationHandler.defaultFrom
- assert toAddresses.any { ((EmailNotificationMessage.Recipient)it).getAddress() == "[email protected]" }
- assert toAddresses.any { ((EmailNotificationMessage.Recipient)it).getAddress() == "[email protected]" }
- assert toAddresses.any { ((EmailNotificationMessage.Recipient)it).getAddress() == "[email protected]" }
+ assert toAddresses.size() == 3
+ assert toAddresses.any { it == "[email protected]" }
+ assert toAddresses.any { it == "[email protected]" }
+ assert toAddresses.any { it == "[email protected]" }
}
when: "an email attribute is added to an asset"
@@ -601,14 +599,14 @@ class NotificationTest extends Specification implements ManagerContainerTrait {
kitchen = assetStorageService.merge(kitchen)
and: "an email notification is sent to a parent asset"
- notification.setTargets(new Notification.Targets(Notification.TargetType.ASSET, managerDemoSetup.apartment1Id))
+ notification.setTargets([new Notification.Target(Notification.TargetType.ASSET, managerDemoSetup.apartment1Id)])
notificationService.sendNotification(notification)
then: "the child asset with the email attribute should have been sent an email"
conditions.eventually {
assert notificationMessages.size() == 4
assert toAddresses.size() == 4
- assert toAddresses.any { ((EmailNotificationMessage.Recipient)it).getAddress() == "[email protected]" }
+ assert toAddresses.any { it == "[email protected]" }
}
cleanup: "the server should be stopped"
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
index 8ac91203c..d2d865515 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy
@@ -5,6 +5,7 @@ import com.google.firebase.messaging.Message
import org.openremote.container.timer.TimerService
import org.openremote.manager.asset.AssetProcessingService
import org.openremote.manager.asset.AssetStorageService
+import org.openremote.manager.notification.EmailNotificationHandler
import org.openremote.manager.notification.PushNotificationHandler
import org.openremote.manager.rules.RulesEngine
import org.openremote.manager.rules.RulesService
@@ -24,11 +25,13 @@ import org.openremote.model.geo.GeoJSONPoint
import org.openremote.model.notification.AbstractNotificationMessage
import org.openremote.model.notification.Notification
import org.openremote.model.notification.NotificationSendResult
+import org.openremote.model.notification.PushNotificationMessage
import org.openremote.model.rules.Ruleset
import org.openremote.model.rules.RulesetStatus
import org.openremote.model.rules.TenantRuleset
import org.openremote.model.value.ObjectValue
import org.openremote.test.ManagerContainerTrait
+import org.simplejavamail.email.Email
import spock.lang.Specification
import spock.util.concurrent.PollingConditions
@@ -45,17 +48,19 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
def "Turn all lights off when console exits the residence geofence"() {
- def notificationMessages = []
- def targetIds = []
+ List<PushNotificationMessage> notificationMessages = []
+ List<Email> emailMessages = []
+ List<Notification.Target> targets = []
+ List<Notification.Target> emailTargets = []
given: "a mock push notification handler"
PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
isValid() >> true
- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {
- id, source, sourceId, targetType, targetId, message ->
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
notificationMessages << message
- targetIds << targetId
+ targets << target
callRealMethod()
}
@@ -65,12 +70,32 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
}
}
+ and: "a mock email notification handler"
+ EmailNotificationHandler mockEmailNotificationHandler = Spy(EmailNotificationHandler) {
+ isValid() >> true
+
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
+ emailTargets << target
+ callRealMethod()
+ }
+
+ // Assume sent to FCM
+ sendMessage(_ as Email) >> {
+ email ->
+ emailMessages << email
+ return NotificationSendResult.success()
+ }
+ }
+
and: "the container environment is started with the mock handler"
def conditions = new PollingConditions(timeout: 10, delay: 1)
def serverPort = findEphemeralPort()
def services = Lists.newArrayList(defaultServices())
services.removeIf {it instanceof PushNotificationHandler}
+ services.removeIf {it instanceof EmailNotificationHandler}
services.add(mockPushNotificationHandler)
+ services.add(mockEmailNotificationHandler)
def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)
def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)
def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)
@@ -192,7 +217,15 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "a notification should have been sent to the console"
conditions.eventually {
assert notificationMessages.size() == 1
- assert targetIds[0] == consoleRegistration.id
+ assert targets[0].type == Notification.TargetType.ASSET
+ assert targets[0].id == consoleRegistration.id
+ }
+
+ and: "an email should have been sent to [email protected]"
+ conditions.eventually {
+ assert emailMessages.size() == 1
+ assert emailMessages[0].recipients.size() == 1
+ assert emailMessages[0].recipients[0].address[0] == "[email protected]"
}
and: "after a few seconds the rule should not have fired again"
@@ -215,7 +248,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console"
conditions.eventually {
assert notificationMessages.size() == 2
- assert targetIds[1] == consoleRegistration.id
+ assert targets[1].id == consoleRegistration.id
}
when: "the console sends a location update with the same location but a newer timestamp"
@@ -225,7 +258,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console (because the reset condition includes reset on timestampChanges)"
conditions.eventually {
assert notificationMessages.size() == 3
- assert targetIds[2] == consoleRegistration.id
+ assert targets[2].id == consoleRegistration.id
}
when: "the console sends a location update with a new location but still outside the geofence"
@@ -236,7 +269,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console (because the reset condition includes reset on valueChanges)"
conditions.eventually {
assert notificationMessages.size() == 4
- assert targetIds[3] == consoleRegistration.id
+ assert targets[3].id == consoleRegistration.id
}
when: "when time advances 5 hours"
@@ -248,7 +281,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
then: "another notification should have been sent to the console (because the reset condition includes reset on timer)"
conditions.eventually {
assert notificationMessages.size() == 5
- assert targetIds[4] == consoleRegistration.id
+ assert targets[4].id == consoleRegistration.id
}
when: "the Rules PAUSE_SCHEDULER is overridden to facilitate testing"
@@ -324,7 +357,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {
and: "another notification should have been sent as inside the validity period"
conditions.eventually {
assert notificationMessages.size() == 6
- assert targetIds[5] == consoleRegistration.id
+ assert targets[5].id == consoleRegistration.id
}
when: "the un-pause elapses"
diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
index 687018b78..3bbcfa74b 100644
--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy
@@ -49,11 +49,11 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCo
PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {
isValid() >> true
- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {
- id, source, sourceId, targetType, targetId, message ->
+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {
+ id, source, sourceId, target, message ->
notificationIds << id
- targetTypes << targetType
- targetIds << targetId
+ targetTypes << target.type
+ targetIds << target.id
messages << message
callRealMethod()
}
diff --git a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
index 21557cdde..24b55aeac 100644
--- a/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
+++ b/test/src/test/resources/org/openremote/test/rules/BasicJsonRules.json
@@ -55,6 +55,22 @@
}
}
},
+ {
+ "action": "notification",
+ "notification": {
+ "message": {
+ "type": "email",
+ "subject": "%RULESET_NAME%",
+ "html": "TEST",
+ "to": [
+ {
+ "address": "[email protected]",
+ "name": "OR Test"
+ }
+ ]
+ }
+ }
+ },
{
"action": "write-attribute",
"target": {