Repository navigation
Expand file tree
/
Copy pathPubnub.java
More file actions
1529 lines (1372 loc) · 51 KB
/
Copy pathPubnub.java
File metadata and controls
1529 lines (1372 loc) · 51 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
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
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.pubnub.api;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.zip.GZIPInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.Mac;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class Request {
private String url;
private Hashtable headers;
private int requestTimeout;
private int connectionTimeout;
public void setRequestTimeout(int requestTimeout) {
this.requestTimeout = requestTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public void setUrl(String url) {
this.url = url;
}
public void setHeaders(Hashtable headers) {
this.headers = headers;
}
public int getRequestTimeout() {
return this.requestTimeout;
}
public Hashtable getHeaders() {
return this.headers;
}
public String getUrl() {
return this.url;
}
}
/**
* @author Pubnub
*
*/
@SuppressWarnings("deprecation")
class PubnubHttpRequest {
private Request request;
private String[] errorsMessages;
public PubnubHttpRequest(Request request, String[] errorsMessages){
this.errorsMessages = errorsMessages;
this.request = request;
}
public String[] errorMessages(){
return this.errorsMessages;
}
public Request request(){
return this.request;
}
}
/**
* Pubnub object facilitates querying channels for messages and listening on channels for presence/message events
* @author Pubnub
*
*/
public class Pubnub {
private String ORIGIN = "pubsub.pubnub.com";
private String PUBLISH_KEY = "";
private String SUBSCRIBE_KEY = "";
private String SECRET_KEY = "";
private String CIPHER_KEY = "";
private boolean SSL = false;
private String sessionUUID = "";
public String getUUID() {
return sessionUUID;
}
public void setUUID(String sessionUUID) {
this.sessionUUID = sessionUUID;
}
private String parameters = "";
private int PUBNUB_WEBREQUEST_CALLBACK_INTERVAL = 310000;
private int PUBNUB_NETWORK_CHECK_RETRIES = 50;
private int PUBNUB_WEBREQUEST_RETRY_INTERVAL = 10000;
private int PUBNUB_FAST_WEBREQUEST_TIMEOUT = 5000;
private int PUBNUB_DEFAULT_CONN_TIMEOUT = 10000;
private HttpURLConnection connection;
/** Sets wait time for Presence/Subscribe API
* @param interval Time interval in milliseconds for which the API's like Presence and Subscribe will block
*/
public void setWebRequestCallbackInterval(int interval){
this.PUBNUB_WEBREQUEST_CALLBACK_INTERVAL = interval;
this.init(this.PUBLISH_KEY, this.SUBSCRIBE_KEY, this.SECRET_KEY, this.CIPHER_KEY, this.SSL);
}
/**
* Sets number of retries to be made for network availability check
* @param count No of times attempt will be made to check network availability
*/
public void setNetworkCheckRetriesCount(int count) {
this.PUBNUB_NETWORK_CHECK_RETRIES = count;
}
/**
* Sets time interval between consecutive network availability checks
* @param interval Time interval in milliseconds between each attempt for network connectivity check
*/
public void setWebRequestRetryInterval(int interval) {
this.PUBNUB_WEBREQUEST_RETRY_INTERVAL = interval;;
}
/**
* Sets timeout values for publish, history, detailedHistory, time, here_now
* @param timeout timeout value in milliseconds for api's publish, history, here_now, detailedHistory, time
*/
public void setFastWebRequestTimeout(int timeout) {
this.PUBNUB_FAST_WEBREQUEST_TIMEOUT = timeout;
}
/** Sets the timeout value for TCP connections made by API to Pubnub Servers
* @param timeout timeout value in milliseconds for tcp connection attempt.
*/
public void setConnectionTimeout(int timeout) {
this.PUBNUB_DEFAULT_CONN_TIMEOUT = timeout;
this.init(this.PUBLISH_KEY, this.SUBSCRIBE_KEY, this.SECRET_KEY, this.CIPHER_KEY, this.SSL);
}
/**
* Returns Time interval in milliseconds for which the API's like Presence and Subscribe will block
* @return Time interval in milliseconds for which the API's like Presence and Subscribe will block
*/
public int getWebRequestCallbackInterval(){
return this.PUBNUB_WEBREQUEST_CALLBACK_INTERVAL;
}
/**
* Returns No of times attempt will be made to check network availability
* @return No of times attempt will be made to check network availability
*/
public int getNetworkCheckRetriesCount() {
return this.PUBNUB_NETWORK_CHECK_RETRIES;
}
/**
* Returns time interval in milliseconds between each attempt for network connectivity check
* @return Time interval in milliseconds between each attempt for network connectivity check
*/
public int getWebRequestRetryInterval() {
return this.PUBNUB_WEBREQUEST_RETRY_INTERVAL;
}
/**
* Returns timeout value in milliseconds for api's publish, history, here_now, detailedHistory, uuid, time
* @return timeout value in milliseconds for api's publish, history, here_now, detailedHistory, uuid, time
*/
public int getFastWebRequestTimeout() {
return this.PUBNUB_FAST_WEBREQUEST_TIMEOUT;
}
/**
* Returns the timeout value for TCP connections made by api
* @return the timeout value for TCP connections made by api
*/
public int getConnectionTimeout() {
return this.PUBNUB_DEFAULT_CONN_TIMEOUT;
}
private Request getRequest(List<String> url_components) {
return getRequest(url_components, 0);
}
@SuppressWarnings({ "deprecation"})
private Request getRequest(List<String> url_components, int requestTimeout) {
Request req = new Request();
StringBuilder url = new StringBuilder();
Iterator<String> url_iterator = url_components.iterator();
String request_for = url_components.get(0);
String request_type = url_components.get(1);
url.append(this.ORIGIN);
// Generate URL with UTF-8 Encoding
while (url_iterator.hasNext()) {
String url_bit = (String) url_iterator.next();
url.append("/").append(_encodeURIcomponent(url_bit));
}
if (request_for.equals("subscribe") || request_for.equals("presence"))
url.append("?uuid=").append(this.sessionUUID);
if (request_for.equals("v2") && request_type.equals("history"))
url.append(parameters);
req.setUrl(url.toString());
Hashtable headers = new Hashtable();
headers.put("V", "3.3");
headers.put("User-Agent", "Java");
headers.put("Accept-Encoding", "gzip");
req.setHeaders(headers);
req.setConnectionTimeout(PUBNUB_DEFAULT_CONN_TIMEOUT);
if (requestTimeout > 0) {
req.setRequestTimeout(requestTimeout);
} else {
req.setRequestTimeout(PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
return req;
}
protected void finalize() {
if (connection != null) {
connection.disconnect();
connection = null;
}
}
public String sessionUUID() {
return sessionUUID;
}
private class ChannelStatus {
String channel;
boolean connected, first;
}
private HashMap<String, ChannelStatus> subscriptions;
/**
*
* Constructor for Pubnub Class
*
* @param publish_key Publish Key
* @param subscribe_key Subscribe Key
* @param secret_key Secret Key
* @param cipher_key Cipher Key
* @param ssl_on SSL enabled ?
*/
public Pubnub(String publish_key, String subscribe_key, String secret_key,
String cipher_key, boolean ssl_on) {
this.init(publish_key, subscribe_key, secret_key, cipher_key, ssl_on);
}
/**
*
* Constructor for Pubnub Class
*
* @param publish_key Publish Key
* @param subscribe_key Subscribe Key
* @param secret_key Secret Key
* @param ssl_on SSL enabled ?
*/
public Pubnub(String publish_key, String subscribe_key, String secret_key,
boolean ssl_on) {
this.init(publish_key, subscribe_key, secret_key, "", ssl_on);
}
/**
*
* Constructor for Pubnub Class
*
* @param publish_key Publish Key
* @param subscribe_key Subscribe Key
*/
public Pubnub(String publish_key, String subscribe_key) {
this.init(publish_key, subscribe_key, "", "", false);
}
/**
*
* Constructor for Pubnub Class
*
* @param publish_key Publish Key
* @param subscribe_key Subscribe Key
* @param secret_key Secret Key
*/
public Pubnub(String publish_key, String subscribe_key, String secret_key) {
this.init(publish_key, subscribe_key, secret_key, "", false);
}
/**
* Initialize PubNub Object State.
*
* @param publish_key
* @param subscribe_key
* @param secret_key
* @param cipher_key
* @param ssl_onn
*/
private void init(String publish_key, String subscribe_key,
String secret_key, String cipher_key, boolean ssl_on) {
this.PUBLISH_KEY = publish_key;
this.SUBSCRIBE_KEY = subscribe_key;
this.SECRET_KEY = secret_key;
this.CIPHER_KEY = cipher_key;
this.SSL = ssl_on;
if (this.sessionUUID.equals(""))
sessionUUID = UUID.randomUUID().toString();
// SSL On?
if (this.SSL) {
this.ORIGIN = "https://" + this.ORIGIN;
} else {
this.ORIGIN = "http://" + this.ORIGIN;
}
}
/**
* getResponseByUrl
*
* Get response by url.
*
* @param phr PubnubHttpRequest
* @param decrypt Decryption enabled ?
*/
private JSONArray getResponseByUrl(PubnubHttpRequest phr, boolean decrypt) {
return _getResponseByUrl(phr, decrypt, -1);
}
/**
* Get response by url.
*
* @param phr PubnubHttpRequest
* @param index
*
*/
private JSONArray getResponseByUrl(PubnubHttpRequest phr, int index) {
return _getResponseByUrl(phr, true, index);
}
/**
* Get response by url.
* @param phr PubnubHttpRequest
*/
private JSONArray getResponseByUrl(PubnubHttpRequest phr) {
return _getResponseByUrl(phr, true, -1);
}
/*
* Get response by url.
*
* @param phr PubnubHttpRequest
* @param decrypt Decryption enabled ?
* @param index
*/
private JSONArray _getResponseByUrl(PubnubHttpRequest phr, boolean decrypt,
int index) {
JSONArray response = _request(phr);
if (this.CIPHER_KEY.length() > 0 && decrypt) {
// Decrypt Messages
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
if (index < 0)
return pc.decryptJSONArray(response);
else {
try {
response.put(index, pc
.decryptJSONArray((JSONArray) response.get(index)));
} catch (JSONException e) {
return null;
}
return response;
}
} else {
return response;
}
}
/**
* Send a message to a channel.
*
* @param channel Channel name
* @param message JSONObject to be published
* @return JSONArray of response
*/
public JSONArray publish(String channel, JSONObject message) {
HashMap<String, Object> args = new HashMap<String, Object>(2);
args.put("channel", channel);
args.put("message", message);
return publish(args, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
* Send a message to a channel.
*
* @param channel Channel name
* @param message JSONObject of message to be published
* @param requestTimeout timeout value in milliseconds for this request
* @return JSONArray of response
*/
public JSONArray publish(String channel, JSONObject message, int requestTimeout) {
HashMap<String, Object> args = new HashMap<String, Object>(2);
args.put("channel", channel);
args.put("message", message);
return publish(args, requestTimeout);
}
/**
* Send a message to a channel.
*
* @param args HashMap of <String, Object> containing channel name, message.
* @param requestTimeout timeout value in milliseconds for this request
* @return JSONArray of response
*/
private JSONArray publish(HashMap<String, Object> args, int requestTimeout) {
String channel = (String) args.get("channel");
Object message = args.get("message");
String[] errorMessages = {"0", "Error: Failed JSONP HTTP Request" };
if (message instanceof JSONObject) {
JSONObject obj = (JSONObject) message;
if (this.CIPHER_KEY.length() > 0) {
// Encrypt Message
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
message = pc.encrypt(obj);
} else {
message = obj;
}
} else if (message instanceof String) {
String obj = (String) message;
if (this.CIPHER_KEY.length() > 0) {
// Encrypt Message
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
try {
message = pc.encrypt(obj);
} catch (Exception e) {
return new JSONArray().put(1).put(
"Message Encryption Error");
}
} else {
message = obj;
}
message = "\"" + message + "\"";
} else if (message instanceof JSONArray) {
JSONArray obj = (JSONArray) message;
if (this.CIPHER_KEY.length() > 0) {
// Encrypt Message
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
message = pc.encryptJSONArray(obj);
} else {
message = obj;
}
}
// Generate String to Sign
String signature = "0";
if (this.SECRET_KEY.length() > 0) {
StringBuilder string_to_sign = new StringBuilder();
string_to_sign.append(this.PUBLISH_KEY).append('/')
.append(this.SUBSCRIBE_KEY).append('/')
.append(this.SECRET_KEY).append('/').append(channel)
.append('/').append(message.toString());
// Sign Message
signature = PubnubCrypto.getHMacSHA256(this.SECRET_KEY,
string_to_sign.toString());
}
// Build URL
String[] urlargs = { "publish", this.PUBLISH_KEY, this.SUBSCRIBE_KEY,
signature, channel, "0", message.toString() };
return _request( new PubnubHttpRequest(getRequest( Arrays.asList(urlargs), requestTimeout), errorMessages));
}
/**
*
* Listen for a message on a channel.
*
* @param channel Channel name for subscribing
* @param callback Callback
* @exception PubnubException Throws PubnubException if Callback is null
*/
public void subscribe(String channel, Callback callback)
throws PubnubException {
HashMap<String, Object> args = new HashMap<String, Object>(2);
args.put("channel", channel);
args.put("callback", callback);
subscribe(args);
}
/**
*
* Listen for a message on a channel.
*
* @param args HashMap <String, Object> containing channel name, function callback.
* @exception PubnubException Throws PubnubException if Callback is missing
*/
private void subscribe(HashMap<String, Object> args) throws PubnubException {
args.put("timetoken", "0");
this._subscribe(args);
}
/**
* Subscribe - Private Interface
*
* Patch provided by petereddy on GitHub
*
* @param args HashMap
* <String, Object> containing channel name, function callback,
* timetoken.
*/
private void _subscribe(HashMap<String, Object> args)
throws PubnubException {
String[] errorMessages = {"0", "0"};
String channel = (String) args.get("channel");
String timetoken = (String) args.get("timetoken");
Callback callback;
// Validate Arguments
if (args.get("callback") != null) {
callback = (Callback) args.get("callback");
} else {
throw new PubnubException("Invalid Callback");
}
if (channel == null || channel.equals("")) {
callback.errorCallback(channel, "Invalid Channel.");
return;
}
// Ensure Single Connection
if (subscriptions != null && subscriptions.size() > 0) {
if (subscriptions.get(channel) == null) {
ChannelStatus cs = new ChannelStatus();
cs.channel = channel;
cs.connected = true;
subscriptions.put(cs.channel, cs);
} else {
callback.errorCallback(channel, "Already Connected");
return;
}
} else {
// New Channel
ChannelStatus cs = new ChannelStatus();
cs.channel = channel;
cs.connected = true;
subscriptions = new HashMap<String, Pubnub.ChannelStatus>();
subscriptions.put(cs.channel, cs);
}
while (true) {
try {
// Build URL
List<String> url = java.util.Arrays.asList("subscribe",
this.SUBSCRIBE_KEY, channel, "0", timetoken);
// Stop Connection?
boolean is_disconnect = false;
if (subscriptions.get(channel) != null
&& !subscriptions.get(channel).connected) {
subscriptions.remove(channel);
callback.disconnectCallback(channel);
is_disconnect = true;
}
if (is_disconnect)
return;
// Wait for Message
JSONArray response = _request(new PubnubHttpRequest(getRequest(url, PUBNUB_WEBREQUEST_CALLBACK_INTERVAL), errorMessages));
// Stop Connection?
if (subscriptions.get(channel) != null
&& !subscriptions.get(channel).connected) {
subscriptions.remove(channel);
callback.disconnectCallback(channel);
is_disconnect = true;
}
if (is_disconnect)
return;
// Problem?
if (response == null || response.optInt(1) == 0) {
ChannelStatus it = null;
if ((it = subscriptions.get(channel)) != null) {
if (it.connected && it.first) {
subscriptions.remove(it.channel);
callback.disconnectCallback(channel);
} else {
subscriptions.remove(it.channel);
callback.errorCallback(channel,
"Lost Network Connection");
}
}
// Ensure Connected (Call Time Function)
boolean is_reconnected = false;
int retries = 0;
while (true && retries < PUBNUB_NETWORK_CHECK_RETRIES) {
double time_token = this.time();
retries++;
if (time_token == 0.0) {
Thread.sleep(PUBNUB_WEBREQUEST_RETRY_INTERVAL);
} else {
// Reconnect Callback
callback.reconnectCallback(channel);
// this._subscribe(args);
is_reconnected = true;
break;
}
}
if (is_reconnected) {
continue;
} else {
HashMap<String, Object> args1 = new HashMap<String, Object>(1);
args.put("channel", channel);
this.unsubscribe(args1);
callback.errorCallback(channel,
" Unsubscribed after " + String.valueOf(PUBNUB_NETWORK_CHECK_RETRIES) + "failed retries");
return;
}
} else {
ChannelStatus it = null;
if ((it = subscriptions.get(channel)) != null) {
// Connect Callback
if (!it.first) {
it.first = true;
callback.connectCallback(channel);
}
}
}
JSONArray messages = response.optJSONArray(0);
// Update TimeToken
if (response.optString(1).length() > 0)
timetoken = response.optString(1);
for (int i = 0; messages.length() > i; i++) {
JSONObject message = messages.optJSONObject(i);
if (message != null) {
if (this.CIPHER_KEY.length() > 0) {
// Decrypt Message
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
message = pc.decrypt(message);
}
if (callback != null) {
if (!callback.successCallback(channel, message))
return;
}
} else {
JSONArray arr = messages.optJSONArray(i);
if (arr != null) {
if (this.CIPHER_KEY.length() > 0) {
PubnubCrypto pc = new PubnubCrypto(
this.CIPHER_KEY);
arr = pc.decryptJSONArray(arr);
;
}
if (callback != null)
if (!callback.successCallback(channel, arr))
return;
} else {
String msgs = messages.getString(0);
if (this.CIPHER_KEY.length() > 0) {
PubnubCrypto pc = new PubnubCrypto(
this.CIPHER_KEY);
msgs = pc.decrypt(msgs);
}
if (callback != null)
if (!callback.successCallback(channel, msgs))
return;
}
}
}
} catch (Exception e) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}
/**
*
* Listen for presence of subscribers on a channel
*
* @param channel Name of the channel on which to listen for join/leave i.e. presence events
* @param callback Callback
* @exception PubnubException Throws PubnubException if Callback is null
*/
public void presence(String channel, Callback callback)
throws PubnubException {
HashMap<String, Object> args = new HashMap<String, Object>(2);
args.put("channel", channel + "-pnpres");
args.put("callback", callback);
subscribe(args);
}
/**
* Read presence information from a channel
* @param channel
* @return JSONArray of uuid's currently subscribing to a channel
*/
public JSONArray here_now(String channel) {
return here_now(channel, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read presence information from a channel
*
* @param channel Channel name
* @param requestTimeout timeout in milliseconds for this request
* @return Array of uuid's currently subscribing to a channel
*/
public JSONArray here_now(String channel, int requestTimeout) {
String[] errorMessages = {};
String[] urlargs = { "v2", "presence", "sub_key", this.SUBSCRIBE_KEY,
"channel", channel };
return getResponseByUrl( new PubnubHttpRequest(getRequest(Arrays.asList(urlargs), requestTimeout), errorMessages) , false);
}
/**
*
* Read history from a channel.
*
* @param channel Channel Name
* @param limit Upper limit on number of messages in response
* @param requestTimeout timeout in milliseconds for this request
* @return JSONArray of message history on a channel.
*/
public JSONArray history(String channel, int limit, int requestTimeout) {
HashMap<String, Object> args = new HashMap<String, Object>(2);
args.put("channel", channel);
args.put("limit", limit);
return history(args,requestTimeout);
}
/**
*
* Read history from a channel.
*
* @param channel Channel Name
* @param limit Upper limit on number of messages in response.
* @return JSONArray of message history on a channel.
*/
public JSONArray history(String channel, int limit) {
return history(channel, limit, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read history from a channel.
*
* @param args HashMap of <String, Object> containing channel name, limit history count
* @param requestTimeout timeout in milliseconds for this request
* @return JSONArray of history.
*/
private JSONArray history(HashMap<String, Object> args, int requestTimeout) {
String channel = (String) args.get("channel");
String[] errorMessages = {"0", "Error: Failed JSONP HTTP Request" };
int limit = Integer.parseInt(args.get("limit").toString());
String[] urlargs = { "history", this.SUBSCRIBE_KEY, channel, "0",
Integer.toString(limit) };
return getResponseByUrl(new PubnubHttpRequest(getRequest(Arrays.asList(urlargs), requestTimeout), errorMessages));
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param end End time
* @param count Upper limit on number of messages to be returned
* @param reverse True if messages need to be in reverse order
* @param requestTimeout Timeout value in milliseconds for this request
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, long end,
int count, Boolean reverse, int requestTimeout) {
String[] errorMessages = {"0", "Error: Failed JSONP HTTP Request" };
parameters = "";
if (count == -1)
count = 100;
parameters = "?count=" + count;
parameters = parameters + "&" + "reverse=" + reverse.toString().toLowerCase();
if (start != -1)
parameters = parameters + "&" + "start="
+ Long.toString(start).toLowerCase();
if (end != -1)
parameters = parameters + "&" + "end="
+ Long.toString(end).toLowerCase();
String[] urlargs = { "v2", "history", "sub-key", this.SUBSCRIBE_KEY,
"channel", channel };
return getResponseByUrl(new PubnubHttpRequest(getRequest(Arrays.asList(urlargs), requestTimeout), errorMessages), 0);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param end End time
* @param count Upper limit on number of messages to be returned
* @param reverse True if messages need to be in reverse order
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, long end,
int count, Boolean reverse) {
return detailedHistory(channel, start, end, count, reverse, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param reverse True if messages need to be in reverse order
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, boolean reverse) {
return detailedHistory(channel, start, -1, -1, reverse, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param reverse True if messages need to be in reverse order
* @param requestTimeout Timeout value in milliseconds for this request
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, boolean reverse, int requestTimeout) {
return detailedHistory(channel, start, -1, -1, reverse, requestTimeout);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param end End time
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, long end) {
return detailedHistory(channel, start, end, -1, false, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
public JSONArray detailedHistory(String channel, long start, long end, int requestTime) {
return detailedHistory(channel, start, end, -1, false, requestTime);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param end End time
* @param reverse True if messages need to be in reverse order
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, long end,
boolean reverse) {
return detailedHistory(channel, start, end, -1, reverse, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param start Start time
* @param end End time
* @param reverse True if messages need to be in reverse order
* @param requestTimeout Timeout value in milliseconds for this request
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, long start, long end,
boolean reverse, int requestTimeout) {
return detailedHistory(channel, start, end, -1, reverse, requestTimeout);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param count Upper limit on number of messages to be returned
* @param reverse True if messages need to be in reverse order
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, int count, boolean reverse) {
return detailedHistory(channel, -1, -1, count, reverse, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param count Upper limit on number of messages to be returned
* @param reverse True if messages need to be in reverse order
* @param requestTimeout Timeout value in milliseconds for this request
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, int count, boolean reverse, int requestTimeout) {
return detailedHistory(channel, -1, -1, count, reverse, requestTimeout);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param reverse True if messages need to be in reverse order
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, boolean reverse) {
return detailedHistory(channel, -1, -1, -1, reverse, PUBNUB_FAST_WEBREQUEST_TIMEOUT);
}
/**
*
* Read DetailedHistory for a channel.
* @param channel Channel name for which detailed history is required
* @param reverse True if messages need to be in reverse order
* @param requestTimeout Timeout value in milliseconds for this request
* @return JSONArray of detailed history.
*/
public JSONArray detailedHistory(String channel, boolean reverse, int requestTimeout) {
return detailedHistory(channel, -1, -1, -1, reverse, requestTimeout);
}
/**
* Read current time from PubNub Cloud.
*
* @return current timestamp.
*/
public double time() {
List<String> url = new ArrayList<String>();
String[] errorMessages = {"0"};
url.add("time");
url.add("0");
JSONArray response = _request( new PubnubHttpRequest(getRequest(url,PUBNUB_FAST_WEBREQUEST_TIMEOUT), errorMessages));
return response.optDouble(0);
}
/**
* Get 32 digit UUID generation at client side.
*
* @return uuid.
*/
public static String uuid() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
/**
* Unsubscribe/Disconnect from channel.
*
* @param args HashMap of <String, Object> containing channel name.
*/
public void unsubscribe(HashMap<String, Object> args) {
String channel = (String) args.get("channel");
ChannelStatus it = null;
if ((it = subscriptions.get(channel)) != null && it.connected == true) {
it.connected = false;
it.first = false;