This repository has been archived by the owner on Sep 21, 2018. It is now read-only.
/
Connection.java
826 lines (670 loc) · 23.9 KB
/
Connection.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
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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/*
Copyright (c) Microsoft Open Technologies, Inc.
All Rights Reserved
See License.txt in the project root for license information.
*/
package microsoft.aspnet.signalr.client;
import java.util.Date;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.transport.AutomaticTransport;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.ConnectionType;
import microsoft.aspnet.signalr.client.transport.DataResultCallback;
import microsoft.aspnet.signalr.client.transport.NegotiationResponse;
import microsoft.aspnet.signalr.client.transport.TransportHelper;
import microsoft.aspnet.signalr.client.Logger;
/**
* Represents a basic SingalR connection
*/
public class Connection implements ConnectionBase {
public static final Version PROTOCOL_VERSION = new Version("1.3");
private Logger mLogger;
private String mUrl;
private String mConnectionToken;
private String mConnectionId;
private String mMessageId;
private String mGroupsToken;
private Credentials mCredentials;
private String mQueryString;
private Map<String, String> mHeaders;
private UpdateableCancellableFuture<Void> mConnectionFuture;
private boolean mAborting = false;
private SignalRFuture<Void> mAbortFuture = new SignalRFuture<Void>();
private Runnable mOnReconnecting;
private Runnable mOnReconnected;
private Runnable mOnConnected;
private MessageReceivedHandler mOnReceived;
private ErrorCallback mOnError;
private Runnable mOnConnectionSlow;
private Runnable mOnClosed;
private StateChangedCallback mOnStateChanged;
private ClientTransport mTransport;
private HeartbeatMonitor mHeartbeatMonitor;
private KeepAliveData mKeepAliveData;
protected ConnectionState mState;
protected JsonParser mJsonParser;
protected Gson mGson;
private Object mStateLock = new Object();
private Object mStartLock = new Object();
/**
* Initializes the connection with an URL
*
* @param url
* The connection URL
*/
public Connection(String url) {
this(url, (String) null);
}
/**
* Initializes the connection with an URL and a query string
*
* @param url
* The connection URL
* @param queryString
* The connection query string
*/
public Connection(String url, String queryString) {
this(url, queryString, new NullLogger());
}
/**
* Initializes the connection with an URL and a logger
*
* @param url
* The connection URL
* @param logger
* The connection logger
*/
public Connection(String url, Logger logger) {
this(url, null, logger);
}
/**
* Initializes the connection with an URL, a query string and a Logger
*
* @param url
* The connection URL
* @param queryString
* The connection query string
* @param logger
* The connection logger
*/
public Connection(String url, String queryString, Logger logger) {
if (url == null) {
throw new IllegalArgumentException("URL cannot be null");
}
if (logger == null) {
throw new IllegalArgumentException("Logger cannot be null");
}
if (!url.endsWith("/")) {
url += "/";
}
log("Initialize the connection", LogLevel.Information);
log("Connection data: " + url + " - " + queryString == null ? "" : queryString, LogLevel.Verbose);
mUrl = url;
mQueryString = queryString;
mLogger = logger;
mJsonParser = new JsonParser();
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
mGson = gsonBuilder.create();
mState = ConnectionState.Disconnected;
}
@Override
public Logger getLogger() {
return mLogger;
}
@Override
public ConnectionState getState() {
return mState;
}
@Override
public String getUrl() {
return mUrl;
}
@Override
public String getConnectionToken() {
return mConnectionToken;
}
@Override
public String getConnectionId() {
return mConnectionId;
}
@Override
public String getQueryString() {
return mQueryString;
}
@Override
public String getMessageId() {
return mMessageId;
}
@Override
public void setMessageId(String messageId) {
mMessageId = messageId;
}
@Override
public String getGroupsToken() {
return mGroupsToken;
}
@Override
public void setGroupsToken(String groupsToken) {
mGroupsToken = groupsToken;
}
@Override
public Map<String, String> getHeaders() {
return mHeaders;
}
@Override
public void reconnecting(Runnable handler) {
mOnReconnecting = handler;
}
@Override
public void reconnected(Runnable handler) {
mOnReconnected = handler;
}
@Override
public void connected(Runnable handler) {
mOnConnected = handler;
}
@Override
public void error(ErrorCallback handler) {
mOnError = handler;
}
@Override
public void received(MessageReceivedHandler handler) {
mOnReceived = handler;
}
@Override
public void connectionSlow(Runnable handler) {
mOnConnectionSlow = handler;
}
@Override
public void closed(Runnable handler) {
mOnClosed = handler;
}
@Override
public void stateChanged(StateChangedCallback handler) {
mOnStateChanged = handler;
}
/**
* Starts the connection using the best available transport
*
* @return A Future for the operation
*/
public SignalRFuture<Void> start() {
return start(new AutomaticTransport(mLogger));
}
/**
* Sends a serialized object
*
* @param object
* The object to send. If the object is a JsonElement, its string
* representation is sent. Otherwise, the object is serialized to
* Json.
* @return A Future for the operation
*/
public SignalRFuture<Void> send(Object object) {
String data = null;
if (object != null) {
if (object instanceof JsonElement) {
data = object.toString();
} else {
data = mGson.toJson(object);
}
}
return send(data);
}
@Override
public SignalRFuture<Void> send(String data) {
log("Sending: " + data, LogLevel.Information);
if (mState == ConnectionState.Disconnected || mState == ConnectionState.Connecting) {
onError(new InvalidStateException(mState), false);
return new SignalRFuture<Void>();
}
final Connection that = this;
log("Invoking send on transport", LogLevel.Verbose);
SignalRFuture<Void> future = mTransport.send(this, data, new DataResultCallback() {
@Override
public void onData(String data) {
that.processReceivedData(data);
}
});
handleFutureError(future, false);
return future;
}
/**
* Handles a Future error, invoking the connection onError event
*
* @param future
* The future to handle
* @param mustCleanCurrentConnection
* True if the connection must be cleaned when an error happens
*/
private void handleFutureError(SignalRFuture<?> future, final boolean mustCleanCurrentConnection) {
final Connection that = this;
future.onError(new ErrorCallback() {
@Override
public void onError(Throwable error) {
that.onError(error, mustCleanCurrentConnection);
}
});
}
@Override
public SignalRFuture<Void> start(final ClientTransport transport) {
synchronized (mStartLock) {
log("Entered startLock in start", LogLevel.Verbose);
if (!changeState(ConnectionState.Disconnected, ConnectionState.Connecting)) {
log("Couldn't change state from disconnected to connecting.", LogLevel.Verbose);
return mConnectionFuture;
}
log("Start the connection, using " + transport.getName() + " transport", LogLevel.Information);
mTransport = transport;
mConnectionFuture = new UpdateableCancellableFuture<Void>(null);
handleFutureError(mConnectionFuture, true);
log("Start negotiation", LogLevel.Verbose);
SignalRFuture<NegotiationResponse> negotiationFuture = transport.negotiate(this);
try {
negotiationFuture.done(new Action<NegotiationResponse>() {
@Override
public void run(NegotiationResponse negotiationResponse) throws Exception {
log("Negotiation completed", LogLevel.Information);
if (!verifyProtocolVersion(negotiationResponse.getProtocolVersion())) {
Exception err = new InvalidProtocolVersionException(negotiationResponse.getProtocolVersion());
onError(err, true);
mConnectionFuture.triggerError(err);
return;
}
mConnectionId = negotiationResponse.getConnectionId();
mConnectionToken = negotiationResponse.getConnectionToken();
log("ConnectionId: " + mConnectionId, LogLevel.Verbose);
log("ConnectionToken: " + mConnectionToken, LogLevel.Verbose);
KeepAliveData keepAliveData = null;
if (negotiationResponse.getKeepAliveTimeout() > 0) {
log("Keep alive timeout: " + negotiationResponse.getKeepAliveTimeout(), LogLevel.Verbose);
keepAliveData = new KeepAliveData((long) (negotiationResponse.getKeepAliveTimeout() * 1000));
}
startTransport(keepAliveData, false);
}
});
negotiationFuture.onError(new ErrorCallback() {
@Override
public void onError(Throwable error) {
mConnectionFuture.triggerError(error);
}
});
} catch (Exception e) {
onError(e, true);
}
handleFutureError(negotiationFuture, true);
mConnectionFuture.setFuture(negotiationFuture);
return mConnectionFuture;
}
}
/**
* Changes the connection state
*
* @param oldState
* The expected old state
* @param newState
* The new state
* @return True, if the state was changed
*/
private boolean changeState(ConnectionState oldState, ConnectionState newState) {
synchronized (mStateLock) {
if (mState == oldState) {
mState = newState;
if (mOnStateChanged != null) {
try {
mOnStateChanged.stateChanged(oldState, newState);
} catch (Throwable e) {
onError(e, false);
}
}
return true;
}
return false;
}
}
@Override
public Credentials getCredentials() {
return mCredentials;
}
@Override
public void setCredentials(Credentials credentials) {
mCredentials = credentials;
}
@Override
public void prepareRequest(Request request) {
if (mCredentials != null) {
log("Preparing request with credentials data", LogLevel.Information);
mCredentials.prepareRequest(request);
}
}
@Override
public String getConnectionData() {
return null;
}
@Override
public void stop() {
synchronized (mStartLock) {
log("Entered startLock in stop", LogLevel.Verbose);
if (mAborting) {
log("Abort already started.", LogLevel.Verbose);
return;
}
if (mState == ConnectionState.Disconnected) {
log("Connection already in disconnected state. Exiting abort", LogLevel.Verbose);
return;
}
log("Stopping the connection", LogLevel.Information);
mAborting = true;
log("Starting abort operation", LogLevel.Verbose);
mAbortFuture = mTransport.abort(this);
final Connection that = this;
mAbortFuture.onError(new ErrorCallback() {
@Override
public void onError(Throwable error) {
synchronized (mStartLock) {
that.onError(error, false);
disconnect();
mAborting = false;
}
}
});
mAbortFuture.onCancelled(new Runnable() {
@Override
public void run() {
synchronized (mStartLock) {
log("Abort cancelled", LogLevel.Verbose);
mAborting = false;
}
}
});
mAbortFuture.done(new Action<Void>() {
@Override
public void run(Void obj) throws Exception {
synchronized (mStartLock) {
log("Abort completed", LogLevel.Information);
disconnect();
mAborting = false;
}
}
});
}
}
@Override
public void disconnect() {
synchronized (mStateLock) {
log("Entered stateLock in disconnect", LogLevel.Verbose);
if (mState == ConnectionState.Disconnected) {
return;
}
log("Disconnecting", LogLevel.Information);
ConnectionState oldState = mState;
mState = ConnectionState.Disconnected;
if (mOnStateChanged != null) {
try {
mOnStateChanged.stateChanged(oldState, ConnectionState.Disconnected);
} catch (Throwable e) {
onError(e, false);
}
}
if (mHeartbeatMonitor != null) {
log("Stopping Heartbeat monitor", LogLevel.Verbose);
mHeartbeatMonitor.stop();
}
mHeartbeatMonitor = null;
if (mConnectionFuture != null) {
log("Stopping the connection", LogLevel.Verbose);
mConnectionFuture.cancel();
mConnectionFuture = new UpdateableCancellableFuture<Void>(null);
}
if (mAbortFuture != null) {
log("Cancelling abort", LogLevel.Verbose);
mAbortFuture.cancel();
}
mConnectionId = null;
mConnectionToken = null;
mCredentials = null;
mGroupsToken = null;
mHeaders = null;
mMessageId = null;
mTransport = null;
onClosed();
}
}
@Override
public Gson getGson() {
return mGson;
}
@Override
public JsonParser getJsonParser() {
return mJsonParser;
}
/**
* Triggers the Reconnecting event
*/
protected void onReconnecting() {
if (mOnReconnecting != null) {
mOnReconnecting.run();
}
}
/**
* Triggers the Reconnected event
*/
protected void onReconnected() {
if (mOnReconnected != null) {
mOnReconnected.run();
}
}
/**
* Triggers the Connected event
*/
protected void onConnected() {
if (mOnConnected != null) {
mOnConnected.run();
}
}
/**
* Verifies the protocol version
*
* @param versionString
* String representing a Version
* @return True if the version is supported.
*/
private static boolean verifyProtocolVersion(String versionString) {
try {
if (versionString == null || versionString.equals("")) {
return false;
}
Version version = new Version(versionString);
return version.equals(PROTOCOL_VERSION);
} catch (Exception e) {
return false;
}
}
/**
* Starts the transport
*
* @param keepAliveData
* Keep Alive data for heartbeat monitor
* @param isReconnecting
* True if is reconnecting
*/
private void startTransport(KeepAliveData keepAliveData, final boolean isReconnecting) {
synchronized (mStartLock) {
log("Entered startLock in startTransport", LogLevel.Verbose);
// if the connection was closed before this callback, just return;
if (mTransport == null) {
log("Transport is null. Exiting startTransport", LogLevel.Verbose);
return;
}
log("Starting the transport", LogLevel.Information);
if (isReconnecting) {
if (mHeartbeatMonitor != null) {
log("Stopping heartbeat monitor", LogLevel.Verbose);
mHeartbeatMonitor.stop();
}
changeState(ConnectionState.Connected, ConnectionState.Reconnecting);
onReconnecting();
}
mHeartbeatMonitor = new HeartbeatMonitor();
mHeartbeatMonitor.setOnWarning(new Runnable() {
@Override
public void run() {
log("Slow connection detected", LogLevel.Information);
if (mOnConnectionSlow != null) {
mOnConnectionSlow.run();
}
}
});
mHeartbeatMonitor.setOnTimeout(new Runnable() {
@Override
public void run() {
log("Timeout", LogLevel.Information);
reconnect();
}
});
final Connection that = this;
ConnectionType connectionType = isReconnecting ? ConnectionType.Reconnection : ConnectionType.InitialConnection;
log("Starting transport for " + connectionType.toString(), LogLevel.Verbose);
SignalRFuture<Void> future = mTransport.start(this, connectionType, new DataResultCallback() {
@Override
public void onData(String data) {
log("Received data: ", LogLevel.Verbose);
processReceivedData(data);
}
});
handleFutureError(future, true);
mConnectionFuture.setFuture(future);
future.onError(new ErrorCallback() {
@Override
public void onError(Throwable error) {
mConnectionFuture.triggerError(error);
}
});
mKeepAliveData = keepAliveData;
try {
future.done(new Action<Void>() {
@Override
public void run(Void obj) throws Exception {
synchronized (mStartLock) {
log("Entered startLock after transport was started", LogLevel.Verbose);
log("Current state: " + mState, LogLevel.Verbose);
if (changeState(ConnectionState.Reconnecting, ConnectionState.Connected)) {
log("Starting Heartbeat monitor", LogLevel.Verbose);
mHeartbeatMonitor.start(mKeepAliveData, that);
log("Reconnected", LogLevel.Information);
onReconnected();
} else if (changeState(ConnectionState.Connecting, ConnectionState.Connected)) {
log("Starting Heartbeat monitor", LogLevel.Verbose);
mHeartbeatMonitor.start(mKeepAliveData, that);
log("Connected", LogLevel.Information);
onConnected();
mConnectionFuture.setResult(null);
}
}
}
});
} catch (Exception e) {
onError(e, false);
}
}
}
/**
* Parses the received data and triggers the OnReceived event
*
* @param data
* The received data
*/
private void processReceivedData(String data) {
if (mHeartbeatMonitor != null) {
mHeartbeatMonitor.beat();
}
MessageResult result = TransportHelper.processReceivedData(data, this);
if (result.disconnect()) {
disconnect();
return;
}
if (result.reconnect()) {
reconnect();
}
}
/**
* Processes a received message
*
* @param message
* The message to process
* @return The processed message
* @throws Exception
* An exception could be thrown if there an error while
* processing the message
*/
protected JsonElement processMessage(JsonElement message) throws Exception {
return message;
}
@Override
public void onError(Throwable error, boolean mustCleanCurrentConnection) {
log(error);
if (mustCleanCurrentConnection) {
if (mState == ConnectionState.Connected) {
log("Triggering reconnect", LogLevel.Verbose);
reconnect();
} else {
log("Triggering disconnect", LogLevel.Verbose);
disconnect();
if (mOnError != null) {
mOnError.onError(error);
}
}
} else {
if (mOnError != null) {
mOnError.onError(error);
}
}
}
/**
* Triggers the Closed event
*/
protected void onClosed() {
if (mOnClosed != null) {
mOnClosed.run();
}
}
/**
* Stops the heartbeat monitor and re-starts the transport
*/
private void reconnect() {
if (mState == ConnectionState.Connected) {
log("Stopping Heartbeat monitor", LogLevel.Verbose);
mHeartbeatMonitor.stop();
log("Restarting the transport", LogLevel.Information);
startTransport(mHeartbeatMonitor.getKeepAliveData(), true);
}
}
protected void log(String message, LogLevel level) {
if (message != null & mLogger != null) {
mLogger.log(getSourceNameForLog() + " - " + message, level);
}
}
protected void log(Throwable error) {
mLogger.log(getSourceNameForLog() + " - Error: " + error.toString(), LogLevel.Critical);
}
protected String getSourceNameForLog() {
return "Connection";
}
@Override
public void onReceived(JsonElement message) {
if (mOnReceived != null && getState() == ConnectionState.Connected) {
log("Invoking messageReceived with: " + message, LogLevel.Verbose);
try {
mOnReceived.onMessageReceived(message);
} catch (Throwable error) {
onError(error, false);
}
}
}
}