This repository has been archived by the owner on May 7, 2020. It is now read-only.
/
SitemapSubscriptionService.java
285 lines (247 loc) · 10.9 KB
/
SitemapSubscriptionService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
/**
* Copyright (c) 2014,2018 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.smarthome.io.rest.sitemap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.commons.lang.StringUtils;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.smarthome.io.rest.sitemap.internal.PageChangeListener;
import org.eclipse.smarthome.io.rest.sitemap.internal.SitemapEvent;
import org.eclipse.smarthome.model.core.EventType;
import org.eclipse.smarthome.model.core.ModelRepositoryChangeListener;
import org.eclipse.smarthome.model.sitemap.LinkableWidget;
import org.eclipse.smarthome.model.sitemap.Sitemap;
import org.eclipse.smarthome.model.sitemap.SitemapProvider;
import org.eclipse.smarthome.model.sitemap.Widget;
import org.eclipse.smarthome.ui.items.ItemUIRegistry;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This is a service that provides the possibility to manage subscriptions to sitemaps.
* As such subscriptions are stateful, they need to be created and removed upon disposal.
* The subscription mechanism makes sure that only events for widgets of the currently active sitemap page are sent as
* events to the subscriber.
* For this to work correctly, the subscriber needs to make sure that setPageId is called whenever it switches to a new
* page.
*
* @author Kai Kreuzer - Initial contribution and API
*/
@Component(service = SitemapSubscriptionService.class)
public class SitemapSubscriptionService implements ModelRepositoryChangeListener {
private static final String SITEMAP_PAGE_SEPARATOR = "#";
private static final String SITEMAP_SUFFIX = ".sitemap";
private final Logger logger = LoggerFactory.getLogger(SitemapSubscriptionService.class);
public interface SitemapSubscriptionCallback {
void onEvent(SitemapEvent event);
}
private ItemUIRegistry itemUIRegistry;
private final List<SitemapProvider> sitemapProviders = new ArrayList<>();
/* subscription id -> sitemap+page */
private final Map<String, String> pageOfSubscription = new ConcurrentHashMap<>();
/* subscription id -> callback */
private final Map<String, SitemapSubscriptionCallback> callbacks = new ConcurrentHashMap<>();
/* sitemap+page -> listener */
private final Map<String, PageChangeListener> pageChangeListeners = new ConcurrentHashMap<>();
public SitemapSubscriptionService() {
}
@Activate
protected void activate() {
}
@Deactivate
protected void deactivate() {
pageOfSubscription.clear();
callbacks.clear();
for (PageChangeListener listener : pageChangeListeners.values()) {
listener.dispose();
}
pageChangeListeners.clear();
}
@Reference
protected void setItemUIRegistry(ItemUIRegistry itemUIRegistry) {
this.itemUIRegistry = itemUIRegistry;
}
protected void unsetItemUIRegistry(ItemUIRegistry itemUIRegistry) {
this.itemUIRegistry = null;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
protected void addSitemapProvider(SitemapProvider provider) {
sitemapProviders.add(provider);
provider.addModelChangeListener(this);
}
protected void removeSitemapProvider(SitemapProvider provider) {
sitemapProviders.remove(provider);
provider.removeModelChangeListener(this);
}
/**
* Creates a new subscription with the given id.
*
* @param callback an instance that should receive the events
* @returns a unique id that identifies the subscription
*/
public String createSubscription(SitemapSubscriptionCallback callback) {
String subscriptionId = UUID.randomUUID().toString();
callbacks.put(subscriptionId, callback);
logger.debug("Created new subscription with id {}", subscriptionId);
return subscriptionId;
}
/**
* Removes an existing subscription
*
* @param subscriptionId the id of the subscription to remove
*/
public void removeSubscription(String subscriptionId) {
callbacks.remove(subscriptionId);
String sitemapPage = pageOfSubscription.remove(subscriptionId);
if (sitemapPage != null && !pageOfSubscription.values().contains(sitemapPage)) {
// this was the only subscription listening on this page, so we can dispose the listener
PageChangeListener listener = pageChangeListeners.remove(sitemapPage);
if (listener != null) {
listener.dispose();
}
}
logger.debug("Removed subscription with id {}", subscriptionId);
}
/**
* Checks whether a subscription with a given id (still) exists.
*
* @param subscriptionId the id of the subscription to check
* @return true, if it exists, false otherwise
*/
public boolean exists(String subscriptionId) {
return callbacks.containsKey(subscriptionId);
}
/**
* Retrieves the current page id for a subscription.
*
* @param subscriptionId the subscription to get the page id for
* @return the id of the currently active page
*/
public String getPageId(String subscriptionId) {
return extractPageId(pageOfSubscription.get(subscriptionId));
}
/**
* Retrieves the current sitemap name for a subscription.
*
* @param subscriptionId the subscription to get the sitemap name for
* @return the name of the current sitemap
*/
public String getSitemapName(String subscriptionId) {
return extractSitemapName(pageOfSubscription.get(subscriptionId));
}
private String extractSitemapName(String sitemapWithPageId) {
return sitemapWithPageId.split(SITEMAP_PAGE_SEPARATOR)[0];
}
private String extractPageId(String sitemapWithPageId) {
return sitemapWithPageId.split(SITEMAP_PAGE_SEPARATOR)[1];
}
/**
* Updates the subscription to send events for the provided page id.
*
* @param subscriptionId the subscription to update
* @param sitemapName the current sitemap name
* @param pageId the current page id
*/
public void setPageId(String subscriptionId, String sitemapName, String pageId) {
SitemapSubscriptionCallback callback = callbacks.get(subscriptionId);
if (callback != null) {
String oldSitemapPage = pageOfSubscription.remove(subscriptionId);
if (oldSitemapPage != null) {
removeCallbackFromListener(oldSitemapPage, callback);
}
addCallbackToListener(sitemapName, pageId, callback);
pageOfSubscription.put(subscriptionId, getValue(sitemapName, pageId));
logger.debug("Subscription {} changed to page {} of sitemap {}",
new Object[] { subscriptionId, pageId, sitemapName });
} else {
throw new IllegalArgumentException("Subscription " + subscriptionId + " does not exist!");
}
}
private void addCallbackToListener(String sitemapName, String pageId, SitemapSubscriptionCallback callback) {
PageChangeListener listener = pageChangeListeners.get(getValue(sitemapName, pageId));
if (listener == null) {
// there is no listener for this page yet, so let's try to create one
listener = new PageChangeListener(sitemapName, pageId, itemUIRegistry, collectWidgets(sitemapName, pageId));
pageChangeListeners.put(getValue(sitemapName, pageId), listener);
}
if (listener != null) {
listener.addCallback(callback);
}
}
private EList<Widget> collectWidgets(String sitemapName, String pageId) {
EList<Widget> widgets = new BasicEList<Widget>();
Sitemap sitemap = getSitemap(sitemapName);
if (sitemap != null) {
if (pageId.equals(sitemap.getName())) {
widgets = itemUIRegistry.getChildren(sitemap);
} else {
Widget pageWidget = itemUIRegistry.getWidget(sitemap, pageId);
if (pageWidget instanceof LinkableWidget) {
widgets = itemUIRegistry.getChildren((LinkableWidget) pageWidget);
// We add the page widget. It will help any UI to update the page title.
widgets.add(pageWidget);
}
}
}
return widgets;
}
private void removeCallbackFromListener(String sitemapPage, SitemapSubscriptionCallback callback) {
PageChangeListener oldListener = pageChangeListeners.get(sitemapPage);
if (oldListener != null) {
oldListener.removeCallback(callback);
if (!pageOfSubscription.values().contains(sitemapPage)) {
// no other callbacks are left here, so we can safely dispose the listener
oldListener.dispose();
pageChangeListeners.remove(sitemapPage);
}
}
}
private String getValue(String sitemapName, String pageId) {
return sitemapName + SITEMAP_PAGE_SEPARATOR + pageId;
}
private Sitemap getSitemap(String sitemapName) {
for (SitemapProvider provider : sitemapProviders) {
Sitemap sitemap = provider.getSitemap(sitemapName);
if (sitemap != null) {
return sitemap;
}
}
return null;
}
@Override
public void modelChanged(String modelName, EventType type) {
if (type != EventType.MODIFIED || !modelName.endsWith(SITEMAP_SUFFIX)) {
return; // we process only sitemap modifications here
}
String changedSitemapName = StringUtils.removeEnd(modelName, SITEMAP_SUFFIX);
for (Entry<String, PageChangeListener> listenerEntry : pageChangeListeners.entrySet()) {
String sitemapWithPage = listenerEntry.getKey();
String sitemapName = extractSitemapName(sitemapWithPage);
String pageId = extractPageId(sitemapWithPage);
if (sitemapName.equals(changedSitemapName)) {
EList<Widget> widgets = collectWidgets(sitemapName, pageId);
listenerEntry.getValue().sitemapContentChanged(widgets);
}
}
}
}