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
Event related updates
Rich Turnerecbc2a174014
diff --git a/client/src/main/java/org/openremote/app/client/event/EventServiceImpl.java b/client/src/main/java/org/openremote/app/client/event/EventServiceImpl.javaindex ff84a164a..29ef5efdd 100644--- a/client/src/main/java/org/openremote/app/client/event/EventServiceImpl.java+++ b/client/src/main/java/org/openremote/app/client/event/EventServiceImpl.java@@ -103,7 +103,7 @@ public class EventServiceImpl implements EventService {public void stop() {for (Map.Entry<String, Double> entry : activeSubscriptions.entrySet()) {DomGlobal.clearInterval(entry.getValue());- CancelEventSubscription cancellation = new CancelEventSubscription(entry.getKey());+ CancelEventSubscription cancellation = new CancelEventSubscription(entry.getKey(), null);sendServiceMessage(CancelEventSubscription.MESSAGE_PREFIX + cancelEventSubscriptionMapper.write(cancellation));}activeSubscriptions.clear();@@ -119,18 +119,33 @@ public class EventServiceImpl implements EventService {if (data.startsWith(UnauthorizedEventSubscription.MESSAGE_PREFIX)) {data = data.substring(UnauthorizedEventSubscription.MESSAGE_PREFIX.length());UnauthorizedEventSubscription failure = unauthorizedEventSubscriptionMapper.read(data);- eventBus.dispatch(new SubscriptionFailureEvent(failure.getEventType()));+ eventBus.dispatch(new SubscriptionFailureEvent(failure.getSubscription().getEventType()));} else if (data.startsWith(SharedEvent.MESSAGE_PREFIX)) {data = data.substring(SharedEvent.MESSAGE_PREFIX.length());- if (data.startsWith("[")) {+ if (data.startsWith("{")) {+ SharedEvent event = sharedEventMapper.read(data);+ eventBus.dispatch(event);+ } else if (data.startsWith("[")) {// Handle array of eventsSharedEvent[] events = sharedEventArrayMapper.read(data);for (SharedEvent event : events) {eventBus.dispatch(event);}} else {- SharedEvent event = sharedEventMapper.read(data);- eventBus.dispatch(event);+ String[] dataArr = data.split(":(.+)");+ if (dataArr.length == 2) {+ String subscriptionId = dataArr[0];+ if (dataArr[1].startsWith("[")) {+ // Handle array of events+ SharedEvent[] events = sharedEventArrayMapper.read(data);+ for (SharedEvent event : events) {+ eventBus.dispatch(event);+ }+ } else {+ SharedEvent event = sharedEventMapper.read(data);+ eventBus.dispatch(event);+ }+ }}}}diff --git a/client/src/main/java/org/openremote/app/client/widget/MapWidget.java b/client/src/main/java/org/openremote/app/client/widget/MapWidget.javaindex 85bf077c1..4d1b5fa77 100644--- a/client/src/main/java/org/openremote/app/client/widget/MapWidget.java+++ b/client/src/main/java/org/openremote/app/client/widget/MapWidget.java@@ -164,15 +164,12 @@ public class MapWidget extends FlowPanel {throw new IllegalStateException("Already initialized");}- ObjectValue mapOptions = Values.createObject();+ ObjectValue mapOptions = mapSettings.getObject("options").flatMap(opts -> opts.getObject("default")).orElse(null);mapOptions.put("style", mapSettings.deepCopy());- mapOptions.put("minZoom", mapSettings.getNumber("minZoom").orElse(0d));- mapOptions.put("maxZoom", mapSettings.getNumber("maxZoom").orElse(22d));- if (mapSettings.getArray("maxBounds").isPresent()) {- mapOptions.put("maxBounds", mapSettings.getArray("maxBounds").get());- }- if (mapSettings.getBoolean("boxZoom").isPresent()) {- mapOptions.put("boxZoom", mapSettings.getBoolean("boxZoom").get());+ mapOptions.put("minZoom", mapOptions.getNumber("minZoom").orElse(0d));+ mapOptions.put("maxZoom", mapOptions.getNumber("maxZoom").orElse(22d));+ if (mapOptions.getArray("bounds").isPresent()) {+ mapOptions.put("maxBounds", mapOptions.getArray("bounds").get());}mapOptions.put("container", hostElementId);mapOptions.put("attributionControl", true);diff --git a/client/src/main/webapp/src/or-app/or-app-events.html b/client/src/main/webapp/src/or-app/or-app-events.htmlindex 23e2a412f..024ba354b 100644--- a/client/src/main/webapp/src/or-app/or-app-events.html+++ b/client/src/main/webapp/src/or-app/or-app-events.html@@ -42,7 +42,7 @@eventType: "attribute",filter: {filterType: "attribute-entity-id",- entityId: assetIds+ entityIds: assetIds}});}@@ -79,10 +79,10 @@onServiceMessageReceived(data) {if (!data)return;- if (data.startsWith("UNAUTHORIZED")) {+ if (data.startsWith("UNAUTHORIZED:")) {openremote.INSTANCE.setError("Unauthorized event subscription.");- } else if (data.startsWith("EVENT")) {- data = data.substring("EVENT".length);+ } else if (data.startsWith("EVENT:")) {+ data = data.substring("EVENT:".length);if (data.startsWith("[")) {// Handle array of eventslet events = JSON.parse(data);diff --git a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.javaindex 777c014dc..b1cd0229a 100644--- a/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java+++ b/manager/src/main/java/org/openremote/manager/asset/AssetProcessingService.java@@ -178,7 +178,7 @@ public class AssetProcessingService extends RouteBuilder implements ContainerSerboolean isRestrictedUser = identityService.getIdentityProvider().isRestrictedUser(auth.getUserId());// Client can subscribe to several assets- for (String assetId : filter.getEntityId()) {+ for (String assetId : filter.getEntityIds()) {Asset asset = assetStorageService.find(assetId);// If the asset doesn't exist, subscription must failif (asset == null)diff --git a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java b/manager/src/main/java/org/openremote/manager/event/ClientEventService.javaindex 650e44060..902013083 100644--- a/manager/src/main/java/org/openremote/manager/event/ClientEventService.java+++ b/manager/src/main/java/org/openremote/manager/event/ClientEventService.java@@ -31,10 +31,7 @@ import org.openremote.container.web.socket.WebsocketConstants;import org.openremote.manager.concurrent.ManagerExecutorService;import org.openremote.manager.security.ManagerIdentityService;import org.openremote.model.Constants;-import org.openremote.model.event.shared.CancelEventSubscription;-import org.openremote.model.event.shared.EventSubscription;-import org.openremote.model.event.shared.SharedEvent;-import org.openremote.model.event.shared.UnauthorizedEventSubscription;+import org.openremote.model.event.shared.*;import org.openremote.model.syslog.SyslogEvent;import java.util.Collection;@@ -49,7 +46,7 @@ import static org.apache.camel.builder.PredicateBuilder.or;* Messages always start with a message discriminator in all uppercase letters, followed* by an optional JSON payload.* <p>- * The following messages can be send by a client:+ * The following messages can be sent by a client:* <dl>* <dt><code>SUBSCRIBE{...}</code><dt>* <dd><p>@@ -163,13 +160,14 @@ public class ClientEventService implements ContainerService {if (eventSubscriptionAuthorizers.stream().anyMatch(authorizer -> authorizer.apply(authContext, subscription))) {boolean restrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());- eventSubscriptions.update(sessionKey, restrictedUser, subscription);+ eventSubscriptions.createOrUpdate(sessionKey, restrictedUser, subscription);+ sendToSession(sessionKey, subscription);} else {LOG.warning("Unauthorized subscription from '"+ authContext.getUsername() + "' in realm '" + authContext.getAuthenticatedRealm()+ "': " + subscription);- sendToSession(sessionKey, new UnauthorizedEventSubscription(subscription.getEventType()));+ sendToSession(sessionKey, new UnauthorizedEventSubscription(subscription));}}).when(bodyAs(String.class).startsWith(CancelEventSubscription.MESSAGE_PREFIX))@@ -178,6 +176,14 @@ public class ClientEventService implements ContainerService {String sessionKey = getSessionKey(exchange);eventSubscriptions.cancel(sessionKey, exchange.getIn().getBody(CancelEventSubscription.class));})+ .when(bodyAs(String.class).startsWith(RenewEventSubscriptions.MESSAGE_PREFIX))+ .convertBodyTo(RenewEventSubscriptions.class)+ .process(exchange -> {+ String sessionKey = getSessionKey(exchange);+ AuthContext authContext = exchange.getIn().getHeader(Constants.AUTH_CONTEXT, AuthContext.class);+ boolean restrictedUser = identityService.getIdentityProvider().isRestrictedUser(authContext.getUserId());+ eventSubscriptions.update(sessionKey, restrictedUser,exchange.getIn().getBody(RenewEventSubscriptions.class).getSubscriptionIds());+ }).when(bodyAs(String.class).startsWith(SharedEvent.MESSAGE_PREFIX)).convertBodyTo(SharedEvent.class).process(exchange -> {diff --git a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.javaindex e20bd3f8a..88385f576 100644--- a/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java+++ b/manager/src/main/java/org/openremote/manager/event/EventSubscriptions.java@@ -23,11 +23,14 @@ import org.apache.camel.Exchange;import org.apache.camel.Message;import org.apache.camel.impl.DefaultMessage;import org.openremote.container.timer.TimerService;+import org.openremote.container.util.UniqueIdentifierGenerator;import org.openremote.container.web.socket.WebsocketConstants;import org.openremote.manager.concurrent.ManagerExecutorService;+import org.openremote.model.event.TriggeredEventSubscription;import org.openremote.model.event.shared.CancelEventSubscription;import org.openremote.model.event.shared.EventSubscription;import org.openremote.model.event.shared.SharedEvent;+import org.openremote.model.util.TextUtil;import java.util.*;import java.util.logging.Logger;@@ -42,7 +45,7 @@ public class EventSubscriptions {private static final Logger LOG = Logger.getLogger(EventSubscriptions.class.getName());final protected TimerService timerService;- final protected Map<String, SessionSubscriptions> sessionSubscriptions = new HashMap<>();+ final protected Map<String, SessionSubscriptions> sessionSubscriptionIdMap = new HashMap<>();class SessionSubscriptions extends HashSet<SessionSubscription> {public void removeExpired() {@@ -56,25 +59,47 @@ public class EventSubscriptions {);}- public void update(boolean restrictedUser, EventSubscription eventSubscription) {- cancel(eventSubscription.getEventType());+ public void createOrUpdate(boolean restrictedUser, EventSubscription eventSubscription) {++ if (TextUtil.isNullOrEmpty(eventSubscription.getSubscriptionId())) {+ cancelByType(eventSubscription.getEventType());+ } else {+ cancelById(eventSubscription.getSubscriptionId());+ }+add(new SessionSubscription(restrictedUser, timerService.getCurrentTimeMillis(), eventSubscription));}- public void cancel(String eventType) {+ public void update(boolean resstrictedUser, String[] subscriptionIds) {+ List<String> ids = Arrays.asList(subscriptionIds);+ forEach(sessionSubscription -> {+ if (ids.contains(sessionSubscription.subscriptionId)) {+ sessionSubscription.restrictedUser = resstrictedUser;+ sessionSubscription.timestamp = timerService.getCurrentTimeMillis();+ }+ });+ }++ public void cancelByType(String eventType) {removeIf(sessionSubscription -> sessionSubscription.subscription.getEventType().equals(eventType));}++ public void cancelById(String subscriptionId) {+ removeIf(sessionSubscription -> sessionSubscription.subscription.getSubscriptionId().equals(subscriptionId));+ }}class SessionSubscription {- final boolean restrictedUser;- final long timestamp;+ boolean restrictedUser;+ long timestamp;final EventSubscription subscription;+ final String subscriptionId;public SessionSubscription(boolean restrictedUser, long timestamp, EventSubscription subscription) {this.restrictedUser = restrictedUser;this.timestamp = timestamp;this.subscription = subscription;+ this.subscriptionId = subscription.getSubscriptionId();}public boolean matches(boolean accessibleForRestrictedUsers, SharedEvent event) {@@ -94,39 +119,53 @@ public class EventSubscriptions {LOG.info("Starting background task checking for expired event subscriptions from clients");this.timerService = timerService;executorService.scheduleAtFixedRate(() -> {- synchronized (this.sessionSubscriptions) {- for (SessionSubscriptions subscriptions : sessionSubscriptions.values()) {+ synchronized (this.sessionSubscriptionIdMap) {+ for (SessionSubscriptions subscriptions : sessionSubscriptionIdMap.values()) {subscriptions.removeExpired();}}}, 5000, 1000);}- public void update(String sessionKey, boolean restrictedUser, EventSubscription subscription) {- synchronized (this.sessionSubscriptions) {+ public void createOrUpdate(String sessionKey, boolean restrictedUser, EventSubscription subscription) {+ synchronized (this.sessionSubscriptionIdMap) {// TODO Check if the user can actually subscribe to the events it wants, how do we do that?- LOG.fine("For session '" + sessionKey + "', updating: " + subscription);+ LOG.fine("For session '" + sessionKey + "', creating/updating: " + subscription);SessionSubscriptions sessionSubscriptions =- this.sessionSubscriptions.computeIfAbsent(sessionKey, k -> new SessionSubscriptions());- sessionSubscriptions.update(restrictedUser, subscription);+ this.sessionSubscriptionIdMap.computeIfAbsent(sessionKey, k -> new SessionSubscriptions());+ sessionSubscriptions.createOrUpdate(restrictedUser, subscription);+ }+ }++ public void update(String sessionKey, boolean restrictedUser, String[] subscriptionIds) {+ synchronized (this.sessionSubscriptionIdMap) {+ SessionSubscriptions sessionSubscriptions = this.sessionSubscriptionIdMap.get(sessionKey);+ if (sessionSubscriptions != null) {+ LOG.fine("For session '" + sessionKey + "', updating: " + Arrays.toString(subscriptionIds));+ sessionSubscriptions.update(restrictedUser, subscriptionIds);+ }}}public void cancel(String sessionKey, CancelEventSubscription subscription) {- synchronized (this.sessionSubscriptions) {- if (!this.sessionSubscriptions.containsKey(sessionKey))+ synchronized (this.sessionSubscriptionIdMap) {+ if (!this.sessionSubscriptionIdMap.containsKey(sessionKey))return;LOG.fine("For session '" + sessionKey + "', cancelling: " + subscription);- SessionSubscriptions sessionSubscriptions = this.sessionSubscriptions.get(sessionKey);- sessionSubscriptions.cancel(subscription.getEventType());+ SessionSubscriptions sessionSubscriptions = this.sessionSubscriptionIdMap.get(sessionKey);+ if (TextUtil.isNullOrEmpty(subscription.getSubscriptionId())) {+ sessionSubscriptions.cancelByType(subscription.getEventType());+ } else {+ sessionSubscriptions.cancelById(subscription.getSubscriptionId());+ }}}public void cancelAll(String sessionKey) {- synchronized (this.sessionSubscriptions) {- if (this.sessionSubscriptions.containsKey(sessionKey)) {+ synchronized (this.sessionSubscriptionIdMap) {+ if (this.sessionSubscriptionIdMap.containsKey(sessionKey)) {LOG.fine("Cancelling all subscriptions for session: " + sessionKey);- this.sessionSubscriptions.remove(sessionKey);+ this.sessionSubscriptionIdMap.remove(sessionKey);}}}@@ -141,8 +180,8 @@ public class EventSubscriptions {boolean accessibleForRestrictedUsers = exchange.getIn().getHeader(HEADER_ACCESS_RESTRICTED, false, Boolean.class);Set<Map.Entry<String, SessionSubscriptions>> sessionSubscriptionsSet;- synchronized (this.sessionSubscriptions) {- sessionSubscriptionsSet = new HashSet<>(sessionSubscriptions.entrySet());+ synchronized (this.sessionSubscriptionIdMap) {+ sessionSubscriptionsSet = new HashSet<>(sessionSubscriptionIdMap.entrySet());}for (Map.Entry<String, SessionSubscriptions> entry : sessionSubscriptionsSet) {@@ -157,14 +196,17 @@ public class EventSubscriptions {if (sessionSubscription.subscription.getFilter() == null|| sessionSubscription.subscription.getFilter().apply(event)) {LOG.fine("Creating message for subscribed session '" + sessionKey + "': " + event);++ TriggeredEventSubscription<SharedEvent> triggeredEventSubscription = new TriggeredEventSubscription<>(event, sessionSubscription.subscriptionId);+if (sessionSubscription.subscription.getInternalConsumer() == null) {Message msg = new DefaultMessage();- msg.setBody(event); // Don't copy the event, use same reference+ msg.setBody(triggeredEventSubscription); // Don't copy the event, use same referencemsg.setHeaders(new HashMap<>(exchange.getIn().getHeaders())); // Copy headersmsg.setHeader(WebsocketConstants.SESSION_KEY, sessionKey);messageList.add(msg);} else {- sessionSubscription.subscription.getInternalConsumer().accept(event);+ sessionSubscription.subscription.getInternalConsumer().accept(triggeredEventSubscription);}}}diff --git a/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java b/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.javaindex 4218ef485..9dc98a9d5 100644--- a/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java+++ b/manager/src/main/java/org/openremote/manager/event/EventTypeConverters.java@@ -43,13 +43,14 @@ import org.apache.camel.Converter;import org.apache.camel.Exchange;import org.apache.camel.TypeConverters;import org.openremote.container.Container;-import org.openremote.model.event.shared.CancelEventSubscription;-import org.openremote.model.event.shared.EventSubscription;-import org.openremote.model.event.shared.SharedEvent;-import org.openremote.model.event.shared.UnauthorizedEventSubscription;+import org.openremote.model.event.TriggeredEventSubscription;+import org.openremote.model.event.shared.*;+import org.openremote.model.util.TextUtil;import java.util.logging.Logger;+import static org.openremote.model.event.shared.EventSubscription.SUBSCRIBED_MESSAGE_PREFIX;+public class EventTypeConverters implements TypeConverters {private static final Logger LOG = Logger.getLogger(EventTypeConverters.class.getName());@@ -64,6 +65,15 @@ public class EventTypeConverters implements TypeConverters {return SharedEvent.MESSAGE_PREFIX + Container.JSON.writeValueAsString(event);}+ @Converter+ public String writeTriggeredEventSubscription(TriggeredEventSubscription triggeredEventSubscription, Exchange exchange) throws Exception {+ if (!TextUtil.isNullOrEmpty(triggeredEventSubscription.getSubscriptionId())) {+ return SharedEvent.MESSAGE_PREFIX + triggeredEventSubscription.getSubscriptionId() + ":" + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvent());+ }++ return SharedEvent.MESSAGE_PREFIX + Container.JSON.writeValueAsString(triggeredEventSubscription.getEvent());+ }+@Converterpublic SharedEvent readEvent(String string, Exchange exchange) throws Exception {if (!string.startsWith(SharedEvent.MESSAGE_PREFIX))@@ -72,6 +82,11 @@ public class EventTypeConverters implements TypeConverters {return Container.JSON.readValue(string, SharedEvent.class);}+ @Converter+ public String writeEventSubscription(EventSubscription eventSubscription, Exchange exchange) throws Exception {+ return SUBSCRIBED_MESSAGE_PREFIX + Container.JSON.writeValueAsString(eventSubscription);+ }+@Converterpublic EventSubscription readEventSubscription(String string, Exchange exchange) throws Exception {if (!string.startsWith(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX))@@ -92,4 +107,12 @@ public class EventTypeConverters implements TypeConverters {public String writeUnauthorizedEventSubscription(UnauthorizedEventSubscription unauthorizedEventSubscription, Exchange exchange) throws Exception {return UnauthorizedEventSubscription.MESSAGE_PREFIX + Container.JSON.writeValueAsString(unauthorizedEventSubscription);}++ @Converter+ public RenewEventSubscriptions readRenewEventSubscriptions(String string, Exchange exchange) throws Exception {+ if (!string.startsWith(RenewEventSubscriptions.MESSAGE_PREFIX))+ return null;+ string = string.substring(RenewEventSubscriptions.MESSAGE_PREFIX.length());+ return Container.JSON.readValue(string, RenewEventSubscriptions.class);+ }}\ No newline at end of filediff --git a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.javaindex b4c9c170a..6a99f22c5 100644--- a/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java+++ b/model/src/main/java/org/openremote/model/attribute/AttributeEvent.java@@ -67,21 +67,21 @@ public class AttributeEvent extends SharedEvent {public static final String FILTER_TYPE = "attribute-entity-id";- protected String[] entityId = new String[0];+ protected String[] entityIds = new String[0];protected EntityIdFilter() {}- public EntityIdFilter(String... entityId) {- this.entityId = entityId;+ public EntityIdFilter(String... entityIds) {+ this.entityIds = entityIds;}- public String[] getEntityId() {- return entityId;+ public String[] getEntityIds() {+ return entityIds;}- public void setEntityId(String[] entityId) {- this.entityId = entityId;+ public void setEntityIds(String[] entityIds) {+ this.entityIds = entityIds;}@Override@@ -91,13 +91,13 @@ public class AttributeEvent extends SharedEvent {@Overridepublic boolean apply(AttributeEvent event) {- return Arrays.asList(entityId).contains(event.getEntityId());+ return Arrays.asList(entityIds).contains(event.getEntityId());}@Overridepublic String toString() {return getClass().getSimpleName() + "{" +- "entityId='" + Arrays.toString(entityId) + '\'' ++ "entityIds='" + Arrays.toString(entityIds) + '\'' +'}';}}diff --git a/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java b/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.javanew file mode 100644index 000000000..29f09bb71--- /dev/null+++ b/model/src/main/java/org/openremote/model/event/TriggeredEventSubscription.java@@ -0,0 +1,52 @@+/*+ * Copyright 2019, 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.event;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;+import org.openremote.model.event.shared.SharedEvent;++public class TriggeredEventSubscription<E extends SharedEvent> {++ protected E event;+ protected String subscriptionId;++ @JsonCreator+ public TriggeredEventSubscription(@JsonProperty("event") E event, @JsonProperty("subscriptionId") String subscriptionId) {+ this.event = event;+ this.subscriptionId = subscriptionId;+ }++ public E getEvent() {+ return event;+ }++ public String getSubscriptionId() {+ return subscriptionId;+ }++ @Override+ public String toString() {+ return "TriggeredEventSubscription{" ++ "event=" + event ++ ", subscriptionId='" + subscriptionId + '\'' ++ '}';+ }+}diff --git a/model/src/main/java/org/openremote/model/event/shared/CancelEventSubscription.java b/model/src/main/java/org/openremote/model/event/shared/CancelEventSubscription.javaindex 5f1e5c8fb..5f02e3265 100644--- a/model/src/main/java/org/openremote/model/event/shared/CancelEventSubscription.java+++ b/model/src/main/java/org/openremote/model/event/shared/CancelEventSubscription.java@@ -23,30 +23,31 @@ import org.openremote.model.event.Event;/*** A client can unsubscribe from {@link SharedEvent}s on the server, providing the- * type of event it doesn't want to receive anymore+ * type of event it doesn't want to receive anymore or the subscription ID to remove+ * a specific subscriber.*/-// TODO: Remove eventType once manager updated to use new UI componentspublic class CancelEventSubscription<E extends SharedEvent> {public static final String MESSAGE_PREFIX = "UNSUBSCRIBE:";protected String eventType;- protected Long subscriptionId;+ protected String subscriptionId;protected CancelEventSubscription() {}- public CancelEventSubscription(Long subscriptionId) {+ public CancelEventSubscription(String eventType, String subscriptionId) {+ this.eventType = eventType;this.subscriptionId = subscriptionId;}- public CancelEventSubscription(String eventType) {- this.eventType = eventType;+ public CancelEventSubscription(Class<E> eventClass) {+ this(Event.getEventType(eventClass), null);}- public CancelEventSubscription(Class<E> eventClass) {- this(Event.getEventType(eventClass));+ public CancelEventSubscription(Class<E> eventClass, String subscriptionId) {+ this(Event.getEventType(eventClass), subscriptionId);}public String getEventType() {@@ -57,14 +58,10 @@ public class CancelEventSubscription<E extends SharedEvent> {this.eventType = eventType;}- public Long getSubscriptionId() {+ public String getSubscriptionId() {return subscriptionId;}- public void setSubscriptionId(Long subscriptionId) {- this.subscriptionId = subscriptionId;- }-@Overridepublic String toString() {return getClass().getSimpleName() + "{" +diff --git a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.javaindex 7de3a690f..2e0eb9ce8 100644--- a/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java+++ b/model/src/main/java/org/openremote/model/event/shared/EventSubscription.java@@ -20,6 +20,7 @@package org.openremote.model.event.shared;import org.openremote.model.event.Event;+import org.openremote.model.event.TriggeredEventSubscription;import java.util.function.Consumer;@@ -30,6 +31,9 @@ import java.util.function.Consumer;* <p>* Subscriptions must be refreshed by the client every {@link #RENEWAL_PERIOD_SECONDS}* or the server will expire and remove the subscription.+ * <p>+ * A subscription can optionally contain a {@link #subscriptionId} which allows a client+ * to have multiple subscriptions for the same event type.*/public class EventSubscription<E extends SharedEvent> {@@ -39,10 +43,12 @@ public class EventSubscription<E extends SharedEvent> {protected String eventType;protected EventFilter<E> filter;+ protected String subscriptionId;+/*** Optional only set when an internal subscription is made*/- protected Consumer<E> internalConsumer;+ protected Consumer<TriggeredEventSubscription<E>> internalConsumer;protected EventSubscription() {}@@ -64,12 +70,19 @@ public class EventSubscription<E extends SharedEvent> {this.filter = filter;}- public EventSubscription(Class<E> eventClass, EventFilter<E> filter, Consumer<E> internalConsumer) {+ public EventSubscription(Class<E> eventClass, EventFilter<E> filter, Consumer<TriggeredEventSubscription<E>> internalConsumer) {this.eventType = Event.getEventType(eventClass);this.filter = filter;this.internalConsumer = internalConsumer;}+ public EventSubscription(Class<E> eventClass, EventFilter<E> filter, String subscriptionId, Consumer<TriggeredEventSubscription<E>> internalConsumer) {+ this.eventType = Event.getEventType(eventClass);+ this.filter = filter;+ this.subscriptionId = subscriptionId;+ this.internalConsumer = internalConsumer;+ }+public String getEventType() {return eventType;}@@ -90,15 +103,20 @@ public class EventSubscription<E extends SharedEvent> {return Event.getEventType(eventClass).equals(getEventType());}- public Consumer<E> getInternalConsumer() {+ public Consumer<TriggeredEventSubscription<E>> getInternalConsumer() {return internalConsumer;}+ public String getSubscriptionId() {+ return subscriptionId;+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +"eventType='" + eventType + '\'' +", filter=" + filter ++ "subscriptionId='" + subscriptionId + '\'' +'}';}}diff --git a/model/src/main/java/org/openremote/model/event/shared/RenewEventSubscriptions.java b/model/src/main/java/org/openremote/model/event/shared/RenewEventSubscriptions.javanew file mode 100644index 000000000..7457ea64a--- /dev/null+++ b/model/src/main/java/org/openremote/model/event/shared/RenewEventSubscriptions.java@@ -0,0 +1,39 @@+/*+ * Copyright 2019, 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.event.shared;++import com.fasterxml.jackson.annotation.JsonCreator;+import com.fasterxml.jackson.annotation.JsonProperty;++public class RenewEventSubscriptions {++ public static final String MESSAGE_PREFIX = "RENEW:";++ protected String[] subscriptionIds;++ @JsonCreator+ public RenewEventSubscriptions(@JsonProperty("subscriptionIds") String[] subscriptionIds) {+ this.subscriptionIds = subscriptionIds;+ }++ public String[] getSubscriptionIds() {+ return subscriptionIds;+ }+}diff --git a/model/src/main/java/org/openremote/model/event/shared/UnauthorizedEventSubscription.java b/model/src/main/java/org/openremote/model/event/shared/UnauthorizedEventSubscription.javaindex abd95bee6..8c74fc42f 100644--- a/model/src/main/java/org/openremote/model/event/shared/UnauthorizedEventSubscription.java+++ b/model/src/main/java/org/openremote/model/event/shared/UnauthorizedEventSubscription.java@@ -19,8 +19,6 @@*/package org.openremote.model.event.shared;-import org.openremote.model.event.Event;-/*** The server returns this message when an {@link EventSubscription} failed.* <p>@@ -32,31 +30,23 @@ public class UnauthorizedEventSubscription<E extends SharedEvent> {public static final String MESSAGE_PREFIX = "UNAUTHORIZED:";- protected String eventType;+ protected EventSubscription subscription;protected UnauthorizedEventSubscription() {}- public UnauthorizedEventSubscription(String eventType) {- this.eventType = eventType;- }-- public UnauthorizedEventSubscription(Class<E> eventClass) {- this(Event.getEventType(eventClass));- }-- public String getEventType() {- return eventType;+ public UnauthorizedEventSubscription(EventSubscription subscription) {+ this.subscription = subscription;}- public void setEventType(String eventType) {- this.eventType = eventType;+ public EventSubscription getSubscription() {+ return subscription;}@Overridepublic String toString() {- return getClass().getSimpleName() + "{" +- "eventType='" + eventType + '\'' +- '}';+ return "UnauthorizedEventSubscription{" ++ "subscription=" + subscription ++ '}';}}diff --git a/test/src/main/groovy/org/openremote/test/ClientEventService.groovy b/test/src/main/groovy/org/openremote/test/ClientEventService.groovyindex 6a8e507ce..3ca875e54 100644--- a/test/src/main/groovy/org/openremote/test/ClientEventService.groovy+++ b/test/src/main/groovy/org/openremote/test/ClientEventService.groovy@@ -52,18 +52,34 @@ class ClientEventService implements EventService {if (data.startsWith(UnauthorizedEventSubscription.MESSAGE_PREFIX)) {data = data.substring(UnauthorizedEventSubscription.MESSAGE_PREFIX.length())UnauthorizedEventSubscription failure = objectMapper.readValue(data, UnauthorizedEventSubscription.class)- eventBus.dispatch(new SubscriptionFailureEvent(failure.getEventType()))+ eventBus.dispatch(new SubscriptionFailureEvent(failure.subscription.getEventType()))} else if (data.startsWith(SharedEvent.MESSAGE_PREFIX)) {data = data.substring(SharedEvent.MESSAGE_PREFIX.length())- if (data.startsWith("[")) {++ if (data.startsWith("{")) {+ SharedEvent event = objectMapper.readValue(data, SharedEvent.class)+ eventBus.dispatch(event)+ } else if (data.startsWith("[")) {// Handle array of eventsSharedEvent[] events = objectMapper.readValue(data, SharedEvent[].class)for (SharedEvent event : events) {eventBus.dispatch(event)}} else {- SharedEvent event = objectMapper.readValue(data, SharedEvent.class)- eventBus.dispatch(event)+ String[] dataArr = data.split(":(.+)")+ if (dataArr.length == 2) {+ String subscriptionId = dataArr[0]+ if (dataArr[1].startsWith("[")) {+ // Handle array of events+ SharedEvent[] events = objectMapper.readValue(data, SharedEvent[].class)+ for (SharedEvent event : events) {+ eventBus.dispatch(event)+ }+ } else {+ SharedEvent event = objectMapper.readValue(data, SharedEvent.class)+ eventBus.dispatch(event)+ }+ }}}} catch (Throwable t) {diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex 34e8c5422..0c13ae48e 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -141,17 +141,23 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {true,false,false,+ false,+ false,null))put("push", new ConsoleProvider("fcm",true,true,+ true,+ true,false,(ObjectValue) parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)))}- })+ },+ "",+ ["manager"] as String)def returnedConsoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)def consoleId = returnedConsoleRegistration.getId()def console = assetStorageService.find(consoleId, true)@@ -189,8 +195,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {"Test 1.0",false,false,+ false,+ false,true,- null+ null,))returnedConsoleRegistration = authenticatedConsoleResource.register(null, returnedConsoleRegistration)console = assetStorageService.find(consoleId, true)@@ -291,7 +299,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {}.orElse(null) == "23123213ad2313b0897efd"when: "an invalid console registration is registered"- def invalidRegistration = new ConsoleRegistration(null, null, "1.0", null, null)+ def invalidRegistration = new ConsoleRegistration(null, null, "1.0", null, null, null, null)authenticatedConsoleResource.register(null, invalidRegistration)then: "the result should be bad request"diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovyindex 744e8ffc5..5753080f6 100644--- a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy+++ b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy@@ -191,14 +191,14 @@ class ClientEventTest extends Specification implements ManagerContainerTrait, Gwand: "an internal attribute event subscription is made"List<AttributeEvent> internalReceivedEvents = []- internalClientEventService.getEventSubscriptions().update(+ internalClientEventService.getEventSubscriptions().createOrUpdate(ClientEventTest.class.getName(),false,new EventSubscription<>(AttributeEvent.class,new AttributeEvent.EntityIdFilter(managerDemoSetup.thingId),- { attributeEvent ->- internalReceivedEvents.add(attributeEvent as AttributeEvent)+ { triggeredEventSubscription ->+ internalReceivedEvents.add(triggeredEventSubscription.event as AttributeEvent)}))diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovyindex e969f89c4..e9e80724b 100644--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy@@ -134,27 +134,33 @@ class NotificationTest extends Specification implements ManagerContainerTrait {when: "various consoles are registered"def consoleRegistration = new ConsoleRegistration(null,- "Test Console",- "1.0",- "Android 7.0",- new HashMap<String, ConsoleProvider>() {- {- put("geofence", new ConsoleProvider(- ORConsoleGeofenceAssetAdapter.NAME,- true,- false,- false,- null- ))- put("push", new ConsoleProvider(- "fcm",- true,- true,- false,- (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)- ))- }- })+ "Test Console",+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ false,+ false,+ null+ ))+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ true,+ true,+ false,+ (ObjectValue) parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)+ ))+ }+ },+ "",+ ["manager"] as String)def testuser2Console = testuser2ConsoleResource.register(null, consoleRegistration)def testuser3Console1 = testuser3ConsoleResource.register(null, consoleRegistration)def testuser3Console2 = testuser3ConsoleResource.register(null, consoleRegistration)@@ -189,7 +195,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {ex.response.status == 403when: "the admin user sends a notification to a user in a different realm"- notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.realmAUser)+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)advancePseudoClock(1, TimeUnit.HOURS, container)adminNotificationResource.sendNotification(null, notification)@@ -197,7 +203,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {notificationIds.size() == 5when: "a regular user sends a push notification to a user in a different realm"- notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.realmAUser)+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)testuser1NotificationResource.sendNotification(null, notification)then: "access should be forbidden"@@ -205,7 +211,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {ex.response.status == 403when: "a restricted user sends a push notification to another user in the same realm"- notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.realmAUser)+ notification.targets = new Notification.Targets(Notification.TargetType.USER, keycloakDemoSetup.testuser2Id)testuser3NotificationResource.sendNotification(null, notification)then: "access should be forbidden"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.groovyindex 67aff4815..4ab92191a 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@@ -120,17 +120,23 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {true,false,false,+ false,+ false,null))put("push", new ConsoleProvider("fcm",true,true,+ true,+ true,false,(ObjectValue) parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)))}- })+ },+ "",+ ["manager"] as String[])consoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)then: "the console should have been registered"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 6617ac7a2..b9ccc2a3f 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@@ -4,7 +4,6 @@ import com.google.common.collect.Listsimport com.google.firebase.messaging.Messageimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesService@@ -17,7 +16,10 @@ import org.openremote.model.attribute.AttributeRefimport org.openremote.model.console.ConsoleProviderimport org.openremote.model.console.ConsoleRegistrationimport org.openremote.model.console.ConsoleResource-import org.openremote.model.notification.*+import org.openremote.model.notification.AbstractNotificationMessage+import org.openremote.model.notification.Notification+import org.openremote.model.notification.NotificationSendResult+import org.openremote.model.notification.PushNotificationMessageimport org.openremote.model.rules.AssetRulesetimport org.openremote.model.rules.Rulesetimport org.openremote.model.value.ObjectValue@@ -66,7 +68,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCodef conditions = new PollingConditions(timeout: 20, delay: 1)def serverPort = findEphemeralPort()def services = Lists.newArrayList(defaultServices())- services.removeIf {it instanceof PushNotificationHandler}+ services.removeIf { it instanceof PushNotificationHandler }services.add(mockPushNotificationHandler)def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -114,27 +116,33 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCowhen: "a console is registered by the test user"def consoleRegistration = new ConsoleRegistration(null,- "Test Console",- "1.0",- "Android 7.0",- new HashMap<String, ConsoleProvider>() {- {- put("geofence", new ConsoleProvider(- ORConsoleGeofenceAssetAdapter.NAME,- true,- false,- false,- null- ))- put("push", new ConsoleProvider(- "fcm",- true,- true,- false,- (ObjectValue)parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)- ))- }- })+ "Test Console",+ "1.0",+ "Android 7.0",+ new HashMap<String, ConsoleProvider>() {+ {+ put("geofence", new ConsoleProvider(+ ORConsoleGeofenceAssetAdapter.NAME,+ true,+ false,+ false,+ false,+ false,+ null+ ))+ put("push", new ConsoleProvider(+ "fcm",+ true,+ true,+ true,+ true,+ false,+ (ObjectValue) parse("{token: \"23123213ad2313b0897efd\"}").orElse(null)+ ))+ }+ },+ "",+ ["manager"] as String)def returnedConsoleRegistration = authenticatedConsoleResource.register(null, consoleRegistration)then: "the console should be registered"