-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathSession.java
More file actions
440 lines (398 loc) · 16.1 KB
/
Session.java
File metadata and controls
440 lines (398 loc) · 16.1 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package eu.chargetime.ocpp;
/*
ChargeTime.eu - Java-OCA-OCPP
Copyright (C) 2015-2016 Thomas Volden <tv@chargetime.eu>
MIT License
Copyright (C) 2016-2018 Thomas Volden
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import static eu.chargetime.ocpp.ProtocolVersion.OCPP1_6;
import static eu.chargetime.ocpp.ProtocolVersion.OCPP2_0_1;
import eu.chargetime.ocpp.feature.Feature;
import eu.chargetime.ocpp.model.Confirmation;
import eu.chargetime.ocpp.model.Request;
import eu.chargetime.ocpp.utilities.MoreObjects;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Unites outgoing {@link Request} with incoming {@link Confirmation}s or errors. Catches errors and
* responds with error messages.
*/
public class Session implements ISession {
private static final Logger logger = LoggerFactory.getLogger(Session.class);
private final UUID sessionId = UUID.randomUUID();
private final Communicator communicator;
private final Queue queue;
private final RequestDispatcher dispatcher;
private final IFeatureRepository featureRepository;
private final Map<String, SimpleImmutableEntry<String, CompletableFuture<Confirmation>>>
pendingPromises = new ConcurrentHashMap<>();
private SessionEvents events;
/**
* Handles required injections.
*
* @param communicator send and receive messages.
* @param queue store and restore requests based on unique ids.
* @param fulfiller the {@link PromiseFulfiller} to use
* @param featureRepository the {@link IFeatureRepository} to use
*/
public Session(
Communicator communicator,
Queue queue,
PromiseFulfiller fulfiller,
IFeatureRepository featureRepository) {
this.communicator = communicator;
this.queue = queue;
this.dispatcher = new RequestDispatcher(fulfiller);
this.featureRepository = featureRepository;
}
/**
* Get the {@link FeatureRepository} used in this session
*
* @return the {@link FeatureRepository} used in this session
*/
@Override
public IFeatureRepository getFeatureRepository() {
return featureRepository;
}
/**
* Get a unique session {@link UUID} identifier.
*
* @return the unique session {@link UUID} identifier
*/
public UUID getSessionId() {
return sessionId;
}
/**
* Send a {@link Request}.
*
* @param action action name to identify the feature.
* @param payload the {@link Request} payload to send
* @param uuid unique identification to identify the request
*/
public void sendRequest(String action, Request payload, String uuid) {
communicator.sendCall(uuid, action, payload);
}
/**
* Send a {@link Request} which has no confirmation.
*
* @param action action name to identify the feature.
* @param payload the {@link Request} payload to send
* @param uuid unique identification to identify the request
*/
public void sendMessage(String action, Request payload, String uuid) {
if (isSendCapableRPC()) {
communicator.send(uuid, action, payload);
events.handleConfirmation(uuid, null);
} else {
events.handleError(
uuid,
"MessageTypeNotSupported",
"SEND message type is not supported in " + featureRepository.getProtocolVersion(),
payload);
}
}
/**
* Store a {@link Request} and get the unique id.
*
* @param payload the {@link Request} payload to send
* @return unique identification to identify the request.
*/
public String storeRequest(Request payload) {
return queue.store(payload);
}
/**
* Remove a stored {@link Request} using a unique identifier. If no request is found for the
* identifier this method has no effect.
*
* @param ticket unique identifier returned when {@link Request} was initially stored.
*/
public void removeRequest(String ticket) {
queue.removeRequest(ticket);
}
/**
* Send a {@link Confirmation} to a {@link Request}
*
* @param uniqueId the unique identification the receiver expects.
* @param action action name to identify the feature.
* @param confirmation the {@link Confirmation} payload to send.
*/
public void sendConfirmation(String uniqueId, String action, Confirmation confirmation) {
communicator.sendCallResult(uniqueId, action, confirmation);
}
private Optional<Class<? extends Confirmation>> getConfirmationType(String uniqueId)
throws UnsupportedFeatureException {
Optional<Request> requestOptional = queue.restoreRequest(uniqueId);
if (requestOptional.isPresent()) {
Optional<Feature> featureOptional = featureRepository.findFeature(requestOptional.get());
if (featureOptional.isPresent()) {
return Optional.ofNullable(featureOptional.get().getConfirmationType());
} else {
logger.debug("Feature for request with id: {} not found in session: {}", uniqueId, this);
throw new UnsupportedFeatureException(
"Error with getting confirmation type by request id = " + uniqueId);
}
} else {
logger.debug("Request with id: {} not found in session: {}", uniqueId, this);
}
return Optional.empty();
}
/**
* Connect to a specific uri, provided a call back handler for connection related events.
*
* @param uri url and port of the remote system.
* @param eventHandler call back handler for connection related events.
*/
public void open(String uri, SessionEvents eventHandler) {
this.events = eventHandler;
dispatcher.setEventHandler(eventHandler);
communicator.connect(uri, new CommunicatorEventHandler());
}
/** Close down the connection. */
public void close() {
communicator.disconnect();
}
public void accept(SessionEvents eventHandler) {
this.events = eventHandler;
dispatcher.setEventHandler(eventHandler);
communicator.accept(new CommunicatorEventHandler());
}
private class CommunicatorEventHandler implements CommunicatorEvents {
private static final String OCCURRENCE_CONSTRAINT_VIOLATION =
"Payload for Action is syntactically correct but at least one of the fields violates"
+ " occurrence constraints";
private static final String PROPERTY_CONSTRAINT_VIOLATION =
"Payload is syntactically correct but at least one field contains an invalid value";
private static final String INTERNAL_ERROR =
"An internal error occurred and the receiver was not able to process the requested Action"
+ " successfully";
private static final String UNABLE_TO_PROCESS = "Unable to process action";
@Override
public void onCallResult(String id, String action, Object payload) {
try {
Optional<Class<? extends Confirmation>> confirmationTypeOptional = getConfirmationType(id);
if (confirmationTypeOptional.isPresent()) {
Confirmation confirmation =
communicator.unpackPayload(payload, confirmationTypeOptional.get());
if (confirmation.validate()) {
events.handleConfirmation(id, confirmation);
} else {
logger.warn(PROPERTY_CONSTRAINT_VIOLATION);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(
id, action, "PropertyConstraintViolation", PROPERTY_CONSTRAINT_VIOLATION);
}
}
} else {
logger.warn(INTERNAL_ERROR);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(id, action, "InternalError", INTERNAL_ERROR);
}
}
} catch (OccurenceConstraintException ex) {
logger.warn(ex.getMessage(), ex);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(
id, action, "OccurrenceConstraintViolation", ex.getMessage());
}
} catch (PropertyConstraintException ex) {
logger.warn(ex.getMessage(), ex);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(
id, action, "PropertyConstraintViolation", ex.getMessage());
}
} catch (SecurityErrorException ex) {
logger.warn(ex.getMessage(), ex);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(id, action, "SecurityError", ex.getMessage());
}
} catch (UnsupportedFeatureException ex) {
logger.warn(ex.getMessage(), ex);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(id, action, "NotSupported", ex.getMessage());
}
} catch (Exception ex) {
logger.warn(ex.getMessage(), ex);
if (isCallResultErrorCapableRPC()) {
communicator.sendCallResultError(
id, action, "InternalError", ex.getClass().getSimpleName() + ": " + ex.getMessage());
}
}
}
@Override
public void onCall(String id, String action, Object payload) {
Optional<Feature> featureOptional = featureRepository.findFeature(action);
if (!featureOptional.isPresent() || featureOptional.get().getConfirmationType() == null) {
communicator.sendCallError(
id, action, "NotImplemented", "Requested Action is not known by receiver");
} else {
try {
Request request =
communicator.unpackPayload(payload, featureOptional.get().getRequestType());
request.setOcppMessageId(id);
if (request.validate()) {
CompletableFuture<Confirmation> promise = new CompletableFuture<>();
promise.whenComplete(new ConfirmationHandler(id, action, communicator));
promise.whenComplete((result, error) -> pendingPromises.remove(id));
addPendingPromise(id, action, promise);
dispatcher.handleRequest(promise, request);
} else {
communicator.sendCallError(
id,
action,
isLegacyRPC() ? "OccurenceConstraintViolation" : "OccurrenceConstraintViolation",
OCCURRENCE_CONSTRAINT_VIOLATION);
}
} catch (PropertyConstraintException ex) {
logger.warn(ex.getMessage(), ex);
communicator.sendCallError(id, action, "TypeConstraintViolation", ex.getMessage());
} catch (SecurityErrorException ex) {
logger.warn(ex.getMessage(), ex);
communicator.sendCallError(id, action, "SecurityError", ex.getMessage());
} catch (Exception ex) {
logger.warn(UNABLE_TO_PROCESS, ex);
communicator.sendCallError(
id,
action,
isLegacyRPC() ? "FormationViolation" : "FormatViolation",
UNABLE_TO_PROCESS);
}
}
}
@Override
public void onError(String id, String errorCode, String errorDescription, Object payload) {
events.handleError(id, errorCode, errorDescription, payload);
}
@Override
public void onCallResultError(
String id, String errorCode, String errorDescription, Object payload) {
if (!isCallResultErrorCapableRPC()) {
logger.warn(
"Received CALLRESULTERROR message type is not supported in {}",
featureRepository.getProtocolVersion());
return;
}
events.handleConfirmationError(id, errorCode, errorDescription, payload);
}
@Override
public void onSend(String id, String action, Object payload) {
if (!isSendCapableRPC()) {
logger.warn(
"Received SEND message type is not supported in {}",
featureRepository.getProtocolVersion());
return;
}
Optional<Feature> featureOptional = featureRepository.findFeature(action);
if (!featureOptional.isPresent() || featureOptional.get().getConfirmationType() != null) {
logger.warn("Requested Action {} is not known by receiver", action);
} else {
try {
Request request =
communicator.unpackPayload(payload, featureOptional.get().getRequestType());
request.setOcppMessageId(id);
if (request.validate()) {
dispatcher.handleRequest(null, request);
} else {
logger.warn("Received SEND message with id {} is invalid: {}", id, request);
}
} catch (PropertyConstraintException | SecurityErrorException ex) {
logger.warn(ex.getMessage(), ex);
} catch (Exception ex) {
logger.warn(UNABLE_TO_PROCESS, ex);
}
}
}
@Override
public void onDisconnected() {
events.handleConnectionClosed();
}
@Override
public void onConnected() {
events.handleConnectionOpened();
}
private boolean isLegacyRPC() {
ProtocolVersion protocolVersion = featureRepository.getProtocolVersion();
return protocolVersion == null || protocolVersion.equals(OCPP1_6);
}
}
private boolean isCallResultErrorCapableRPC() {
ProtocolVersion protocolVersion = featureRepository.getProtocolVersion();
return protocolVersion != null
&& !protocolVersion.equals(OCPP1_6)
&& !protocolVersion.equals(OCPP2_0_1);
}
private boolean isSendCapableRPC() {
ProtocolVersion protocolVersion = featureRepository.getProtocolVersion();
return protocolVersion != null
&& !protocolVersion.equals(OCPP1_6)
&& !protocolVersion.equals(OCPP2_0_1);
}
private void addPendingPromise(
String id, String action, CompletableFuture<Confirmation> promise) {
pendingPromises.put(id, new SimpleImmutableEntry<>(action, promise));
}
@Override
public boolean completePendingPromise(String id, Confirmation confirmation)
throws UnsupportedFeatureException, OccurenceConstraintException {
SimpleImmutableEntry<String, CompletableFuture<Confirmation>> promiseAction =
pendingPromises.remove(id);
if (promiseAction == null) {
return false;
}
// check confirmation type, it has to correspond to original request type
Optional<Feature> featureOptional = featureRepository.findFeature(promiseAction.getKey());
if (featureOptional.isPresent() && featureOptional.get().getConfirmationType() != null) {
if (!featureOptional.get().getConfirmationType().isInstance(confirmation)) {
throw new OccurenceConstraintException();
}
} else {
logger.debug("Feature for confirmation with id: {} not found in session: {}", id, this);
throw new UnsupportedFeatureException(
"Error with getting confirmation type by request id = " + id);
}
promiseAction.getValue().complete(confirmation);
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Session session = (Session) o;
return MoreObjects.equals(sessionId, session.sessionId);
}
@Override
public int hashCode() {
return MoreObjects.hash(sessionId);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("sessionId", sessionId)
.add("communicator", communicator)
.add("queue", queue)
.add("dispatcher", dispatcher)
.add("featureRepository", featureRepository)
.add("events", events)
.toString();
}
}