forked from ringcentral/pubnub-jtools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPubnubCore.java
More file actions
2769 lines (2379 loc) · 88.8 KB
/
Copy pathPubnubCore.java
File metadata and controls
2769 lines (2379 loc) · 88.8 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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Random;
/**
* Pubnub object facilitates querying channels for messages and listening on
* channels for presence/message events
*
* @author Pubnub
*
*/
abstract class PubnubCore {
private String HOSTNAME = "pubsub";
private int HOSTNAME_SUFFIX = 1;
private String DOMAIN = "pubnub.com";
private String ORIGIN_STR = null;
protected String PUBLISH_KEY = "";
protected String SUBSCRIBE_KEY = "";
protected String SECRET_KEY = "";
private String CIPHER_KEY = "";
private String IV = null;
private volatile String AUTH_STR = null;
private volatile boolean CACHE_BUSTING = true;
protected Hashtable params;
private volatile boolean resumeOnReconnect;
private boolean SSL = true;
protected String UUID = null;
private Subscriptions channelSubscriptions;
private Subscriptions channelGroupSubscriptions;
protected SubscribeManager subscribeManager;
protected NonSubscribeManager nonSubscribeManager;
protected TimedTaskManager timedTaskManager;
private volatile String _timetoken = "0";
private volatile String _saved_timetoken = "0";
private String PRESENCE_SUFFIX = "-pnpres";
protected static String VERSION = "";
private Random generator = new Random();
private static Logger log = new Logger(PubnubCore.class);
protected abstract String getUserAgent();
private int PRESENCE_HEARTBEAT_TASK = 0;
private int HEARTBEAT = 320;
private volatile int PRESENCE_HB_INTERVAL = 0;
/**
* This method when called stops Pubnub threads
*/
public void shutdown() {
nonSubscribeManager.stop();
subscribeManager.stop();
timedTaskManager.stop();
}
/**
* This method returns the state of Resume on Reconnect setting
*
* @return Current state of Resume On Reconnect Setting
*/
public boolean isResumeOnReconnect() {
return resumeOnReconnect;
}
/**
* This method sets retry interval for subscribe. Pubnub API will make
* maxRetries attempts to connect to pubnub servers. These attemtps will be
* made at an interval of retryInterval milliseconds.
*
* @param retryInterval
* Retry Interval in milliseconds
*/
public void setRetryInterval(int retryInterval) {
subscribeManager.setRetryInterval(retryInterval);
}
/**
* This method sets window interval for subscribe.
*
* @param windowInterval
* Window Interval in milliseconds
*/
public void setWindowInterval(int windowInterval) {
subscribeManager.setWindowInterval(windowInterval);
}
/**
* Returns current retry interval for subscribe
* @return Current Retry Interval in milliseconds
*/
public int getRetryInterval() {
return subscribeManager.retryInterval;
}
/**
* Returns current window interval for subscribe
* @return Current Window Interval in milliseconds
*/
public int getWindowInterval() {
return subscribeManager.windowInterval;
}
String[] getPresenceHeartbeatUrl() {
String channelString = channelSubscriptions.getItemStringNoPresence();
if (channelString.length() <= 0) {
return null;
}
return new String[]{ getPubnubUrl(), "v2", "presence", "sub-key",
this.SUBSCRIBE_KEY, "channel",
PubnubUtil.urlEncode(channelString), "heartbeat"
};
}
private String getState() {
return (channelSubscriptions.state.length() > 0) ? channelSubscriptions.state.toString() : null;
}
class PresenceHeartbeatTask extends TimedTask {
private Callback callback;
PresenceHeartbeatTask(int interval, Callback callback) {
super(interval);
this.callback = callback;
}
public void run() {
String[] urlComponents = getPresenceHeartbeatUrl();
if (urlComponents == null)
return;
//String[] urlComponents = { getPubnubUrl(), "time", "0"};
Hashtable parameters = PubnubUtil.hashtableClone(params);
if (parameters.get("uuid") == null)
parameters.put("uuid", UUID);
String st = getState();
if (st != null) parameters.put("state", st);
if (HEARTBEAT > 0 && HEARTBEAT < 320 ) parameters.put("heartbeat", String.valueOf(HEARTBEAT));
HttpRequest hreq = new HttpRequest(urlComponents, parameters,
new ResponseHandler() {
public void handleResponse(HttpRequest hreq, String response) {
JSONObject jso;
try {
jso = new JSONObject(response);
response = jso.getString("message");
} catch (JSONException e) {
handleError(
hreq,
PubnubError.getErrorObject(
PubnubError.PNERROBJ_INVALID_JSON, 1, response
)
);
return;
}
callback.successCallback(
channelSubscriptions.getItemStringNoPresence(),
response
);
}
public void handleError(HttpRequest hreq, PubnubError error) {
callback.errorCallback(channelSubscriptions.getItemStringNoPresence(), error);
}
});
_request(hreq, nonSubscribeManager);
}
}
/**
* This method sets presence expiry timeout.
*
* @param pnexpires
* Presence Expiry timeout in seconds
*/
public void setPnExpires(int pnexpires, Callback callback) {
setHeartbeat(pnexpires,callback);
}
/**
* This method sets presence expiry timeout.
*
* @param heartbeat
* Presence Heartbeat value in seconds
*/
public void setHeartbeat(int heartbeat, Callback callback) {
Callback cb = getWrappedCallback(callback);
HEARTBEAT = (heartbeat > 0 && heartbeat < 5)?5:heartbeat;
if (PRESENCE_HB_INTERVAL == 0) {
PRESENCE_HB_INTERVAL = (HEARTBEAT - 3 >= 1)?HEARTBEAT - 3:1;
}
if (PRESENCE_HEARTBEAT_TASK == 0) {
PRESENCE_HEARTBEAT_TASK = timedTaskManager.addTask("Presence-Heartbeat",
new PresenceHeartbeatTask(PRESENCE_HB_INTERVAL, cb));
} else if (PRESENCE_HB_INTERVAL == 0 || PRESENCE_HB_INTERVAL > 320) {
timedTaskManager.removeTask(PRESENCE_HEARTBEAT_TASK);
} else {
timedTaskManager.updateTask(PRESENCE_HEARTBEAT_TASK, PRESENCE_HB_INTERVAL);
}
disconnectAndResubscribe();
}
public void setPnExpires(int pnexpires) {
setPnExpires(pnexpires, null);
}
public void setHeartbeat(int heartbeat) {
setHeartbeat(heartbeat, null);
}
public void setHeartbeatInterval(int heartbeatInterval) {
setHeartbeatInterval(heartbeatInterval, null);
}
public void setHeartbeatInterval(int heartbeatInterval, Callback callback) {
Callback cb = getWrappedCallback(callback);
PRESENCE_HB_INTERVAL = heartbeatInterval;
if (PRESENCE_HEARTBEAT_TASK == 0) {
PRESENCE_HEARTBEAT_TASK = timedTaskManager.addTask("Presence-Heartbeat",
new PresenceHeartbeatTask(PRESENCE_HB_INTERVAL, cb));
} else if (PRESENCE_HB_INTERVAL == 0 || PRESENCE_HB_INTERVAL > 320) {
timedTaskManager.removeTask(PRESENCE_HEARTBEAT_TASK);
} else {
timedTaskManager.updateTask(PRESENCE_HEARTBEAT_TASK, PRESENCE_HB_INTERVAL);
}
}
public int getHeartbeatInterval() {
return PRESENCE_HB_INTERVAL;
}
/**
* Returns presence expiry timeout value
* @return Current presence expiry timeout value
*/
public int getPnExpires() {
return getHeartbeat();
}
/**
* Returns presence heartbeat value
* @return Current presence heartbeat value
*/
public int getHeartbeat() {
return HEARTBEAT;
}
/**
* This methods sets maximum number of retries for subscribe. Pubnub API
* will make maxRetries attempts to connect to pubnub servers before timing
* out.
*
* @param maxRetries
* Max number of retries
*/
public void setMaxRetries(int maxRetries) {
subscribeManager.setMaxRetries(maxRetries);
}
/**
* Returns current max retries for Subscribe
* @return Current max retries
*/
public int getMaxRetries() {
return subscribeManager.maxRetries;
}
protected String getPubnubUrl() {
if (ORIGIN_STR == null) {
// SSL On?
if (this.SSL) {
ORIGIN_STR = "https://";
} else {
ORIGIN_STR = "http://";
}
ORIGIN_STR += HOSTNAME;
ORIGIN_STR += ((!this.CACHE_BUSTING)?"":"-" + String.valueOf(HOSTNAME_SUFFIX));
ORIGIN_STR += "." + DOMAIN;
}
return ORIGIN_STR;
}
private Callback voidCallback = new Callback()
{public void successCallback(String channel, Object message) {}};
protected Callback getWrappedCallback(Callback callback){
if (callback == null) {
return voidCallback;
} else
return callback;
}
private boolean validateInput(String name, Object input, Callback callback) {
if (input == null) {
callback.errorCallback("", PubnubError.getErrorObject(
PubnubError.PNERROBJ_INVALID_ARGUMENTS, 1, name + " cannot be null"));
return false;
}
if (input instanceof String && ((String)input).length() == 0) {
callback.errorCallback("", PubnubError.getErrorObject(
PubnubError.PNERROBJ_INVALID_ARGUMENTS, 2, name + " cannot be zero length"));
return false;
}
return true;
}
/**
* Enable/Disable Cache Busting
*
* @param cacheBusting
*/
public void setCacheBusting(boolean cacheBusting) {
this.CACHE_BUSTING = cacheBusting;
}
/**
* Get Cache Busting value
* @return current cache busting setting
*/
public boolean getCacheBusting() {
return this.CACHE_BUSTING;
}
/**
* This method returns all channel names currently subscribed to in form of
* a comma separated String
*
* @return Comma separated string with all channel names currently
* subscribed
*/
public String getCurrentlySubscribedChannelNames() {
String currentChannels = channelSubscriptions.getItemString();
return currentChannels.equals("") ? "no channels." : currentChannels;
}
/**
* If Resume on Reconnect is set to true, then Pubnub catches up on
* reconnection after disconnection. If false, then messages sent on the
* channel between disconnection and reconnection are not received.
*
* @param resumeOnReconnect
* True or False setting for Resume on Reconnect
*/
public void setResumeOnReconnect(boolean resumeOnReconnect) {
this.resumeOnReconnect = resumeOnReconnect;
}
/**
* Returns Resume on Reconnect current setting
* @return Resume on Reconnect setting
*/
public boolean getResumeOnReconnect() {
return this.resumeOnReconnect;
}
/**
* This method returns unique identifier.
* @return Unique Identifier .
*/
abstract String uuid();
/**
* Sets value for UUID
*
* @param uuid
* UUID value for Pubnub client
*/
public void setUUID(String uuid) {
this.UUID = uuid;
}
/**
* Gets current UUID
*
* @return uuid
* current UUID value for Pubnub client
*/
public String getUUID() {
return this.UUID;
}
/**
*
* 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 ?
* @param initialization_vector
* Initialization vector
*/
public PubnubCore(String publish_key, String subscribe_key,
String secret_key, String cipher_key, boolean ssl_on, String initialization_vector) {
this.init(publish_key, subscribe_key, secret_key, cipher_key, ssl_on, initialization_vector);
}
/**
*
* 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 PubnubCore(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 PubnubCore(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 PubnubCore(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
*/
public PubnubCore(String publish_key, String subscribe_key, boolean ssl) {
this.init(publish_key, subscribe_key, "", "", ssl);
}
/**
*
* Constructor for Pubnub Class
*
* @param publish_key
* Publish Key
* @param subscribe_key
* Subscribe Key
* @param secret_key
* Secret Key
*/
public PubnubCore(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_on
*/
private void init(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, null);
}
/**
*
* Initialize PubNub Object State.
*
* @param publish_key
* @param subscribe_key
* @param secret_key
* @param cipher_key
* @param ssl_on
*/
private void init(String publish_key, String subscribe_key,
String secret_key, String cipher_key, boolean ssl_on, String initialization_vector) {
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 (UUID == null)
UUID = uuid();
if (channelSubscriptions == null)
channelSubscriptions = new Subscriptions();
if (channelGroupSubscriptions == null)
channelGroupSubscriptions = new Subscriptions();
if (subscribeManager == null)
subscribeManager = new SubscribeManager("Subscribe-Manager-"
+ System.identityHashCode(this), 10000, 310000);
if (nonSubscribeManager == null)
nonSubscribeManager = new NonSubscribeManager(
"Non-Subscribe-Manager-" + System.identityHashCode(this),
10000, 15000);
if (timedTaskManager == null)
timedTaskManager = new TimedTaskManager("TimedTaskManager");
if (params == null)
params = new Hashtable();
params.put("pnsdk", getUserAgent());
subscribeManager.setHeader("V", VERSION);
subscribeManager.setHeader("Accept-Encoding", "gzip");
subscribeManager.setHeader("User-Agent", getUserAgent());
nonSubscribeManager.setHeader("V", VERSION);
nonSubscribeManager.setHeader("Accept-Encoding", "gzip");
nonSubscribeManager.setHeader("User-Agent", getUserAgent());
}
/**
* This method sets timeout value for subscribe/presence. Default value is
* 310000 milliseconds i.e. 310 seconds
*
* @param timeout
* Timeout value in milliseconds for subscribe/presence
*/
protected void setSubscribeTimeout(int timeout) {
subscribeManager.setRequestTimeout(timeout);
this.disconnectAndResubscribe();
}
protected int getSubscribeTimeout() {
return subscribeManager.requestTimeout;
}
/**
* This method set timeout value for non subscribe operations like publish,
* history, hereNow. Default value is 15000 milliseconds i.e. 15 seconds.
*
* @param timeout
* Timeout value in milliseconds for Non subscribe operations
* like publish, history, hereNow
*/
protected void setNonSubscribeTimeout(int timeout) {
nonSubscribeManager.setRequestTimeout(timeout);
}
protected int getNonSubscribeTimeout() {
return nonSubscribeManager.requestTimeout;
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* JSONObject to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, JSONObject message, boolean storeInHistory, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
args.put("storeInHistory", (storeInHistory)?"":"0");
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* JSONOArray to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, JSONArray message, boolean storeInHistory, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
args.put("storeInHistory", (storeInHistory)?"":"0");
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* String to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, String message, boolean storeInHistory, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
args.put("storeInHistory", (storeInHistory)?"":"0");
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* Integer to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, Integer message, boolean storeInHistory, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
args.put("storeInHistory", (storeInHistory)?"":"0");
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* Double to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, Double message, boolean storeInHistory, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
args.put("storeInHistory", (storeInHistory)?"":"0");
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* JSONObject to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, JSONObject message, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* JSONOArray to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, JSONArray message, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* String to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, String message, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* Integer to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, Integer message, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param channel
* Channel name
* @param message
* Double to be published
* @param callback
* object of sub class of Callback class
*/
public void publish(String channel, Double message, Callback callback) {
Hashtable args = new Hashtable();
args.put("channel", channel);
args.put("message", message);
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param args
* Hashtable containing channel name, message.
* @param callback
* object of sub class of Callback class
*/
protected void publish(Hashtable args, Callback callback) {
args.put("callback", callback);
publish(args);
}
/**
* Send a message to a channel.
*
* @param args
* Hashtable containing channel name, message, callback
*/
protected void publish(Hashtable args) {
final String channel = (String) args.get("channel");
final Object message = args.get("message");
final Callback callback = getWrappedCallback((Callback) args.get("callback"));
String storeInHistory = (String) args.get("storeInHistory");
String msgStr = message.toString();
Hashtable parameters = PubnubUtil.hashtableClone(params);
if (storeInHistory != null && storeInHistory.length() > 0) parameters.put("store", storeInHistory);
if (this.CIPHER_KEY.length() > 0) {
// Encrypt Message
PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY, this.IV);
try {
if (message instanceof String) {
msgStr = "\"" + msgStr + "\"";
}
msgStr = "\"" + pc.encrypt(msgStr) + "\"";
} catch (PubnubException e) {
callback.errorCallback(channel, getPubnubError(e, PubnubError.PNERROBJ_ENCRYPTION_ERROR, 4, msgStr + " : " + e.toString()));
return;
}
} else {
if (message instanceof String) {
msgStr = "\"" + msgStr + "\"";
}
}
// Generate String to Sign
String signature = "0";
if (this.SECRET_KEY.length() > 0) {
StringBuffer string_to_sign = new StringBuffer();
string_to_sign.append(this.PUBLISH_KEY).append('/')
.append(this.SUBSCRIBE_KEY).append('/')
.append(this.SECRET_KEY).append('/').append(channel)
.append('/').append(msgStr);
// Sign Message
try {
signature = new String(PubnubCrypto.hexEncode(PubnubCrypto
.md5(string_to_sign.toString())), "UTF-8");
} catch (UnsupportedEncodingException e) {
PubnubError pe = PubnubError.getErrorObject(PubnubError.PNERROBJ_ENCRYPTION_ERROR, 6, msgStr + " : " + e.toString());
callback.errorCallback(channel, pe);
} catch (PubnubException e) {
callback.errorCallback(channel, getPubnubError(e, PubnubError.PNERROBJ_ENCRYPTION_ERROR, 5, msgStr + " : " + e.toString()));
}
}
String[] urlComponents = { getPubnubUrl(), "publish", this.PUBLISH_KEY,
this.SUBSCRIBE_KEY, PubnubUtil.urlEncode(signature),
PubnubUtil.urlEncode(channel), "0",
PubnubUtil.urlEncode(msgStr)
};
class PublishResponseHandler extends ResponseHandler {
public void handleResponse(HttpRequest hreq, String response) {
JSONArray jsarr;
try {
jsarr = new JSONArray(response);
} catch (JSONException e) {
handleError(hreq,
PubnubError.getErrorObject(PubnubError.PNERROBJ_INVALID_JSON, 1, response));
return;
}
callback.successCallback(channel, jsarr);
}
public void handleError(HttpRequest hreq, PubnubError error) {
callback.errorCallback(channel, error);
return;
}
}
HttpRequest hreq = new HttpRequest(urlComponents, parameters, new PublishResponseHandler());
_request(hreq, nonSubscribeManager);
}
/**
*
* 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
* object of sub class of Callback class
* @exception PubnubException
* Throws PubnubException if Callback is null
*/
public void presence(String channel, Callback callback)
throws PubnubException {
Hashtable args = new Hashtable(2);
args.put("channels", new String[] {channel + PRESENCE_SUFFIX});
args.put("callback", callback);
subscribe(args);
}
/**
* Read presence information for uuid
*
* @param uuid
* UUID
* @param callback
* object of sub class of Callback class
*/
public void whereNow(final String uuid, Callback callback) {
final Callback cb = getWrappedCallback(callback);
String[] urlargs = { getPubnubUrl(), "v2", "presence", "sub_key",
this.SUBSCRIBE_KEY, "uuid", PubnubUtil.urlEncode(uuid)
};
HttpRequest hreq = new HttpRequest(urlargs, params,
new ResponseHandler() {
public void handleResponse(HttpRequest hreq, String response) {
invokeCallback("", response, "payload", cb, 4);
}
public void handleError(HttpRequest hreq, PubnubError error) {
cb.errorCallback("", error);
return;
}
});
_request(hreq, nonSubscribeManager);
}
public void whereNow(Callback callback) {
whereNow(this.UUID, callback);
}
public void setState(String channel, String uuid, JSONObject state, Callback callback) {
_setState(channelSubscriptions, PubnubUtil.urlEncode(channel), null, uuid, state, callback);
}
public void channelGroupSetState(String group, String uuid, JSONObject state, Callback callback) {
_setState(channelSubscriptions, ".", group, uuid, state, callback);
}
protected void _setState(Subscriptions sub, String channel, String group, String uuid, JSONObject state, Callback callback) {
SubscriptionItem item = sub.getItem(channel);
final Callback cb = getWrappedCallback(callback);
Hashtable parameters = PubnubUtil.hashtableClone(params);
String[] urlArgs = { getPubnubUrl(), "v2", "presence", "sub-key",
this.SUBSCRIBE_KEY, "channel", channel, "uuid", PubnubUtil.urlEncode(uuid),
"data"
};
if (state != null) parameters.put("state", state.toString());
if (group != null) parameters.put("channel-group", group);
if (item != null) {
try {
sub.state.put(channel, state);
} catch (JSONException e) {
}
}
HttpRequest hreq = new HttpRequest(urlArgs, parameters,
new ResponseHandler() {
public void handleResponse(HttpRequest hreq, String response) {
invokeCallback("", response, "payload", cb, 2 );
}
public void handleError(HttpRequest hreq, PubnubError error) {
cb.errorCallback("", error);
}
});
_request(hreq, nonSubscribeManager);
}
public void getState(String channel, String uuid, Callback callback) {