11package com .pubnub .api .managers ;
22
3- import com .fasterxml .jackson .databind .JsonNode ;
4- import com .fasterxml .jackson .databind .ObjectMapper ;
5- import com .pubnub .api .callbacks .PNCallback ;
6- import com .pubnub .api .callbacks .SubscribeCallback ;
7- import com .pubnub .api .vendor .Crypto ;
83import com .pubnub .api .PubNub ;
9- import com .pubnub .api .PubNubException ;
104import com .pubnub .api .builder .dto .StateOperation ;
115import com .pubnub .api .builder .dto .SubscribeOperation ;
126import com .pubnub .api .builder .dto .UnsubscribeOperation ;
7+ import com .pubnub .api .callbacks .PNCallback ;
8+ import com .pubnub .api .callbacks .SubscribeCallback ;
139import com .pubnub .api .endpoints .presence .Heartbeat ;
1410import com .pubnub .api .endpoints .presence .Leave ;
1511import com .pubnub .api .endpoints .pubsub .Subscribe ;
1612import com .pubnub .api .enums .PNHeartbeatNotificationOptions ;
17- import com .pubnub .api .enums .PNOperationType ;
1813import com .pubnub .api .enums .PNStatusCategory ;
19- import com .pubnub .api .models .consumer .PNErrorData ;
2014import com .pubnub .api .models .consumer .PNStatus ;
21- import com .pubnub .api .models .consumer .pubsub .PNMessageResult ;
22- import com .pubnub .api .models .consumer .pubsub .PNPresenceEventResult ;
2315import com .pubnub .api .models .server .Envelope ;
24- import com .pubnub .api .models .server .PresenceEnvelope ;
2516import com .pubnub .api .models .server .SubscribeEnvelope ;
2617import com .pubnub .api .models .server .SubscribeMessage ;
18+ import com .pubnub .api .workers .SubscribeMessageWorker ;
2719import lombok .extern .slf4j .Slf4j ;
2820import retrofit2 .Call ;
2921
30- import java .io .IOException ;
31- import java .util .ArrayList ;
3222import java .util .List ;
3323import java .util .Map ;
3424import java .util .Timer ;
3525import java .util .TimerTask ;
26+ import java .util .concurrent .LinkedBlockingQueue ;
3627
3728@ Slf4j
3829public class SubscriptionManager {
3930
4031 private static final int HEART_BEAT_INTERVAL_MULTIPLIER = 1000 ;
41- private List <SubscribeCallback > listeners ;
4232 private PubNub pubnub ;
4333 private Call <SubscribeEnvelope > subscribeCall ;
4434 private Call <Envelope > heartbeatCall ;
35+
36+ private LinkedBlockingQueue <SubscribeMessage > messageQueue ;
37+
4538 /**
4639 * Store the latest timetoken to subscribe with, null by default to get the latest timetoken.
4740 */
@@ -57,9 +50,10 @@ public class SubscriptionManager {
5750 */
5851 private Timer timer ;
5952
60- private ObjectMapper mapper ;
61-
6253 private StateManager subscriptionState ;
54+ private ListenerManager listenerManager ;
55+
56+ private Thread consumerThread ;
6357
6458 /**
6559 * lever to indicate if an announcement to the user about the subscription should be made.
@@ -69,24 +63,27 @@ public class SubscriptionManager {
6963
7064
7165 public SubscriptionManager (PubNub pubnubInstance ) {
72- this .subscriptionState = new StateManager ();
7366 this .pubnub = pubnubInstance ;
74- this .listeners = new ArrayList <>();
75- this .mapper = new ObjectMapper ();
7667
7768 this .subscriptionStatusAnnounced = false ;
69+ this .messageQueue = new LinkedBlockingQueue <>();
70+ this .subscriptionState = new StateManager ();
71+ this .listenerManager = new ListenerManager (this .pubnub );
7872
79- }
8073
74+ consumerThread = new Thread (new SubscribeMessageWorker (this .pubnub , listenerManager , messageQueue ));
75+ consumerThread .start ();
76+ }
8177
82- public final synchronized void addListener (SubscribeCallback listener ) {
83- listeners . add (listener );
78+ public final void addListener (SubscribeCallback listener ) {
79+ listenerManager . addListener (listener );
8480 }
8581
86- public final synchronized void removeListener (SubscribeCallback listener ) {
87- listeners . remove (listener );
82+ public final void removeListener (SubscribeCallback listener ) {
83+ listenerManager . removeListener (listener );
8884 }
8985
86+
9087 public final synchronized void reconnect () {
9188 this .startSubscribeLoop ();
9289 this .registerHeartbeatTimer ();
@@ -95,6 +92,7 @@ public final synchronized void reconnect() {
9592 public synchronized void stop () {
9693 stopHeartbeatTimer ();
9794 stopSubscribeLoop ();
95+ consumerThread .interrupt ();
9896 }
9997
10098 public final synchronized void adaptStateBuilder (final StateOperation stateOperation ) {
@@ -122,7 +120,7 @@ public final synchronized void adaptUnsubscribeBuilder(final UnsubscribeOperatio
122120 .async (new PNCallback <Boolean >() {
123121 @ Override
124122 public void onResponse (final Boolean result , final PNStatus status ) {
125- announce (status );
123+ listenerManager . announce (status );
126124 }
127125 });
128126
@@ -174,12 +172,13 @@ public void onResponse(final SubscribeEnvelope result, final PNStatus status) {
174172 if (status .getCategory () == PNStatusCategory .PNTimeoutCategory ) {
175173 startSubscribeLoop ();
176174 } else {
177- announce (status );
175+ listenerManager . announce (status );
178176 }
179177
180178 return ;
181179 }
182180
181+
183182 if (!subscriptionStatusAnnounced ) {
184183 PNStatus pnStatus = PNStatus .builder ()
185184 .error (false )
@@ -192,12 +191,12 @@ public void onResponse(final SubscribeEnvelope result, final PNStatus status) {
192191 .tlsEnabled (status .isTlsEnabled ())
193192 .build ();
194193
195- announce (pnStatus );
196194 subscriptionStatusAnnounced = true ;
195+ listenerManager .announce (pnStatus );
197196 }
198197
199198 if (result .getMessages ().size () != 0 ) {
200- processIncomingMessages (result .getMessages ());
199+ messageQueue . addAll (result .getMessages ());
201200 }
202201
203202 timetoken = result .getMetadata ().getTimetoken ();
@@ -238,122 +237,16 @@ public void onResponse(Boolean result, PNStatus status) {
238237 if (status .isError ()) {
239238 if (heartbeatVerbosity == PNHeartbeatNotificationOptions .ALL
240239 || heartbeatVerbosity == PNHeartbeatNotificationOptions .FAILURES ) {
241- announce (status );
240+ listenerManager . announce (status );
242241 }
243242
244243 } else {
245244 if (heartbeatVerbosity == PNHeartbeatNotificationOptions .ALL ) {
246- announce (status );
245+ listenerManager . announce (status );
247246 }
248247 }
249248 }
250249 });
251250 }
252251
253- private void processIncomingMessages (final List <SubscribeMessage > messages ) {
254-
255- for (SubscribeMessage message : messages ) {
256-
257- String channel = message .getChannel ();
258- String subscriptionMatch = message .getSubscriptionMatch ();
259-
260- if (channel .equals (subscriptionMatch )) {
261- subscriptionMatch = null ;
262- }
263-
264- if (message .getChannel ().contains ("-pnpres" )) {
265- PresenceEnvelope presencePayload = mapper .convertValue (message .getPayload (), PresenceEnvelope .class );
266-
267- PNPresenceEventResult pnPresenceEventResult = PNPresenceEventResult .builder ()
268- .event (presencePayload .getAction ())
269- .actualChannel ((subscriptionMatch != null ) ? channel : null )
270- .subscribedChannel (subscriptionMatch != null ? subscriptionMatch : channel )
271- .timetoken (timetoken )
272- .occupancy (presencePayload .getOccupancy ())
273- .uuid (presencePayload .getUuid ())
274- .timestamp (presencePayload .getTimestamp ())
275- .build ();
276-
277- announce (pnPresenceEventResult );
278- } else {
279- JsonNode extractedMessage = processMessage (message .getPayload ());
280-
281- if (extractedMessage == null ) {
282- log .debug ("unable to parse payload on #processIncomingMessages" );
283- }
284-
285- PNMessageResult pnMessageResult = PNMessageResult .builder ()
286- .message (extractedMessage )
287- .actualChannel ((subscriptionMatch != null ) ? channel : null )
288- .subscribedChannel (subscriptionMatch != null ? subscriptionMatch : channel )
289- .timetoken (timetoken )
290- .build ();
291-
292-
293- announce (pnMessageResult );
294- }
295- }
296- }
297-
298- private JsonNode processMessage (final JsonNode input ) {
299- if (pubnub .getConfiguration ().getCipherKey () == null ) {
300- return input ;
301- }
302-
303- Crypto crypto = new Crypto (pubnub .getConfiguration ().getCipherKey ());
304- String outputText ;
305- JsonNode outputObject ;
306-
307- try {
308- outputText = crypto .decrypt (input .toString ());
309- } catch (PubNubException e ) {
310- PNStatus pnStatus = PNStatus .builder ().error (true )
311- .errorData (new PNErrorData (e .getMessage (), e ))
312- .operation (PNOperationType .PNSubscribeOperation )
313- .category (PNStatusCategory .PNDecryptionErrorCategory )
314- .build ();
315-
316- announce (pnStatus );
317- return null ;
318- }
319-
320- try {
321- outputObject = mapper .readValue (outputText , JsonNode .class );
322- } catch (IOException e ) {
323- PNStatus pnStatus = PNStatus .builder ().error (true )
324- .errorData (new PNErrorData (e .getMessage (), e ))
325- .operation (PNOperationType .PNSubscribeOperation )
326- .category (PNStatusCategory .PNMalformedResponseCategory )
327- .build ();
328-
329- announce (pnStatus );
330- return null ;
331- }
332-
333- return outputObject ;
334- }
335-
336- /**
337- * announce a PNStatus to listeners.
338- *
339- * @param status PNStatus which will be broadcast to listeners.
340- */
341- private void announce (final PNStatus status ) {
342- for (SubscribeCallback subscribeCallback : listeners ) {
343- subscribeCallback .status (this .pubnub , status );
344- }
345- }
346-
347- private void announce (final PNMessageResult message ) {
348- for (SubscribeCallback subscribeCallback : listeners ) {
349- subscribeCallback .message (this .pubnub , message );
350- }
351- }
352-
353- private void announce (final PNPresenceEventResult presence ) {
354- for (SubscribeCallback subscribeCallback : listeners ) {
355- subscribeCallback .presence (this .pubnub , presence );
356- }
357- }
358-
359252}
0 commit comments