-
Notifications
You must be signed in to change notification settings - Fork 402
/
EventServlet.java
358 lines (317 loc) · 15.2 KB
/
EventServlet.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*******************************************************************************
* Copyright (c) 2013-2015 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v20.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.bootstrap.demo.servlet;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.servlet.http.HttpServletRequest;
import org.eclipse.jetty.servlets.EventSource;
import org.eclipse.jetty.servlets.EventSourceServlet;
import org.eclipse.leshan.core.request.BootstrapDeleteRequest;
import org.eclipse.leshan.core.request.BootstrapDiscoverRequest;
import org.eclipse.leshan.core.request.BootstrapDownlinkRequest;
import org.eclipse.leshan.core.request.BootstrapRequest;
import org.eclipse.leshan.core.request.BootstrapWriteRequest;
import org.eclipse.leshan.core.request.Identity;
import org.eclipse.leshan.core.response.BootstrapDiscoverResponse;
import org.eclipse.leshan.core.response.LwM2mResponse;
import org.eclipse.leshan.server.bootstrap.BootstrapFailureCause;
import org.eclipse.leshan.server.bootstrap.BootstrapSession;
import org.eclipse.leshan.server.bootstrap.BootstrapSessionListener;
import org.eclipse.leshan.server.bootstrap.LeshanBootstrapServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class EventServlet extends EventSourceServlet {
private static final long serialVersionUID = 1L;
private static final String EVENT_BOOTSTRAP_SESSION = "BSSESSION";
private static final String QUERY_PARAM_ENDPOINT = "ep";
private static final Logger LOG = LoggerFactory.getLogger(EventServlet.class);
private final ObjectMapper objectMapper;
private final Set<LeshanEventSource> eventSources = Collections
.newSetFromMap(new ConcurrentHashMap<LeshanEventSource, Boolean>());
@SuppressWarnings("unused")
private class BootstrapEvent {
public String name;
public String endpoint;
public Date time;
public String message;
public BootstrapEvent(String name, String endpoint, String message) {
this.name = name;
this.endpoint = endpoint;
this.time = new Date();
this.message = message;
}
}
private final BootstrapSessionListener sessionListener = new BootstrapSessionListener() {
@Override
public void sessionInitiated(BootstrapRequest request, Identity clientIdentity) {
try {
String endpointName = request.getEndpointName();
StringBuilder b = new StringBuilder();
b.append("Bootstrap Request from ");
b.append(clientIdentity.getPeerAddress());
if (request.getPreferredContentFormat() != null) {
b.append("\n");
b.append("Preferred Content Format: ");
b.append(request.getPreferredContentFormat().toString());
}
if (!request.getAdditionalAttributes().isEmpty()) {
b.append("\n");
b.append("Additional attributes: ");
b.append(request.getAdditionalAttributes().toString());
}
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("new session", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void unAuthorized(BootstrapRequest request, Identity clientIdentity) {
try {
String endpointName = request.getEndpointName();
StringBuilder b = new StringBuilder();
b.append(clientIdentity);
b.append(" is not allowed to connect.");
b.append("\n");
b.append("(probably bad credentials)");
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("unauthorized", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void authorized(BootstrapSession session) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append(session.getIdentity());
b.append(" is allowed to connect.");
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("authorized", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void noConfig(BootstrapSession session) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("No config to apply to this client.");
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("no config", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstreap Event JSON serialization failed", e);
}
}
@Override
public void sendRequest(BootstrapSession session, BootstrapDownlinkRequest<? extends LwM2mResponse> request) {
try {
if (request instanceof BootstrapDiscoverRequest) {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Send DISCOVER request on ");
b.append(request.getPath().toString());
sendEvent(EVENT_BOOTSTRAP_SESSION, objectMapper.writeValueAsString(
new BootstrapEvent("send discover", endpointName, b.toString())), endpointName);
} else if (request instanceof BootstrapDeleteRequest) {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Send DELETE request on ");
b.append(request.getPath().toString());
sendEvent(EVENT_BOOTSTRAP_SESSION, objectMapper.writeValueAsString(
new BootstrapEvent("send delete", endpointName, b.toString())), endpointName);
} else if (request instanceof BootstrapWriteRequest) {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Send WRITE request on ");
b.append(request.getPath().toString());
b.append(" using ");
b.append(((BootstrapWriteRequest) request).getContentFormat());
b.append('\n');
((BootstrapWriteRequest) request).getNode().appendPrettyNode(b, request.getPath());
sendEvent(EVENT_BOOTSTRAP_SESSION, objectMapper.writeValueAsString(
new BootstrapEvent("send write", endpointName, b.toString())), endpointName);
} else {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Send request: ");
b.append(request.toString());
sendEvent(EVENT_BOOTSTRAP_SESSION, objectMapper.writeValueAsString(
new BootstrapEvent("send request", endpointName, b.toString())), endpointName);
}
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void onResponseSuccess(BootstrapSession session,
BootstrapDownlinkRequest<? extends LwM2mResponse> request, LwM2mResponse response) {
try {
if (request instanceof BootstrapDiscoverResponse) {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Receive DISCOVER reponse\n");
b.append(response.getCode().toString());
b.append(((BootstrapDiscoverResponse) request).getObjectLinks().toString());
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(
new BootstrapEvent("receive success response", endpointName, b.toString())),
endpointName);
} else {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Receive ");
b.append(response.getCode().toString());
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(
new BootstrapEvent("receive success response", endpointName, b.toString())),
endpointName);
}
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void onResponseError(BootstrapSession session, BootstrapDownlinkRequest<? extends LwM2mResponse> request,
LwM2mResponse response) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Receive ");
b.append(response.getCode().toString());
if (response.getErrorMessage() != null) {
b.append("\n");
b.append(response.getErrorMessage());
}
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(
new BootstrapEvent("receive error response", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void onRequestFailure(BootstrapSession session,
BootstrapDownlinkRequest<? extends LwM2mResponse> request, Throwable cause) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Request was not send because of failure : \n");
appendError(cause, b);
sendEvent(EVENT_BOOTSTRAP_SESSION, objectMapper.writeValueAsString(
new BootstrapEvent("request failure", endpointName, b.toString())), endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
public void appendError(Throwable e, StringBuilder b) {
if (e.getMessage() != null) {
b.append(e.getMessage());
} else {
b.append(e.getClass().getSimpleName());
}
if (e.getCause() != null) {
b.append("\ncaused by : ");
this.appendError(e.getCause(), b);
}
}
@Override
public void end(BootstrapSession session) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Bootstrap session finished with success");
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("finished", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
@Override
public void failed(BootstrapSession session, BootstrapFailureCause cause) {
try {
String endpointName = session.getEndpoint();
StringBuilder b = new StringBuilder();
b.append("Bootstrap session failed : ");
b.append(cause.toString());
sendEvent(EVENT_BOOTSTRAP_SESSION,
objectMapper.writeValueAsString(new BootstrapEvent("failed", endpointName, b.toString())),
endpointName);
} catch (JsonProcessingException e) {
LOG.error("Bootstrap Event JSON serialization failed", e);
}
}
};
public EventServlet(LeshanBootstrapServer server) {
server.addListener(sessionListener);
objectMapper = new ObjectMapper();
}
private synchronized void sendEvent(String event, String data, String endpoint) {
if (LOG.isDebugEnabled()) {
LOG.debug("Dispatching {} event from endpoint {}", event, endpoint);
}
for (LeshanEventSource eventSource : eventSources) {
if (eventSource.getEndpoint() == null || eventSource.getEndpoint().equals(endpoint)) {
eventSource.sentEvent(event, data);
}
}
}
@Override
protected EventSource newEventSource(HttpServletRequest req) {
String endpoint = req.getParameter(QUERY_PARAM_ENDPOINT);
return new LeshanEventSource(endpoint);
}
private class LeshanEventSource implements EventSource {
private String endpoint;
private Emitter emitter;
public LeshanEventSource(String endpoint) {
this.endpoint = endpoint;
}
@Override
public void onOpen(Emitter emitter) throws IOException {
this.emitter = emitter;
eventSources.add(this);
}
@Override
public void onClose() {
eventSources.remove(this);
}
public void sentEvent(String event, String data) {
try {
emitter.event(event, data);
} catch (IOException e) {
e.printStackTrace();
onClose();
}
}
public String getEndpoint() {
return endpoint;
}
}
}