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
Notification updates to allow FCMDeliveryService to be used for more general purposes
Rich Turner624c29fabb26
diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java b/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.javaindex 8be3951b8..5df001758 100644--- a/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java+++ b/manager/src/main/java/org/openremote/manager/notification/FCMDeliveryService.java@@ -26,6 +26,7 @@ import org.openremote.container.Container;import org.openremote.model.notification.DeviceNotificationToken;import org.openremote.model.notification.AlertNotification;import org.openremote.model.notification.DeliveryStatus;+import org.openremote.model.util.TextUtil;import javax.persistence.EntityManager;import javax.ws.rs.client.Entity;@@ -49,6 +50,7 @@ public class FCMDeliveryService {final protected String fcmKey;final protected ResteasyWebTarget firebaseTarget;+ final protected boolean valid;public FCMDeliveryService(Container container) {this(@@ -58,9 +60,24 @@ public class FCMDeliveryService {}public FCMDeliveryService(String fcmKey, String firebaseUrl) {- if (fcmKey == null) {- LOG.info(NOTIFICATION_FIREBASE_API_KEY + " not defined, can not send notifications to user devices");+ boolean ok = true;++ if (TextUtil.isNullOrEmpty(fcmKey)) {+ LOG.info(NOTIFICATION_FIREBASE_API_KEY + " not defined, can not send notifications");+ ok = false;+ }+ if (TextUtil.isNullOrEmpty(firebaseUrl)) {+ LOG.info(NOTIFICATION_FIREBASE_URL + " not defined, can not send notifications");+ ok = false;+ }+ if (!ok) {+ this.valid = false;+ this.fcmKey = null;+ this.firebaseTarget = null;+ return;}++ this.valid = true;this.fcmKey = fcmKey;ResteasyClient client = new ResteasyClientBuilder()@@ -71,6 +88,11 @@ public class FCMDeliveryService {}public Consumer<EntityManager> deliverPendingToFCM(String userId, List<DeviceNotificationToken> deviceTokens) {+ if (!isValid()) {+ LOG.warning("FCM invalid configuration so ignoring");+ return null;+ }+return entityManager -> {List<AlertNotification> pendingNotifications = entityManager.createQuery("SELECT an FROM AlertNotification an WHERE an.userId =:userId and an.deliveryStatus = :deliveryStatus",@@ -93,11 +115,6 @@ public class FCMDeliveryService {* @return <code>true</code> if a signal was delivered to at least one device of the user.*/protected boolean sendPickupSignalThroughFCM(String userId, List<DeviceNotificationToken> deviceTokens) {- if (fcmKey == null) {- LOG.warning("No " + NOTIFICATION_FIREBASE_API_KEY + " configured, can't deliver pending notifications of: " + userId);- return false;- }-if (deviceTokens.size() == 0) {LOG.fine("No registered devices, can't deliver pending notifications of: " + userId);return false;@@ -105,29 +122,16 @@ public class FCMDeliveryService {boolean success = false;for (DeviceNotificationToken deviceToken : deviceTokens) {- try {- Invocation.Builder builder = firebaseTarget.request().header("Authorization", "key=" + fcmKey);FCMBaseMessage message;if ("ANDROID".equals(deviceToken.getDeviceType())) {message = new FCMBaseMessage(deviceToken.getToken());} else {message = new FCMMessage(new FCMNotification("_"), true, true, "high", deviceToken.getToken());}- LOG.fine("Sending FCM notification pickup message to: " + deviceToken);- Response response = builder.post(Entity.entity(message, "application/json"));- if (response.getStatus() != 200) {- LOG.warning("Error sending FCM notification pickup message, status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");- } else {- LOG.fine("Pickup message delivered successfully delivered to FCM: " + deviceToken);- }- response.close();- success = true;- } catch (Exception e) {- if (success) {- LOG.log(Level.WARNING, "Error sending FCM notification pickup message: " + getRootCause(e), e);- }- }+ LOG.fine("Sending FCM notification pickup message to: " + deviceToken);+ // Changed to behave like javadoc says+ success = sendFCMMessage(message) || success;}if (success) {LOG.fine("Successfully delivered FCM pickup message for at least one device of: " + userId);@@ -137,4 +141,37 @@ public class FCMDeliveryService {return success;}+ public boolean sendFCMMessage(FCMBaseMessage message) {+ if (!isValid()) {+ LOG.warning("FCM invalid configuration so ignoring");+ return false;+ }++ boolean success = false;+ Response response = null;++ try {+ Invocation.Builder builder = firebaseTarget.request().header("Authorization", "key=" + fcmKey);+ response = builder.post(Entity.entity(message, "application/json"));++ if (response.getStatus() != 200) {+ LOG.warning("Send error: status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");+ } else {+ LOG.fine("Send success: status=[" + response.getStatus() + "], statusInformation=[" + response.getStatusInfo() + "]");+ success = true;+ }+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Error sending FCM notification pickup message: " + getRootCause(e), e);+ } finally {+ if (response != null) {+ response.close();+ }+ }++ return success;+ }++ public boolean isValid() {+ return valid;+ }}diff --git a/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java b/manager/src/main/java/org/openremote/manager/notification/FCMMessage.javaindex f4ecf98e7..78426de5b 100644--- a/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java+++ b/manager/src/main/java/org/openremote/manager/notification/FCMMessage.java@@ -20,6 +20,9 @@package org.openremote.manager.notification;import com.fasterxml.jackson.annotation.JsonProperty;+import org.openremote.model.value.ObjectValue;++import java.util.Map;public class FCMMessage extends FCMBaseMessage {@@ -27,6 +30,7 @@ public class FCMMessage extends FCMBaseMessage {protected boolean contentAvailable;protected boolean mutableContent;protected String priority;+ protected Map<String, String> data;public FCMMessage(FCMNotification notification, boolean contentAvailable, boolean mutableContent, String priority, String to) {super(to);@@ -70,6 +74,14 @@ public class FCMMessage extends FCMBaseMessage {this.priority = priority;}+ public Map<String, String> getData() {+ return data;+ }++ public void setData(Map<String, String> data) {+ this.data = data;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +@@ -77,6 +89,7 @@ public class FCMMessage extends FCMBaseMessage {", contentAvailable=" + contentAvailable +", mutableContent=" + mutableContent +", priority='" + priority + '\'' ++ ", data='" + data + '\'' +'}';}}diff --git a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java b/manager/src/main/java/org/openremote/manager/notification/NotificationService.javaindex 261853f1a..7683a4e50 100644--- a/manager/src/main/java/org/openremote/manager/notification/NotificationService.java+++ b/manager/src/main/java/org/openremote/manager/notification/NotificationService.java@@ -29,10 +29,12 @@ import org.openremote.model.notification.AlertNotification;import org.openremote.model.notification.DeliveryStatus;import org.openremote.model.user.UserQuery;+import javax.persistence.EntityManager;import javax.persistence.Query;import java.util.Date;import java.util.List;import java.util.Optional;+import java.util.function.Consumer;public class NotificationService implements ContainerService {@@ -99,7 +101,10 @@ public class NotificationService implements ContainerService {persistenceService.doTransaction(entityManager -> entityManager.merge(notification));// Try to queue through FCM in a separate transaction- persistenceService.doTransaction(fcmDeliveryService.deliverPendingToFCM(userId, findAllTokenForUser(userId)));+ Consumer<EntityManager> fcmMessageGenerator = fcmDeliveryService.deliverPendingToFCM(userId, findAllTokenForUser(userId));+ if (fcmMessageGenerator != null) {+ persistenceService.doTransaction(fcmMessageGenerator);+ }}public List<AlertNotification> getNotificationsOfUser(String userId, DeliveryStatus deliveryStatus) {diff --git a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy b/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovyindex c35aab105..78daf6b2d 100644--- a/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/user/NotificationServiceTest.groovy@@ -1,6 +1,7 @@package org.openremote.test.userimport org.openremote.container.timer.TimerService+import org.openremote.manager.notification.FCMBaseMessageimport org.openremote.manager.notification.FCMDeliveryServiceimport org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.setup.SetupService@@ -23,6 +24,8 @@ import static org.openremote.manager.setup.AbstractKeycloakSetup.SETUP_ADMIN_PASimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_IDimport static org.openremote.model.Constants.MASTER_REALMimport static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER+import static org.openremote.manager.notification.FCMDeliveryService.NOTIFICATION_FIREBASE_API_KEY+import static org.openremote.manager.notification.FCMDeliveryService.NOTIFICATION_FIREBASE_URLclass NotificationServiceTest extends Specification implements ManagerContainerTrait {@@ -30,14 +33,17 @@ class NotificationServiceTest extends Specification implements ManagerContainerTgiven: "the server container is started"def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(serverPort) << [+ (NOTIFICATION_FIREBASE_API_KEY): "test",+ (NOTIFICATION_FIREBASE_URL): "test"+ ], defaultServices())def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)and: "a mock FCM delivery service"def mockFCMDeliveryService = Spy(FCMDeliveryService, constructorArgs: [container]) {// Always "deliver" to FCM- sendPickupSignalThroughFCM(*_) >> {+ sendFCMMessage(_ as FCMBaseMessage) >> {return true}}