-
Notifications
You must be signed in to change notification settings - Fork 2
/
IMDataAdapter.java
301 lines (235 loc) · 9.83 KB
/
IMDataAdapter.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
Copyright (c) Lightstreamer Srl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.lightstreamer.examples.messenger_demo.adapters;
import java.io.File;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.lightstreamer.interfaces.data.DataProviderException;
import com.lightstreamer.interfaces.data.FailureException;
import com.lightstreamer.interfaces.data.ItemEventListener;
import com.lightstreamer.interfaces.data.SmartDataProvider;
import com.lightstreamer.interfaces.data.SubscriptionException;
public class IMDataAdapter implements SmartDataProvider {
private static String LIST = "buddy_list";
private static String USER_PREFIX = "im_";
private static String ME = "me";
private static String NOBODY = "nobody";
/**
* A static map, to be used by the Metadata Adapter to find the data
* adapter instance; this allows the Metadata Adapter to forward client
* messages to the adapter.
* The map allows multiple instances of this Data Adapter to be included
* in different Adapter Sets. Each instance is identified with the name
* of the related Adapter Set; defining multiple instances in the same
* Adapter Set is not allowed.
*/
public static final ConcurrentHashMap<String, IMDataAdapter> feedMap =
new ConcurrentHashMap<String, IMDataAdapter>();
/**
* Private logger; a specific "LS_demos_Logger.Messenger" category
* should be supplied by log4j configuration.
*/
private Logger logger;
/**
* A map containing all active subscriptions to the nicknames;
* it associates each item name with the item handle to be used
* to identify the item towards Lightstreamer Kernel.
* The map also indicates the current set of active users.
*/
private final ConcurrentHashMap<String, Object> subscriptions =
new ConcurrentHashMap<String, Object>();
/**
* Handle to identify the LIST item, as received by Lightstreamer.
*/
private Object listHandle;
/**
* Mutex to tighten subscription list manipulations and updates
* for the LIST items.
*/
private Object listMutex = new Object();
/**
* The listener of updates set by Lightstreamer Kernel.
*/
private ItemEventListener listener;
/**
* Used to enqueue the calls to the listener.
*/
private final ExecutorService executor;
public IMDataAdapter() {
executor = Executors.newSingleThreadExecutor();
}
public void init(Map params, File configDir) throws DataProviderException {
// Logging configuration for the demo is carried out in the init
// method of Metadata Adapter. In order to be sure that this method
// is executed after log configuration was completed, this parameter
// must be present in the Adapter Set configuration (adapters.xml):
// <metadata_adapter_initialised_first>Y</metadata_adapter_initialised_first>
logger = LogManager.getLogger("LS_demos_Logger.Messenger");
// Read the Adapter Set name, which is supplied by the Server as a parameter
String adapterSetId = (String) params.get("adapters_conf.id");
// Put a reference to this instance on a static map
// to be read by the Metadata Adapter
feedMap.put(adapterSetId, this);
// Adapter ready
logger.info("IMDataAdapter ready");
}
public void subscribe(String item, Object handle, boolean needsIterator)
throws SubscriptionException, FailureException {
if (item.equals(LIST)) {
// returns the list of the users currently available,
synchronized (listMutex) {
assert(listHandle == null);
listHandle = handle;
Enumeration<String> keys = subscriptions.keys();
while(keys.hasMoreElements()) {
String user = keys.nextElement();
this.updateList("ADD", user, true);
}
sendListEOS();
}
} else if (item.startsWith(USER_PREFIX)) {
String user = item.substring(USER_PREFIX.length());
assert(! subscriptions.containsKey(user));
synchronized (listMutex) {
// Add the new item to the list of subscribed items
subscriptions.put(user, handle);
this.updateList("ADD", user, false);
}
} else {
throw new SubscriptionException("Unexpected item name: " + item);
}
logger.info(item + " subscribed");
}
public void unsubscribe(String item) throws SubscriptionException,
FailureException {
if (item.equals(LIST)) {
synchronized (listMutex) {
assert(listHandle != null);
listHandle = null;
}
} else if (item.startsWith(USER_PREFIX)) {
String user = item.substring(USER_PREFIX.length());
assert(subscriptions.containsKey(user));
synchronized (listMutex) {
subscriptions.remove(user);
this.updateList("DELETE", user, false);
}
} else {
throw new SubscriptionException("Unexpected item name: " + item);
}
}
public boolean isSnapshotAvailable(String item)
throws SubscriptionException {
if (item.equals(LIST)) {
return true;
}
return false;
}
public void setListener(ItemEventListener listener) {
this.listener = listener;
}
/**
* Accepts message submission with a specified sender and target user
* nicknames.
*/
public void sendMessage(String from, String to, String message) {
if (from.equals(to)) {
Object handle = subscriptions.get(from);
if (handle != null) {
this.sendMessage(ME,ME,message,handle);
}
} else {
Object toHandle = subscriptions.get(to);
Object fromHandle = subscriptions.get(from);
if (toHandle == null) {
if (fromHandle != null) {
this.sendMessage(ME,NOBODY,message,fromHandle);
}
} else {
this.sendMessage(from,ME,message,toHandle);
if (fromHandle != null) {
this.sendMessage(ME,to,message,fromHandle);
}
}
}
}
private void sendMessage(String from, String to, String message, Object handle) {
final Object currHandle = handle;
final HashMap<String, String> update = new HashMap<String, String>();
update.put("fromNick", from);
update.put("toNick", to);
update.put("message", message);
//If we have a listener create a new Runnable to be used as a task to pass the
//new update to the listener
Runnable updateTask = new Runnable() {
public void run() {
// call the update on the listener;
// in case the listener has just been detached,
// the listener should detect the case
listener.smartUpdate(currHandle, update, false);
}
};
//We add the task on the executor to pass to the listener the actual status
executor.execute(updateTask);
}
private void updateList(String command, String key, final boolean isForSnapshot) {
assert(command.equals("ADD") || ! isForSnapshot);
final Object currHandle = listHandle;
if (currHandle == null) {
return;
}
final HashMap<String, String> update = new HashMap<String, String>();
update.put("command", command);
update.put("key", key);
//If we have a listener create a new Runnable to be used as a task to pass the
//new update to the listener
Runnable updateTask = new Runnable() {
public void run() {
// call the update on the listener;
// in case the listener has just been detached,
// the listener should detect the case
listener.smartUpdate(currHandle, update, isForSnapshot);
}
};
//We add the task on the executor to pass to the listener the actual status
executor.execute(updateTask);
}
private void sendListEOS() {
final Object currHandle = listHandle;
if (currHandle == null) {
return;
}
//If we have a listener create a new Runnable to be used as a task to pass the
//new update to the listener
Runnable eosTask = new Runnable() {
public void run() {
// call the update on the listener;
// in case the listener has just been detached,
// the listener should detect the case
listener.smartEndOfSnapshot(currHandle);
}
};
//We add the task on the executor to pass to the listener the actual status
executor.execute(eosTask);
}
public void subscribe(String arg0, boolean arg1)
throws SubscriptionException, FailureException {
//NEVER CALLED
}
}