100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Added Email notification support
Rich Turner26bb531a9102
diff --git a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.propertiesindex d7a470adb..548038e0a 100644--- a/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties+++ b/client/src/main/resources/org/openremote/app/client/i18n/ManagerMessages.properties@@ -240,6 +240,7 @@ validationFailure[VALUE_MISMATCH]=Value must be of type ''{0}''.validationFailure[VALUE_PERCENTAGE_OUT_OF_RANGE]=Percentage value must be a number between 0 and 100.validationFailure[VALUE_TEMPERATURE_OUT_OF_RANGE]=Temperature out of scale''s range.validationFailure[VALUE_INVALID_COLOR_FORMAT]=Invalid color format.+validationFailure[VALUE_INVALID_EMAIL_FORMAT]=Invalid email format.validationFailure[VALUE_NUMBER_OUT_OF_RANGE]=Number out of scale''s range.validationFailure[META_ITEM_NAME_IS_REQUIRED]=Meta item name is required.validationFailure[META_ITEM_VALUE_IS_REQUIRED]=Meta item value must be a valid ''{0}''.diff --git a/gradle.properties b/gradle.propertiesindex e727cd6d4..d7563d1a6 100644--- a/gradle.properties+++ b/gradle.properties@@ -44,4 +44,5 @@ ical4jVersion = 2.1.5jafamaVersion = 2.3.1friendlyIdVersion = 1.0.1geotoolsVersion = 19.1-firebaseAdminVersion = 6.1.0\ No newline at end of file+firebaseAdminVersion = 6.1.0+simpleJavaMailVersion = 5.0.4\ No newline at end of filediff --git a/manager/build.gradle b/manager/build.gradleindex 3e31500fc..ddf287598 100644--- a/manager/build.gradle+++ b/manager/build.gradle@@ -17,6 +17,7 @@ dependencies {compile "net.jafama:jafama:$jafamaVersion"compile "org.geotools:gt-main:$geotoolsVersion"compile "com.google.firebase:firebase-admin:$firebaseAdminVersion"+ compile "org.simplejavamail:simple-java-mail:$simpleJavaMailVersion"}jar {diff --git a/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.javanew file mode 100644index 000000000..cbf84a298--- /dev/null+++ b/manager/src/main/java/org/openremote/manager/notification/EmailNotificationHandler.java@@ -0,0 +1,326 @@+/*+ * Copyright 2018, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.manager.notification;++import org.openremote.container.Container;+import org.openremote.manager.asset.AssetStorageService;+import org.openremote.manager.security.ManagerIdentityService;+import org.openremote.model.AbstractValueHolder;+import org.openremote.model.asset.Asset;+import org.openremote.model.attribute.AttributeType;+import org.openremote.model.notification.AbstractNotificationMessage;+import org.openremote.model.notification.EmailNotificationMessage;+import org.openremote.model.notification.Notification;+import org.openremote.model.notification.NotificationSendResult;+import org.openremote.model.query.AssetQuery;+import org.openremote.model.query.BaseAssetQuery;+import org.openremote.model.query.UserQuery;+import org.openremote.model.query.filter.*;+import org.openremote.model.security.User;+import org.openremote.model.util.TextUtil;+import org.simplejavamail.email.Email;+import org.simplejavamail.email.EmailBuilder;+import org.simplejavamail.email.EmailPopulatingBuilder;+import org.simplejavamail.email.Recipient;+import org.simplejavamail.mailer.Mailer;+import org.simplejavamail.mailer.MailerBuilder;+import org.simplejavamail.mailer.config.TransportStrategy;++import java.util.*;+import java.util.logging.Level;+import java.util.logging.Logger;+import java.util.stream.Collectors;++import static org.openremote.container.util.MapAccess.getBoolean;+import static org.openremote.container.util.MapAccess.getInteger;+import static org.openremote.model.Constants.*;+import static org.openremote.model.query.BaseAssetQuery.Include.ONLY_ID_AND_NAME_AND_ATTRIBUTES;++public class EmailNotificationHandler implements NotificationHandler {++ private static final Logger LOG = Logger.getLogger(EmailNotificationHandler.class.getName());+ protected String defaultFrom;+ protected Mailer mailer;+ protected ManagerIdentityService managerIdentityService;+ protected AssetStorageService assetStorageService;+ // Keep 100 user email addresses in cache for quick lookup+ protected LinkedHashMap<String, EmailNotificationMessage.Recipient> userEmails = new LinkedHashMap<String, EmailNotificationMessage.Recipient>(100) {+ @Override+ protected boolean removeEldestEntry(Map.Entry<String, EmailNotificationMessage.Recipient> eldest) {+ return size() > 100;+ }+ };+ // Keep 1000 asset email addresses in cache for quick lookup+ protected LinkedHashMap<String, EmailNotificationMessage.Recipient> assetEmails = new LinkedHashMap<String, EmailNotificationMessage.Recipient>(1000) {+ @Override+ protected boolean removeEldestEntry(Map.Entry<String, EmailNotificationMessage.Recipient> eldest) {+ return size() > 1000;+ }+ };++ @Override+ public void init(Container container) throws Exception {++ managerIdentityService = container.getService(ManagerIdentityService.class);+ assetStorageService = container.getService(AssetStorageService.class);++ // Configure SMTP+ String host = container.getConfig().getOrDefault(SETUP_EMAIL_HOST, null);+ int port = getInteger(container.getConfig(), SETUP_EMAIL_PORT, SETUP_EMAIL_PORT_DEFAULT);+ String user = container.getConfig().getOrDefault(SETUP_EMAIL_USER, null);+ String password = container.getConfig().getOrDefault(SETUP_EMAIL_PASSWORD, null);++ defaultFrom = container.getConfig().getOrDefault(SETUP_EMAIL_FROM, SETUP_EMAIL_FROM_DEFAULT);++ if (!TextUtil.isNullOrEmpty(host)) {+ MailerBuilder.MailerRegularBuilder mailerBuilder = MailerBuilder.withSMTPServer(host, port, user, password);+ boolean startTls = getBoolean(container.getConfig(), SETUP_EMAIL_TLS, SETUP_EMAIL_TLS_DEFAULT);++ mailerBuilder.withTransportStrategy(startTls ? TransportStrategy.SMTP_TLS : TransportStrategy.SMTP);+ mailer = mailerBuilder.buildMailer();+ try {+ mailer.testConnection();+ } catch (Exception e) {+ LOG.log(Level.SEVERE, "Failed to connect to SMTP server so disabling email notifications");+ mailer = null;+ }+ }+ }++ @Override+ public void start(Container container) throws Exception {++ }++ @Override+ public void stop(Container container) throws Exception {++ }++ @Override+ public boolean isValid() {+ return mailer != null;+ }++ @Override+ public String getTypeName() {+ return EmailNotificationMessage.TYPE;+ }++ @Override+ public boolean isMessageValid(AbstractNotificationMessage message) {+ return (message instanceof EmailNotificationMessage);+// if (!(message instanceof EmailNotificationMessage)) {+// LOG.warning("Invalid message: '" + message.getClass().getSimpleName() + "' is not an instance of PushNotificationMessage");+// return false;+// }+//+// EmailNotificationMessage emailMessage = (EmailNotificationMessage) message;+// if (emailMessage.getFrom() == null || (+// (emailMessage.getTo() == null || emailMessage.getTo().isEmpty())+// && (emailMessage.getCc() == null || emailMessage.getCc().isEmpty())+// && (emailMessage.getBcc() == null || emailMessage.getBcc().isEmpty()))) {+// LOG.warning("Invalid message: must contain a from and at least one recipient");+// return false;+// }+//+// return true;+ }++ @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()+ .select(new BaseAssetQuery.Select(+ ONLY_ID_AND_NAME_AND_ATTRIBUTES,+ false,+ AttributeType.EMAIL.getName()))+ .path(new PathPredicate(targetId))+ .attributes(new AttributePredicate(+ new StringPredicate(AttributeType.EMAIL.getName()),+ new ValueNotEmptyPredicate())));++ if (assets.isEmpty()) {+ LOG.fine("No assets with email attribute descendants of target asset");+ return null;+ }++ 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()));+ }++ return null;+ }++ @Override+ public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {++ // Check handler is valid+ if (!isValid()) {+ LOG.warning("SMTP invalid configuration so ignoring");+ return NotificationSendResult.failure("SMTP invalid configuration so ignoring");+ }++ EmailNotificationMessage.Recipient recipient;++ switch (targetType) {++ case USER:+ recipient = getUserRecipient(targetId);+ break;+ case ASSET:+ recipient = getAssetRecipient(targetId);+ 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;++ // Set from based on source if not already set+ if (emailNotificationMessage.getFrom() == null) {+ emailNotificationMessage.setFrom(defaultFrom);+ }++ // Override any to addresses with target recipient+ emailNotificationMessage.setTo(recipient);++ return sendMessage(buildEmail(id, emailNotificationMessage));+ }++ public NotificationSendResult sendMessage(Email email) {+ try {+ mailer.sendMail(email);+ return NotificationSendResult.success();+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Email send failed: " + e.getMessage(), e);+ return NotificationSendResult.failure("Email send failed: " + e.getMessage());+ }+ }++ protected EmailNotificationMessage.Recipient getUserRecipient(String userId) {+ if (userEmails.containsKey(userId)) {+ return userEmails.get(userId);+ }++ User[] users = managerIdentityService.getIdentityProvider().getUsers(Collections.singletonList(userId));+ if (users == null || users.length == 0) {+ return null;+ }+ return new EmailNotificationMessage.Recipient(users[0].getFullName(), users[0].getEmail());+ }++ protected EmailNotificationMessage.Recipient getAssetRecipient(String assetId) {+ if (assetEmails.containsKey(assetId)) {+ return assetEmails.get(assetId);+ }++ Asset asset = assetStorageService.find(assetId);+ if (asset == null) {+ return null;+ }++ return new EmailNotificationMessage.Recipient(asset.getName(), asset.getAttribute(AttributeType.EMAIL)+ .flatMap(AbstractValueHolder::getValueAsString)+ .orElse(null));+ }++ protected Email buildEmail(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());++ if (emailNotificationMessage.getTo() != null) {+ 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()));+ }++ if (emailNotificationMessage.getBcc() != null) {+ emailBuilder.bcc(+ 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();+ }++ protected Recipient convertRecipient(EmailNotificationMessage.Recipient recipient) {+ return recipient == null ? null : new Recipient(recipient.getName(), recipient.getAddress(), null);+ }+}diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.javaindex 3cda37e6b..489bf6aa0 100644--- a/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationHandler.java@@ -43,6 +43,11 @@ public interface NotificationHandler extends ContainerService {*/String getTypeName();+ /**+ * Indicates if this handler has a valid configuration and is usable.+ */+ boolean isValid();+/*** Allows the handler to validate the specified {@link AbstractNotificationMessage}.*/@@ -56,7 +61,7 @@ public interface NotificationHandler extends ContainerService {* {@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).*/- Notification.Targets mapTarget(Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);+ Notification.Targets mapTarget(Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);/*** Send the specified {@link AbstractNotificationMessage} to the target; the target supplied would be a target@@ -67,5 +72,5 @@ public interface NotificationHandler extends ContainerService {* 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.TargetType targetType, String targetId, AbstractNotificationMessage message);+ NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message);}diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.javaindex 5fd0cf28e..c9d0b3fe9 100644--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java@@ -58,15 +58,16 @@ import java.util.stream.IntStream;import static org.openremote.manager.notification.NotificationProcessingException.Reason.*;import static org.openremote.model.notification.Notification.HEADER_SOURCE;+import static org.openremote.model.notification.Notification.Source.ASSET_RULESET;+import static org.openremote.model.notification.Notification.Source.CLIENT;import static org.openremote.model.notification.Notification.Source.INTERNAL;// TODO Implement notification purging - configurable MAX_AGE for notifications?public class NotificationService extends RouteBuilder implements ContainerService {- private static final Logger LOG = Logger.getLogger(NotificationService.class.getName());public static final String NOTIFICATION_QUEUE = "seda://NotificationQueue?waitForTaskToComplete=IfReplyExpected&timeout=10000&purgeWhenStopping=true&discardIfNoConsumers=false&size=25000";protected static final TemporalField WEEK_FIELD_ISO = WeekFields.of(Locale.FRANCE).dayOfWeek(); // Always use ISO for consistency-+ private static final Logger LOG = Logger.getLogger(NotificationService.class.getName());protected TimerService timerService;protected PersistenceService persistenceService;protected AssetStorageService assetStorageService;@@ -78,10 +79,45 @@ public class NotificationService extends RouteBuilder implements ContainerServic// Create notification handlers here to facilitate testingnotificationHandlerMap = new HashMap<>();NotificationHandler pushHandler = new PushNotificationHandler();+ NotificationHandler emailHandler = new EmailNotificationHandler();notificationHandlerMap.put(pushHandler.getTypeName(), pushHandler);+ notificationHandlerMap.put(emailHandler.getTypeName(), emailHandler);}+ protected static Processor handleNotificationProcessingException(Logger logger) {+ return exchange -> {+ Notification notification = exchange.getIn().getBody(Notification.class);+ Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);++ StringBuilder error = new StringBuilder();++ Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, "unknown source", Notification.Source.class);+ if (source != null) {+ error.append("Error processing from ").append(source);+ }++ String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);+ if (protocolName != null) {+ error.append(" (protocol: ").append(protocolName).append(")");+ }++ // TODO Better exception handling - dead letter queue?+ if (exception instanceof NotificationProcessingException) {+ NotificationProcessingException processingException = (NotificationProcessingException) exception;+ error.append(" - ").append(processingException.getReasonPhrase());+ error.append(": ").append(notification.toString());+ logger.warning(error.toString());+ } else {+ error.append(": ").append(notification.toString());+ logger.log(Level.WARNING, error.toString(), exception);+ }++ // Make the exception available if MEP is InOut+ exchange.getOut().setBody(exception);+ };+ }+@Overridepublic void init(Container container) throws Exception {this.timerService = container.getService(TimerService.class);@@ -97,10 +133,10 @@ public class NotificationService extends RouteBuilder implements ContainerServic}container.getService(WebService.class).getApiSingletons().add(- new NotificationResourceImpl(this,- container.getService(MessageBrokerService.class),- container.getService(AssetStorageService.class),- container.getService(ManagerIdentityService.class))+ new NotificationResourceImpl(this,+ container.getService(MessageBrokerService.class),+ container.getService(AssetStorageService.class),+ container.getService(ManagerIdentityService.class)));}@@ -122,178 +158,181 @@ public class NotificationService extends RouteBuilder implements ContainerServicpublic void configure() throws Exception {from(NOTIFICATION_QUEUE)- .routeId("NotificationQueueProcessor")- .doTry()- .process(exchange -> {- Notification notification = exchange.getIn().getBody(Notification.class);+ .routeId("NotificationQueueProcessor")+ .doTry()+ .process(exchange -> {+ Notification notification = exchange.getIn().getBody(Notification.class);- if (notification == null) {- throw new NotificationProcessingException(MISSING_NOTIFICATION, "Notification must be set");- }+ if (notification == null) {+ throw new NotificationProcessingException(MISSING_NOTIFICATION, "Notification must be set");+ }- LOG.finest("Processing: " + notification.getName());+ LOG.finest("Processing: " + notification.getName());- if (notification.getMessage() == null) {- throw new NotificationProcessingException(MISSING_MESSAGE, "Notification message must be set");- }+ if (notification.getMessage() == null) {+ throw new NotificationProcessingException(MISSING_MESSAGE, "Notification message must be set");+ }- if (notification.getTargets() == null || notification.getTargets().getType() == null || notification.getTargets().getIds() == null || Arrays.stream(notification.getTargets().getIds()).anyMatch(TextUtil::isNullOrEmpty)) {- throw new NotificationProcessingException(MISSING_TARGETS, "Notification targets must be set");- }+ if (notification.getTargets() == null || notification.getTargets().getType() == null || notification.getTargets().getIds() == null || 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);+ Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, () -> null, Notification.Source.class);- if (source == null) {- throw new NotificationProcessingException(MISSING_SOURCE);- }+ if (source == null) {+ throw new NotificationProcessingException(MISSING_SOURCE);+ }- // Validate handler and message- NotificationHandler handler = notificationHandlerMap.get(notification.getMessage().getType());- if (handler == null) {- throw new NotificationProcessingException(UNSUPPORTED_MESSAGE_TYPE, "No handler for message type: " + notification.getMessage().getType());- }- if (!handler.isMessageValid(notification.getMessage())) {- throw new NotificationProcessingException(INVALID_MESSAGE);- }+ // Validate handler and message+ NotificationHandler handler = notificationHandlerMap.get(notification.getMessage().getType());+ if (handler == null) {+ throw new NotificationProcessingException(UNSUPPORTED_MESSAGE_TYPE, "No handler for message type: " + notification.getMessage().getType());+ }+ if (!handler.isMessageValid(notification.getMessage())) {+ throw new NotificationProcessingException(INVALID_MESSAGE);+ }- // Validate access and map targets to handler compatible targets- String realmId = null;- String userId = null;- String assetId = null;- AtomicReference<String> sourceId = new AtomicReference<>();- boolean isSuperUser = false;- boolean isRestrictedUser = false;-- switch (source) {- case INTERNAL:- isSuperUser = true;- break;-- 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);- }-- realmId = identityService.getIdentityProvider().getTenantForRealm(authContext.getAuthenticatedRealm()).getId();- userId = authContext.getUserId();- sourceId.set(userId);- isSuperUser = authContext.isSuperUser();- isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());- break;-- case GLOBAL_RULESET:- isSuperUser = true;- break;-- case TENANT_RULESET:- realmId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);- sourceId.set(realmId);- break;-- case ASSET_RULESET:- assetId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);- sourceId.set(assetId);- Asset asset = assetStorageService.find(assetId, false);- realmId = asset.getRealmId();- break;- }+ // Validate access and map targets to handler compatible targets+ String realmId = null;+ String userId = null;+ String assetId = null;+ AtomicReference<String> sourceId = new AtomicReference<>();+ boolean isSuperUser = false;+ boolean isRestrictedUser = false;++ switch (source) {+ case INTERNAL:+ isSuperUser = true;+ break;++ 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);+ }++ realmId = identityService.getIdentityProvider().getTenantForRealm(authContext.getAuthenticatedRealm()).getId();+ userId = authContext.getUserId();+ sourceId.set(userId);+ isSuperUser = authContext.isSuperUser();+ isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());+ break;++ case GLOBAL_RULESET:+ isSuperUser = true;+ break;++ case TENANT_RULESET:+ realmId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);+ sourceId.set(realmId);+ break;++ case ASSET_RULESET:+ assetId = exchange.getIn().getHeader(Notification.HEADER_SOURCE_ID, String.class);+ sourceId.set(assetId);+ Asset asset = assetStorageService.find(assetId, false);+ realmId = asset.getRealmId();+ break;+ }- LOG.info("Sending " + notification.getMessage().getType() + " notification '" + notification.getName() + "': '" + source + ":" + sourceId.get() + "' -> " + notification.getTargets());-- // Check access permissions- checkAccess(notification.getTargets(), realmId, 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(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());-- if (mappedTargetsList.isEmpty()) {- // TODO: Should the entire notification send request fail if any mappings fail?- throw new NotificationProcessingException(ERROR_TARGET_MAPPING, "No mapped targets");- }+ LOG.info("Sending " + notification.getMessage().getType() + " notification '" + notification.getName() + "': '" + source + ":" + sourceId.get() + "' -> " + notification.getTargets());++ // Check access permissions+ checkAccess(source, sourceId.get(), notification.getTargets(), realmId, 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());++ if (mappedTargetsList.isEmpty()) {+ // TODO: Should the entire notification send request fail if any mappings fail?+ throw new NotificationProcessingException(ERROR_TARGET_MAPPING, "No mapped targets");+ }- // 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)- ));- }+ // 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)+ ));+ }- // 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())- .setMessage(notification.getMessage().toValue())- .setSource(source)- .setSourceId(sourceId.get())- .setTarget(targets.getType())- .setTargetId(targetId)- .setSentOn(Date.from(timerService.getNow().toInstant()));-- sentNotification = em.merge(sentNotification);- long id = sentNotification.getId();-- try {- NotificationSendResult result = handler.sendMessage(id,- 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());- 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");- }- });- })- .endDoTry()- .doCatch(NotificationProcessingException.class)- .process(handleNotificationProcessingException(LOG));+ // 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())+ .setMessage(notification.getMessage().toValue())+ .setSource(source)+ .setSourceId(sourceId.get())+ .setTarget(targets.getType())+ .setTargetId(targetId)+ .setSentOn(Date.from(timerService.getNow().toInstant()));++ 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());+ 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");+ }+ });+ })+ .endDoTry()+ .doCatch(NotificationProcessingException.class)+ .process(handleNotificationProcessingException(LOG));}public void sendNotification(Notification notification) throws NotificationProcessingException {@@ -347,16 +386,16 @@ public class NotificationService extends RouteBuilder implements ContainerServicreturn persistenceService.doReturningTransaction(entityManager -> {TypedQuery<SentNotification> query = entityManager.createQuery(builder.toString(), SentNotification.class);IntStream.range(0, parameters.size())- .forEach(i -> query.setParameter(i+1, parameters.get(i)));+ .forEach(i -> query.setParameter(i + 1, parameters.get(i)));return query.getResultList();});}public void removeNotification(Long id) {persistenceService.doTransaction(entityManager -> entityManager- .createQuery("delete SentNotification where id = :id")- .setParameter("id", id)- .executeUpdate()+ .createQuery("delete SentNotification where id = :id")+ .setParameter("id", id)+ .executeUpdate());}@@ -370,7 +409,7 @@ public class NotificationService extends RouteBuilder implements ContainerServicpersistenceService.doTransaction(entityManager -> {Query query = entityManager.createQuery(builder.toString());IntStream.range(0, parameters.size())- .forEach(i -> query.setParameter(i+1, parameters.get(i)));+ .forEach(i -> query.setParameter(i + 1, parameters.get(i)));query.executeUpdate();});}@@ -406,54 +445,54 @@ public class NotificationService extends RouteBuilder implements ContainerServicif (hasIds) {builder.append(" AND n.id IN ?")- .append(parameters.size() + 1);+ .append(parameters.size() + 1);parameters.add(ids);return;}if (hasTypes) {builder.append(" AND n.type IN ?")- .append(parameters.size() + 1);+ .append(parameters.size() + 1);parameters.add(types);}if (fromTimestamp != null) {builder.append(" AND n.sentOn >= ?")- .append(parameters.size() + 1);+ .append(parameters.size() + 1);parameters.add(new Date(fromTimestamp));}if (toTimestamp != null) {builder.append(" AND n.sentOn <= ?")- .append(parameters.size() + 1);+ .append(parameters.size() + 1);parameters.add(new Date(toTimestamp));}if (hasAssets) {builder.append(" AND n.target = ?")- .append(parameters.size() + 1)- .append(" AND n.targetId IN ?")- .append(parameters.size() + 2);+ .append(parameters.size() + 1)+ .append(" AND n.targetId IN ?")+ .append(parameters.size() + 2);parameters.add(Notification.TargetType.ASSET);parameters.add(assetIds);} else if (hasUsers) {builder.append(" AND n.target = ?")- .append(parameters.size() + 1)- .append(" AND n.targetId IN ?")- .append(parameters.size() + 2);+ .append(parameters.size() + 1)+ .append(" AND n.targetId IN ?")+ .append(parameters.size() + 2);parameters.add(Notification.TargetType.USER);parameters.add(userIds);} else if (hasTenants) {builder.append(" AND n.target = ?")- .append(parameters.size() + 1)- .append(" AND n.targetId IN ?")- .append(parameters.size() + 2);+ .append(parameters.size() + 1)+ .append(" AND n.targetId IN ?")+ .append(parameters.size() + 2);parameters.add(Notification.TargetType.TENANT);parameters.add(tenantIds);@@ -495,7 +534,7 @@ public class NotificationService extends RouteBuilder implements ContainerServic}@SuppressWarnings("unchecked")- protected void checkAccess(Notification.Targets targets, String realmId, String userId, boolean isSuperUser, boolean isRestrictedUser, String assetId) throws NotificationProcessingException {+ protected void checkAccess(Notification.Source source, String sourceId, Notification.Targets targets, String realmId, String userId, boolean isSuperUser, boolean isRestrictedUser, String assetId) throws NotificationProcessingException {if (isSuperUser) {return;@@ -504,17 +543,24 @@ public class NotificationService extends RouteBuilder implements ContainerServicswitch (targets.getType()) {case TENANT:- // Only super user can send notifications to whole tenant- throw new NotificationProcessingException(INSUFFICIENT_ACCESS);-+ if (source == CLIENT || source == ASSET_RULESET) {+ throw new NotificationProcessingException(INSUFFICIENT_ACCESS);+ }case USER:if (TextUtil.isNullOrEmpty(realmId) || isRestrictedUser) {throw new NotificationProcessingException(INSUFFICIENT_ACCESS);}// Requester must be in the same realm as all target users- boolean realmMatch = Arrays.stream(identityService.getIdentityProvider().getUsers(Arrays.asList(targets.getIds())))- .allMatch(user -> realmId.equals(user.getRealmId()));+ boolean realmMatch = false;++ if (targets.getType() == Notification.TargetType.USER) {+ realmMatch = Arrays.stream(identityService.getIdentityProvider().getUsers(Arrays.asList(targets.getIds())))+ .allMatch(user -> realmId.equals(user.getRealmId()));+ } else {+ // Can only send to the same realm as the requestor realm+ realmMatch = targets.getIds().length == 1 && realmId.equals(targets.getIds()[0]);+ }if (!realmMatch) {throw new NotificationProcessingException(INSUFFICIENT_ACCESS, "Targets must all be in the same realm as the requestor");@@ -553,51 +599,18 @@ public class NotificationService extends RouteBuilder implements ContainerServic}Date lastSend = persistenceService.doReturningTransaction(entityManager -> entityManager.createQuery(- "SELECT n.sentOn FROM SentNotification n WHERE n.source =:source AND n.sourceId =:sourceId AND n.target =:target AND n.targetId =:targetId AND n.name =:name ORDER BY n.sentOn DESC", Date.class)- .setParameter("source", source)- .setParameter("sourceId", sourceId)- .setParameter("target", target)- .setParameter("targetId", targetId)- .setParameter("name", notification.getName())- .setMaxResults(1)- .getResultList()).stream().findFirst().orElse(null);+ "SELECT n.sentOn FROM SentNotification n WHERE n.source =:source AND n.sourceId =:sourceId AND n.target =:target AND n.targetId =:targetId AND n.name =:name ORDER BY n.sentOn DESC", Date.class)+ .setParameter("source", source)+ .setParameter("sourceId", sourceId)+ .setParameter("target", target)+ .setParameter("targetId", targetId)+ .setParameter("name", notification.getName())+ .setMaxResults(1)+ .getResultList()).stream().findFirst().orElse(null);return lastSend == null ||- (notification.getRepeatFrequency() != RepeatFrequency.ONCE &&- timerService.getNow().plusSeconds(1).isAfter(getRepeatAfterTimestamp(notification, ZonedDateTime.ofInstant(lastSend.toInstant(),- ZoneId.systemDefault()))));- }-- protected static Processor handleNotificationProcessingException(Logger logger) {- return exchange -> {- Notification notification = exchange.getIn().getBody(Notification.class);- Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);-- StringBuilder error = new StringBuilder();-- Notification.Source source = exchange.getIn().getHeader(HEADER_SOURCE, "unknown source", Notification.Source.class);- if (source != null) {- error.append("Error processing from ").append(source);- }-- String protocolName = exchange.getIn().getHeader(Protocol.SENSOR_QUEUE_SOURCE_PROTOCOL, String.class);- if (protocolName != null) {- error.append(" (protocol: ").append(protocolName).append(")");- }-- // TODO Better exception handling - dead letter queue?- if (exception instanceof NotificationProcessingException) {- NotificationProcessingException processingException = (NotificationProcessingException) exception;- error.append(" - ").append(processingException.getReasonPhrase());- error.append(": ").append(notification.toString());- logger.warning(error.toString());- } else {- error.append(": ").append(notification.toString());- logger.log(Level.WARNING, error.toString(), exception);- }-- // Make the exception available if MEP is InOut- exchange.getOut().setBody(exception);- };+ (notification.getRepeatFrequency() != RepeatFrequency.ONCE &&+ timerService.getNow().plusSeconds(1).isAfter(getRepeatAfterTimestamp(notification, ZonedDateTime.ofInstant(lastSend.toInstant(),+ ZoneId.systemDefault()))));}}\ No newline at end of filediff --git a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.javaindex 5b1167cb6..637f76a7d 100644--- a/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java+++ b/manager/src/main/java/org/openremote/manager/notification/PushNotificationHandler.java@@ -1,5 +1,5 @@/*- * Copyright 2017, OpenRemote Inc.+ * Copyright 2018, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -51,7 +51,6 @@ import java.nio.file.Paths;import java.util.*;import java.util.logging.Level;import java.util.logging.Logger;-import java.util.stream.Collector;import java.util.stream.Collectors;import static org.openremote.container.concurrent.GlobalLock.withLock;@@ -113,7 +112,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatioreturn;}- // Not using Collectors.toMap is there is a quirk in there which means null values aren't supported!+ // Not using Collectors.toMap as there is a quirk in there which means null values aren't supported!consoleFCMTokenMap = new HashMap<>();// Find all console assets that use this adapter@@ -173,7 +172,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio}@Override- public Notification.Targets mapTarget(Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {+ public Notification.Targets mapTarget(Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {// Check if message is going to a topic if so then filter consoles subscribed to that topicPushNotificationMessage pushMessage = (PushNotificationMessage) message;@@ -272,7 +271,7 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio}@Override- public NotificationSendResult sendMessage(long id, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {+ public NotificationSendResult sendMessage(long id, Notification.Source source, String sourceId, Notification.TargetType targetType, String targetId, AbstractNotificationMessage message) {if (targetType != Notification.TargetType.ASSET) {LOG.warning("Target type not supported: " + targetType);@@ -341,19 +340,12 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio// return result;// }+ @Overridepublic boolean isValid() {return valid;}- protected boolean isConsoleSubscribedToTopic(Asset asset, String topic) {- return ConsoleConfiguration.getConsoleProvider(asset, PushNotificationMessage.TYPE)- .map(ConsoleProvider::getData)- .flatMap(objectValue -> objectValue.getArray("topics"))- .map(arrayValue -> arrayValue.contains(topic))- .orElse(false);- }-- protected NotificationSendResult sendMessage(Message message) {+ public NotificationSendResult sendMessage(Message message) {try {FirebaseMessaging.getInstance().send(message);return NotificationSendResult.success();@@ -363,6 +355,14 @@ public class PushNotificationHandler extends RouteBuilder implements Notificatio}}+ protected boolean isConsoleSubscribedToTopic(Asset asset, String topic) {+ return ConsoleConfiguration.getConsoleProvider(asset, PushNotificationMessage.TYPE)+ .map(ConsoleProvider::getData)+ .flatMap(objectValue -> objectValue.getArray("topics"))+ .map(arrayValue -> arrayValue.contains(topic))+ .orElse(false);+ }+protected static Message buildFCMMessage(long id, PushNotificationMessage pushMessage) {Message.Builder builder = Message.builder();diff --git a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.javaindex ffa657f92..b1da2272f 100644--- a/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java+++ b/manager/src/main/java/org/openremote/manager/security/ManagerKeycloakIdentityProvider.java@@ -151,10 +151,6 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider imsb.append(" join UserAsset ua on ua.id.userId = u.id");}- if (query.tenantPredicate != null && TextUtil.isNullOrEmpty(query.tenantPredicate.realm)) {- sb.append(" join PUBLIC.REALM R on R.ID = u.realmId");- }-return sb.toString();}@@ -168,7 +164,7 @@ public class ManagerKeycloakIdentityProvider extends KeycloakIdentityProvider imsb.append(" AND u.realmId = ?").append(parameters.size() + 1);parameters.add(query.tenantPredicate.realmId);} else if (!TextUtil.isNullOrEmpty(query.tenantPredicate.realm)) {- sb.append(" AND r.name = ?").append(parameters.size() + 1);+ sb.append(" AND u.realm = ?").append(parameters.size() + 1);parameters.add(query.tenantPredicate.realm);}diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.javaindex 044038e9a..d9fb14b9b 100644--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java@@ -28,7 +28,10 @@ import org.openremote.container.security.AuthForm;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.manager.security.ManagerKeycloakIdentityProvider;import org.openremote.model.security.TenantEmailConfig;+import org.openremote.model.util.TextUtil;+import static org.openremote.container.security.IdentityService.IDENTITY_NETWORK_HOST;+import static org.openremote.container.security.IdentityService.IDENTITY_NETWORK_HOST_DEFAULT;import static org.openremote.container.util.MapAccess.getBoolean;import static org.openremote.container.util.MapAccess.getInteger;import static org.openremote.model.Constants.*;@@ -42,20 +45,8 @@ public abstract class AbstractKeycloakSetup implements Setup {public static final String SETUP_ADMIN_PASSWORD = "SETUP_ADMIN_PASSWORD";public static final String SETUP_ADMIN_PASSWORD_DEFAULT = "secret";- public static final String SETUP_KEYCLOAK_EMAIL_HOST = "SETUP_KEYCLOAK_EMAIL_HOST";- public static final String SETUP_KEYCLOAK_EMAIL_HOST_DEFAULT = "smtp-host.demo.tld";- public static final String SETUP_KEYCLOAK_EMAIL_USER = "SETUP_KEYCLOAK_EMAIL_USER";- public static final String SETUP_KEYCLOAK_EMAIL_USER_DEFAULT = "smtp-user";- public static final String SETUP_KEYCLOAK_EMAIL_PASSWORD = "SETUP_KEYCLOAK_EMAIL_PASSWORD";- public static final String SETUP_KEYCLOAK_EMAIL_PASSWORD_DEFAULT = "smtp-password";- public static final String SETUP_KEYCLOAK_EMAIL_PORT = "SETUP_KEYCLOAK_EMAIL_PORT";- public static final int SETUP_KEYCLOAK_EMAIL_PORT_DEFAULT = 25;- public static final String SETUP_KEYCLOAK_EMAIL_AUTH = "SETUP_KEYCLOAK_EMAIL_AUTH";- public static final boolean SETUP_KEYCLOAK_EMAIL_AUTH_DEFAULT = true;- public static final String SETUP_KEYCLOAK_EMAIL_TLS = "SETUP_KEYCLOAK_EMAIL_TLS";- public static final boolean SETUP_KEYCLOAK_EMAIL_TLS_DEFAULT = true;- public static final String SETUP_KEYCLOAK_EMAIL_FROM = "SETUP_KEYCLOAK_EMAIL_FROM";- public static final String SETUP_KEYCLOAK_EMAIL_FROM_DEFAULT = "[email protected]";+ public static final String SETUP_EMAIL_FROM_KEYCLOAK = "SETUP_EMAIL_FROM_KEYCLOAK";+ public static final String SETUP_EMAIL_FROM_KEYCLOAK_DEFAULT = "no-reply@";final protected Container container;final protected ManagerIdentityService identityService;@@ -74,15 +65,20 @@ public abstract class AbstractKeycloakSetup implements Setup {this.setupService = container.getService(SetupService.class);// Configure SMTP- if (container.getConfig().containsKey(SETUP_KEYCLOAK_EMAIL_HOST)) {+ String host = container.getConfig().getOrDefault(SETUP_EMAIL_HOST, null);++ if (!TextUtil.isNullOrEmpty(host)) {+ String user = container.getConfig().getOrDefault(SETUP_EMAIL_USER, null);+ String password = container.getConfig().getOrDefault(SETUP_EMAIL_PASSWORD, null);+emailConfig = new TenantEmailConfig();- emailConfig.setHost(container.getConfig().getOrDefault(SETUP_KEYCLOAK_EMAIL_HOST, SETUP_KEYCLOAK_EMAIL_HOST_DEFAULT));- emailConfig.setStarttls(getBoolean(container.getConfig(), SETUP_KEYCLOAK_EMAIL_TLS,SETUP_KEYCLOAK_EMAIL_TLS_DEFAULT));- emailConfig.setPort(getInteger(container.getConfig(), SETUP_KEYCLOAK_EMAIL_PORT, SETUP_KEYCLOAK_EMAIL_PORT_DEFAULT));- emailConfig.setAuth(getBoolean(container.getConfig(), SETUP_KEYCLOAK_EMAIL_AUTH, SETUP_KEYCLOAK_EMAIL_AUTH_DEFAULT));- emailConfig.setUser(container.getConfig().getOrDefault(SETUP_KEYCLOAK_EMAIL_USER, SETUP_KEYCLOAK_EMAIL_USER_DEFAULT));- emailConfig.setPassword(container.getConfig().getOrDefault(SETUP_KEYCLOAK_EMAIL_PASSWORD, SETUP_KEYCLOAK_EMAIL_PASSWORD_DEFAULT));- emailConfig.setFrom(container.getConfig().getOrDefault(SETUP_KEYCLOAK_EMAIL_FROM, SETUP_KEYCLOAK_EMAIL_FROM_DEFAULT));+ emailConfig.setHost(host);+ emailConfig.setStarttls(getBoolean(container.getConfig(), SETUP_EMAIL_TLS, SETUP_EMAIL_TLS_DEFAULT));+ emailConfig.setPort(getInteger(container.getConfig(), SETUP_EMAIL_PORT, SETUP_EMAIL_PORT_DEFAULT));+ emailConfig.setAuth(!TextUtil.isNullOrEmpty(user));+ emailConfig.setUser(user);+ emailConfig.setPassword(password);+ emailConfig.setFrom(container.getConfig().getOrDefault(SETUP_EMAIL_FROM_KEYCLOAK, SETUP_EMAIL_FROM_KEYCLOAK_DEFAULT + container.getConfig().getOrDefault(IDENTITY_NETWORK_HOST, IDENTITY_NETWORK_HOST_DEFAULT)));} else {emailConfig = null;}diff --git a/manager/src/main/java/org/openremote/manager/setup/builtin/KeycloakDemoSetup.java b/manager/src/main/java/org/openremote/manager/setup/builtin/KeycloakDemoSetup.javaindex 07041a74c..9903b0fc4 100644--- a/manager/src/main/java/org/openremote/manager/setup/builtin/KeycloakDemoSetup.java+++ b/manager/src/main/java/org/openremote/manager/setup/builtin/KeycloakDemoSetup.java@@ -116,6 +116,7 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {testuser2.setUsername("testuser2");testuser2.setFirstName("Testuserfirst");testuser2.setLastName("Testuserlast");+ testuser2.setEmail("[email protected]");testuser2.setEnabled(true);customerAUsersResource.create(testuser2);testuser2 = customerAUsersResource.search("testuser2", null, null, null, null, null).get(0);@@ -136,6 +137,7 @@ public class KeycloakDemoSetup extends AbstractKeycloakSetup {testuser3.setUsername("testuser3");testuser3.setFirstName("Testuserfirst");testuser3.setLastName("Testuserlast");+ testuser3.setEmail("[email protected]");testuser3.setEnabled(true);customerAUsersResource.create(testuser3);testuser3 = customerAUsersResource.search("testuser3", null, null, null, null, null).get(0);diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.javaindex 1de4f29aa..35099897c 100644--- a/model/src/main/java/org/openremote/model/Constants.java+++ b/model/src/main/java/org/openremote/model/Constants.java@@ -42,4 +42,13 @@ public interface Constants {String DEFAULT_DATE_FORMAT ="dd. MMM yyyy";String DEFAULT_TIME_FORMAT ="HH:mm:ss";+ String SETUP_EMAIL_USER = "SETUP_EMAIL_USER";+ String SETUP_EMAIL_HOST = "SETUP_EMAIL_HOST";+ String SETUP_EMAIL_PASSWORD = "SETUP_EMAIL_PASSWORD";+ String SETUP_EMAIL_PORT = "SETUP_EMAIL_PORT";+ int SETUP_EMAIL_PORT_DEFAULT = 25;+ String SETUP_EMAIL_TLS = "SETUP_EMAIL_TLS";+ boolean SETUP_EMAIL_TLS_DEFAULT = true;+ String SETUP_EMAIL_FROM = "SETUP_EMAIL_FROM";+ String SETUP_EMAIL_FROM_DEFAULT = "[email protected]";}diff --git a/model/src/main/java/org/openremote/model/ValueHolder.java b/model/src/main/java/org/openremote/model/ValueHolder.javaindex f7240abac..74bffae43 100644--- a/model/src/main/java/org/openremote/model/ValueHolder.java+++ b/model/src/main/java/org/openremote/model/ValueHolder.java@@ -36,6 +36,7 @@ public interface ValueHolder {VALUE_INVALID_COLOR_FORMAT,VALUE_TEMPERATURE_OUT_OF_RANGE,VALUE_NUMBER_OUT_OF_RANGE,+ VALUE_INVALID_EMAIL_FORMAT,VALUE_INVALID,VALUE_MISMATCH,VALUE_REQUIREDdiff --git a/model/src/main/java/org/openremote/model/attribute/AttributeType.java b/model/src/main/java/org/openremote/model/attribute/AttributeType.javaindex 91d48bb5d..e547f6b3e 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeType.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeType.java@@ -35,7 +35,9 @@ public enum AttributeType implements AttributeDescriptor {CONSOLE_PLATFORM("consolePlatform", AttributeValueType.STRING),- CONSOLE_PROVIDERS("consoleProviders", AttributeValueType.OBJECT);+ CONSOLE_PROVIDERS("consoleProviders", AttributeValueType.OBJECT),++ EMAIL("email", AttributeValueType.EMAIL, new MetaItem(AssetMeta.LABEL, Values.create("Email")));final protected String name;final protected AttributeValueType attributeValueType;diff --git a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.javaindex c7186709f..085aa9db0 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeValueType.java@@ -212,15 +212,15 @@ public enum AttributeValueType {new MetaItem(FORMAT, Values.create("%0.5f MJ"))),FLOW_LPM("tachometer", ValueType.NUMBER, value -> Optional.empty(),- new MetaItem(FORMAT, Values.create("%0.5f l/m"))+ new MetaItem(FORMAT, Values.create("%0.5f L/m"))),FLOW_CMPS("tachometer", ValueType.NUMBER, value -> Optional.empty(),new MetaItem(FORMAT, Values.create("%0.5f m³/s"))),- FLOW_SCCM("tachometer", ValueType.NUMBER, value -> Optional.empty(),- new MetaItem(FORMAT, Values.create("%0.5f cm³/m"))+ FLOW_CCMPS("tachometer", ValueType.NUMBER, value -> Optional.empty(),+ new MetaItem(FORMAT, Values.create("%0.5f cm³/s"))),FLOW_CFPS("tachometer", ValueType.NUMBER, value -> Optional.empty(),@@ -235,7 +235,12 @@ public enum AttributeValueType {new MetaItem(FORMAT, Values.create("%0.1f deg"))),- GEO_JSON_POINT("map-marker", ValueType.OBJECT, value -> Optional.empty());+ GEO_JSON_POINT("map-marker", ValueType.OBJECT, value -> Optional.empty()),++ EMAIL("at", ValueType.STRING, value -> Values.getString(value)+ .filter(s -> !s.matches("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"))+ .map(array -> new ValidationFailure(ValueHolder.ValueFailureReason.VALUE_INVALID_EMAIL_FORMAT))+ );public static final String DEFAULT_ICON = "circle-thin";diff --git a/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java b/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.javanew file mode 100644index 000000000..50d0f282f--- /dev/null+++ b/model/src/main/java/org/openremote/model/notification/EmailNotificationMessage.java@@ -0,0 +1,278 @@+/*+ * Copyright 2018, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.model.notification;++import org.openremote.model.util.TextUtil;+import org.openremote.model.value.ArrayValue;+import org.openremote.model.value.ObjectValue;+import org.openremote.model.value.Values;++import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import java.util.stream.Collectors;++public class EmailNotificationMessage extends AbstractNotificationMessage {++ public static class Recipient {++ protected final String name;+ protected final String address;++ public Recipient(String address) {+ this(null, address);+ }++ public Recipient(String name, String address) {+ this.name = name;+ this.address = address;+ }++ public String getName() {+ return name;+ }++ public String getAddress() {+ return address;+ }++ public ArrayValue toValue() {+ ArrayValue arrayValue = Values.createArray();+ if (!TextUtil.isNullOrEmpty(name)) {+ arrayValue.add(Values.create(name));+ }++ arrayValue.add(Values.create(address));+ return arrayValue;+ }+ }++ public static final String TYPE = "email";+ protected Recipient from;+ protected Recipient replyTo;+ protected String subject;+ protected String text;+ protected String html;+ protected List<Recipient> to;+ protected List<Recipient> cc;+ protected List<Recipient> bcc;++ public EmailNotificationMessage() {+ super(TYPE);+ }++ public Recipient getFrom() {+ return from;+ }++ public EmailNotificationMessage setFrom(String address) {+ return setFrom(null, address);+ }++ public EmailNotificationMessage setFrom(String name, String address) {+ return setFrom(new Recipient(name, address));+ }++ public EmailNotificationMessage setFrom(Recipient sender) {+ this.from = sender;+ return this;+ }++ public String getSubject() {+ return subject;+ }++ public EmailNotificationMessage setSubject(String subject) {+ this.subject = subject;+ return this;+ }++ public String getText() {+ return text;+ }++ public EmailNotificationMessage setText(String text) {+ this.text = text;+ return this;+ }++ public String getHtml() {+ return html;+ }++ public EmailNotificationMessage setHtml(String html) {+ this.html = html;+ return this;+ }++ public Recipient getReplyTo() {+ return replyTo;+ }++ public void setReplyTo(Recipient replyTo) {+ this.replyTo = replyTo;+ }++ public List<Recipient> getTo() {+ return to;+ }++ public EmailNotificationMessage setTo(String...addresses) {+ return setTo(Arrays.stream(addresses).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage setTo(Recipient...recipients) {+ return setTo(Arrays.asList(recipients));+ }++ public EmailNotificationMessage setTo(List<Recipient> recipients) {+ if (to != null) {+ to.clear();+ }++ return addTo(recipients);+ }++ public EmailNotificationMessage addTo(String...addresses) {+ return addTo(Arrays.stream(addresses).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage addTo(Recipient...recipients) {+ return addTo(Arrays.asList(recipients));+ }++ public EmailNotificationMessage addTo(List<Recipient> recipients) {+ if (to == null) {+ to = new ArrayList<>();+ }++ to.addAll(recipients);+ return this;+ }++ public List<Recipient> getCc() {+ return cc;+ }++ public EmailNotificationMessage setCc(String...addresses) {+ return setCc(Arrays.stream(addresses).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage setCc(Recipient...recipients) {+ return setCc(Arrays.asList(recipients));+ }++ public EmailNotificationMessage setCc(List<Recipient> recipients) {+ if (cc != null) {+ cc.clear();+ }++ return addCc(recipients);+ }++ public EmailNotificationMessage addCc(String...addresses) {+ return addCc(Arrays.stream(addresses).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage addCc(Recipient...recipients) {+ return addCc(Arrays.asList(recipients));+ }++ public EmailNotificationMessage addCc(List<Recipient> recipients) {+ if (cc == null) {+ cc = new ArrayList<>();+ }++ cc.addAll(recipients);+ return this;+ }++ public List<Recipient> getBcc() {+ return bcc;+ }++ public EmailNotificationMessage setBcc(String...addresses) {+ return setBcc(Arrays.stream(addresses).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage setBcc(Recipient...recipients) {+ return setBcc(Arrays.asList(recipients));+ }++ public EmailNotificationMessage setBcc(List<Recipient> recipients) {+ if (bcc != null) {+ bcc.clear();+ }++ return addBcc(recipients);+ }++ public EmailNotificationMessage addBcc(String...address) {+ return addBcc(Arrays.stream(address).map(Recipient::new).collect(Collectors.toList()));+ }++ public EmailNotificationMessage addBcc(Recipient...recipients) {+ return addBcc(Arrays.asList(recipients));+ }++ public EmailNotificationMessage addBcc(List<Recipient> recipients) {+ if (bcc == null) {+ bcc = new ArrayList<>();+ }++ to.addAll(recipients);+ return this;+ }++ @Override+ public ObjectValue toValue() {+ ObjectValue objectValue = Values.createObject();+ objectValue.put("from", from != null ? from.toValue() : null);+ objectValue.put("subject", Values.create(subject));++ if (replyTo != null) {+ objectValue.put("replyTo", replyTo.toValue());+ }++ if (!TextUtil.isNullOrEmpty(text)) {+ objectValue.put("text", Values.create(text));+ }+ if (!TextUtil.isNullOrEmpty(html)) {+ objectValue.put("html", Values.create(html));+ }+ if (to != null) {+ ArrayValue arrayValue = Values.createArray();+ to.stream().map(Recipient::toValue).forEach(arrayValue::add);+ objectValue.put("to", arrayValue);+ }+ if (cc != null) {+ ArrayValue arrayValue = Values.createArray();+ cc.stream().map(Recipient::toValue).forEach(arrayValue::add);+ objectValue.put("cc", arrayValue);+ }+ if (bcc != null) {+ ArrayValue arrayValue = Values.createArray();+ bcc.stream().map(Recipient::toValue).forEach(arrayValue::add);+ objectValue.put("bcc", arrayValue);+ }++ return objectValue;+ }+}diff --git a/profile/deploy.yml b/profile/deploy.ymlindex 177f96193..6ef60b67b 100644--- a/profile/deploy.yml+++ b/profile/deploy.yml@@ -102,14 +102,15 @@ services:# SETUP_WIPE_CLEAN_INSTALL: # Allow override on CLI# SETUP_ADMIN_PASSWORD: # Allow override on CLI- # Configure SMTP smart host for Keycloak, to send password reset emails etc.- #SETUP_KEYCLOAK_EMAIL_HOST: smtp-host.demo.tld- #SETUP_KEYCLOAK_EMAIL_USER: 'smtp-user'- #SETUP_KEYCLOAK_EMAIL_PASSWORD: 'smtp-password'- #SETUP_KEYCLOAK_EMAIL_PORT: 25- #SETUP_KEYCLOAK_EMAIL_AUTH: 'true'- #SETUP_KEYCLOAK_EMAIL_TLS: 'true'- #SETUP_KEYCLOAK_EMAIL_FROM: '[email protected]'+ # Configure SMTP smart host, to send password reset emails etc.+ #SETUP_EMAIL_HOST: smtp-host.demo.tld+ #SETUP_EMAIL_USER: 'smtp-user'+ #SETUP_EMAIL_PASSWORD: 'smtp-password'+ #SETUP_EMAIL_PORT: 25+ #SETUP_EMAIL_AUTH: 'true'+ #SETUP_EMAIL_TLS: 'true'+ #SETUP_EMAIL_FROM_KEYCLOAK: '[email protected]'+ #SETUP_EMAIL_FROM_DEFAULT: '[email protected]'# Other demo data can be imported as needed, these examples only use the simulator protocol.SETUP_IMPORT_DEMO_USERS: 'true'diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex f1a325774..0acfdc8d2 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -1,5 +1,6 @@package org.openremote.test.console+import com.google.firebase.messaging.Messageimport org.openremote.container.util.UniqueIdentifierGeneratorimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.notification.NotificationService@@ -19,6 +20,8 @@ import org.openremote.model.console.ConsoleProviderimport org.openremote.model.console.ConsoleRegistrationimport org.openremote.model.console.ConsoleResourceimport org.openremote.model.geo.GeoJSONPoint+import org.openremote.model.notification.AbstractNotificationMessage+import org.openremote.model.notification.Notificationimport org.openremote.model.notification.NotificationSendResultimport org.openremote.model.notification.PushNotificationMessageimport org.openremote.model.query.filter.RadialLocationPredicate@@ -57,14 +60,18 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {isValid() >> true- // Assume sent to FCM- sendMessage(*_) >> {- id, targetType, targetId, message ->+ sendMessage(_ as Long, _ as Notification.Source, _, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, targetType, targetId, message ->notificationIds << idtargetTypes << targetTypetargetIds << targetIdmessages << message- return NotificationSendResult.success()+ callRealMethod()+ }++ // Assume sent to FCM+ sendMessage(_ as Message) >> {+ message -> return NotificationSendResult.success()}}diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovyindex 4df8a4fa7..425890280 100644--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy@@ -1,12 +1,17 @@package org.openremote.test.notification+import com.google.firebase.messaging.Message+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.notification.EmailNotificationHandlerimport org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapterimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.KeycloakDemoSetupimport org.openremote.manager.setup.builtin.ManagerDemoSetup+import org.openremote.model.asset.AssetAttributeimport org.openremote.model.attribute.AttributeRef+import org.openremote.model.attribute.AttributeTypeimport org.openremote.model.console.ConsoleProviderimport org.openremote.model.console.ConsoleRegistrationimport org.openremote.model.console.ConsoleResource@@ -14,7 +19,9 @@ import org.openremote.model.notification.*import org.openremote.model.value.ObjectValueimport org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTrait+import org.simplejavamail.email.Emailimport spock.lang.Specification+import spock.util.concurrent.PollingConditionsimport javax.ws.rs.WebApplicationExceptionimport java.time.Instant@@ -42,25 +49,28 @@ class NotificationTest extends Specification implements ManagerContainerTrait {PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {isValid() >> true- // Assume sent to FCM- sendMessage(*_) >> {- id, targetType, targetId, message ->+ sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.TargetType, _ as String, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, targetType, targetId, message ->notificationIds << idnotificationTargetTypes << targetTypenotificationTargetIds << targetIdnotificationMessages << message- return NotificationSendResult.success()+ callRealMethod()+ }++ // Assume sent to FCM+ sendMessage(_ as Message) >> {+ message -> return NotificationSendResult.success()}}and: "the container environment is started with the mock handler"def serverPort = findEphemeralPort()def services = defaultServices()- ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put("push", mockPushNotificationHandler)+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put(PushNotificationMessage.TYPE, mockPushNotificationHandler)def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def notificationService = container.getService(NotificationService.class)and: "an authenticated test user"def realm = keycloakDemoSetup.customerATenant.realm@@ -500,4 +510,86 @@ class NotificationTest extends Specification implements ManagerContainerTrait {cleanup: "the server should be stopped"stopContainer(container)}++ def "Check email notification functionality"() {++ def notificationIds = []+ def notificationTargetTypes = []+ def notificationTargetIds = []+ def notificationMessages = []+ def toAddresses = []++ given: "a mock email notification handler"+ 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 ->+ notificationIds << id+ notificationTargetTypes << targetType+ notificationTargetIds << targetId+ notificationMessages << message+ callRealMethod()+ }++ sendMessage(_ as Email) >> {+ email ->+ toAddresses.addAll(((EmailNotificationMessage)notificationMessages.last()).getTo())+ return NotificationSendResult.success()+ }+ }++ and: "the container environment is started with the mock handler"+ def serverPort = findEphemeralPort()+ def services = defaultServices()+ ((NotificationService)services.find {it instanceof NotificationService}).notificationHandlerMap.put(EmailNotificationMessage.TYPE, mockEmailNotificationHandler)+ def conditions = new PollingConditions(timeout: 10)+ def container = startContainer(defaultConfig(serverPort), services)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def notificationService = container.getService(NotificationService.class)+ def assetStorageService = container.getService(AssetStorageService.class)++ expect: "the container to be running"+ container.isRunning()++ when: "an email notification is sent to a tenant through same mechanism as rules"+ def notification = new Notification(+ "Test",+ new EmailNotificationMessage().setSubject("Test").setText("Hello world!"),+ new Notification.Targets(Notification.TargetType.TENANT, managerDemoSetup.customerARealmId))+ notificationService.sendNotification(notification, Notification.Source.TENANT_RULESET, managerDemoSetup.customerARealmId)++ then: "the email should have been sent to all tenant users"+ conditions.eventually {+ assert notificationMessages.size() == 2+ assert toAddresses.size() == 2+ 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]" }+ }++ when: "an email attribute is added to an asset"+ def kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId)+ kitchen.addAttributes(new AssetAttribute(AttributeType.EMAIL, Values.create("[email protected]")))+ kitchen = assetStorageService.merge(kitchen)++ and: "an email notification is sent to a parent asset"+ notification.setTargets(new Notification.Targets(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() == 3+ assert toAddresses.size() == 3+ assert toAddresses.any { ((EmailNotificationMessage.Recipient)it).getAddress() == "[email protected]" }+ }++ cleanup: "the server should be stopped"+ stopContainer(container)+ }}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.groovyindex 93afaa28e..855b63178 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@@ -1,5 +1,6 @@package org.openremote.test.rules.residence+import com.google.firebase.messaging.Messageimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.notification.NotificationService@@ -45,14 +46,18 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCoPushNotificationHandler 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 ->+ notificationIds << id+ targetTypes << targetType+ targetIds << targetId+ messages << message+ callRealMethod()+ }+// Assume sent to FCM- sendMessage(*_) >> {- id, targetType, targetId, message ->- notificationIds << id- targetTypes << targetType- targetIds << targetId- messages << message- return NotificationSendResult.success()+ sendMessage(_ as Message) >> {+ message -> return NotificationSendResult.success()}}