-
Notifications
You must be signed in to change notification settings - Fork 962
/
ReconnectPluginActivator.java
685 lines (605 loc) · 21.3 KB
/
ReconnectPluginActivator.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
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Copyright @ 2018 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.java.sip.communicator.plugin.reconnectplugin;
import java.util.*;
import java.util.stream.*;
import net.java.sip.communicator.service.gui.*;
import net.java.sip.communicator.service.netaddr.*;
import net.java.sip.communicator.service.netaddr.event.*;
import net.java.sip.communicator.service.notification.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.resources.*;
import org.osgi.framework.*;
/**
* Activates the reconnect plug-in.
*
* @author Damian Minkov
*/
public class ReconnectPluginActivator
implements BundleActivator,
ServiceListener,
NetworkConfigurationChangeListener
{
/**
* Logger of this class
*/
private static final Logger logger
= Logger.getLogger(ReconnectPluginActivator.class);
/**
* The current BundleContext.
*/
private static BundleContext bundleContext = null;
/**
* The ui service.
*/
private static UIService uiService;
/**
* The resources service.
*/
private static ResourceManagementService resourcesService;
/**
* A reference to the ConfigurationService implementation instance that
* is currently registered with the bundle context.
*/
private static ConfigurationService configurationService = null;
/**
* Notification service.
*/
private static NotificationService notificationService;
/**
* Network address manager service will inform us for changes in
* network configuration.
*/
private NetworkAddressManagerService networkAddressManagerService = null;
/**
* Holds every protocol provider wrapper which can be reconnected and
* a list of the available and up interfaces when the provider was
* registered. When a provider is unregistered by user request it is removed
* from this collection. Or when the provider service is removed from OSGi.
* Or if provider failed registering and there were yet no successful
* connections of this provider.
* Providers REMOVED:
* - When provider is removed from osgi
* - When a provider is UNREGISTERED by user request
* Providers ADDED:
* - When a provider is REGISTERED
*/
private static final Map<PPReconnectWrapper, List<String>>
reconnectEnabledProviders = new HashMap<>();
/**
* A list of currently connected interfaces. If empty network is down.
*/
private static final Set<String> connectedInterfaces = new HashSet<>();
/**
* Start of the delay interval when starting a reconnect.
*/
static final int RECONNECT_DELAY_MIN = 2; // sec
/**
* The end of the interval for the initial reconnect.
*/
static final int RECONNECT_DELAY_MAX = 4; // sec
/**
* Max value for growing the reconnect delay, all subsequent reconnects
* use this maximum delay.
*/
static final int MAX_RECONNECT_DELAY = 300; // sec
/**
* Network notifications event type.
*/
public static final String NETWORK_NOTIFICATIONS = "NetworkNotifications";
/**
* Whether the provider connected at least once, which means settings are
* correct, otherwise it maybe server address wrong or username/password
* and there is no point of reconnecting.
*/
public static final String ATLEAST_ONE_CONNECTION_PROP =
"net.java.sip.communicator.plugin.reconnectplugin." +
"ATLEAST_ONE_SUCCESSFUL_CONNECTION";
/**
* Timer used to filter out too frequent "network down" notifications
* on Android.
*/
private Timer delayedNetworkDown;
/**
* Delay used for filtering out "network down" notifications.
*/
private static final long NETWORK_DOWN_THRESHOLD = 30 * 1000;
/**
* Starts this bundle.
*
* @param bundleContext the <tt>BundleContext</tt> in which this bundle is
* to be started
* @throws Exception if anything goes wrong while starting this bundle
*/
public void start(BundleContext bundleContext)
throws Exception
{
try
{
logger.logEntry();
ReconnectPluginActivator.bundleContext = bundleContext;
}
finally
{
logger.logExit();
}
bundleContext.addServiceListener(this);
this.networkAddressManagerService
= ServiceUtils.getService(
bundleContext,
NetworkAddressManagerService.class);
this.networkAddressManagerService
.addNetworkConfigurationChangeListener(this);
ServiceReference[] protocolProviderRefs = null;
try
{
protocolProviderRefs = bundleContext.getServiceReferences(
ProtocolProviderService.class.getName(), null);
}
catch (InvalidSyntaxException ex)
{
// this shouldn't happen since we're providing no parameter string
// but let's log just in case.
logger.error(
"Error while retrieving service refs", ex);
return;
}
// in case we found any
if (protocolProviderRefs != null)
{
if (logger.isDebugEnabled())
logger.debug("Found "
+ protocolProviderRefs.length
+ " already installed providers.");
for (int i = 0; i < protocolProviderRefs.length; i++)
{
ProtocolProviderService provider
= (ProtocolProviderService) bundleContext
.getService(protocolProviderRefs[i]);
this.handleProviderAdded(provider);
}
}
}
/**
* Stops this bundle.
*
* @param bundleContext the <tt>BundleContext</tt> in which this bundle is
* to be stopped
* @throws Exception if anything goes wrong while stopping this bundle
*/
public void stop(BundleContext bundleContext)
throws Exception
{
}
/**
* Returns the <tt>UIService</tt> obtained from the bundle context.
*
* @return the <tt>UIService</tt> obtained from the bundle context
*/
public static UIService getUIService()
{
if (uiService == null)
{
ServiceReference uiReference =
bundleContext.getServiceReference(UIService.class.getName());
uiService =
(UIService) bundleContext
.getService(uiReference);
}
return uiService;
}
/**
* Returns resource service.
* @return the resource service.
*/
public static ResourceManagementService getResources()
{
if (resourcesService == null)
{
ServiceReference serviceReference = bundleContext
.getServiceReference(ResourceManagementService.class.getName());
if(serviceReference == null)
return null;
resourcesService = (ResourceManagementService) bundleContext
.getService(serviceReference);
}
return resourcesService;
}
/**
* Returns a reference to a ConfigurationService implementation currently
* registered in the bundle context or null if no such implementation was
* found.
*
* @return a currently valid implementation of the ConfigurationService.
*/
public static ConfigurationService getConfigurationService()
{
if (configurationService == null)
{
ServiceReference confReference
= bundleContext.getServiceReference(
ConfigurationService.class.getName());
configurationService
= (ConfigurationService) bundleContext
.getService(confReference);
}
return configurationService;
}
/**
* Returns the <tt>NotificationService</tt> obtained from the bundle context.
*
* @return the <tt>NotificationService</tt> obtained from the bundle context
*/
public static NotificationService getNotificationService()
{
if (notificationService == null)
{
ServiceReference serviceReference = bundleContext
.getServiceReference(NotificationService.class.getName());
notificationService = (NotificationService) bundleContext
.getService(serviceReference);
notificationService.registerDefaultNotificationForEvent(
NETWORK_NOTIFICATIONS,
NotificationAction.ACTION_POPUP_MESSAGE,
null,
null);
}
return notificationService;
}
/**
* When new protocol provider is registered we add needed listeners.
*
* @param serviceEvent ServiceEvent
*/
public void serviceChanged(ServiceEvent serviceEvent)
{
ServiceReference serviceRef = serviceEvent.getServiceReference();
// if the event is caused by a bundle being stopped, we don't want to
// know we are shutting down
if (serviceRef.getBundle().getState() == Bundle.STOPPING)
{
return;
}
Object sService = bundleContext.getService(serviceRef);
if(sService instanceof NetworkAddressManagerService)
{
switch (serviceEvent.getType())
{
case ServiceEvent.REGISTERED:
if(this.networkAddressManagerService != null)
break;
this.networkAddressManagerService =
(NetworkAddressManagerService)sService;
networkAddressManagerService
.addNetworkConfigurationChangeListener(this);
break;
case ServiceEvent.UNREGISTERING:
((NetworkAddressManagerService)sService)
.removeNetworkConfigurationChangeListener(this);
break;
}
return;
}
// we don't care if the source service is not a protocol provider
if (!(sService instanceof ProtocolProviderService))
return;
switch (serviceEvent.getType())
{
case ServiceEvent.REGISTERED:
this.handleProviderAdded((ProtocolProviderService)sService);
break;
case ServiceEvent.UNREGISTERING:
this.handleProviderRemoved( (ProtocolProviderService) sService);
break;
}
}
/**
* Add listeners to newly registered protocols.
*
* @param provider ProtocolProviderService
*/
private void handleProviderAdded(ProtocolProviderService provider)
{
if (logger.isTraceEnabled())
logger.trace("New protocol provider is coming " + provider);
// we just create the instance, if the instance successfully registers
// will use addReconnectEnabledProvider to add itself to those we will
// handle
new PPReconnectWrapper(provider);
}
/**
* Stop listening for events as the provider is removed.
* Providers are removed this way only when there are modified
* in the configuration. So as the provider is modified we will erase
* every instance we got.
*
* @param provider the ProtocolProviderService that has been unregistered.
*/
private void handleProviderRemoved(ProtocolProviderService provider)
{
if (logger.isTraceEnabled())
logger.trace("Provider modified forget every instance of it "
+ provider);
if(hasAtLeastOneSuccessfulConnection(provider))
{
setAtLeastOneSuccessfulConnection(provider, false);
}
synchronized(reconnectEnabledProviders)
{
Iterator<PPReconnectWrapper> iter
= reconnectEnabledProviders.keySet().iterator();
while(iter.hasNext())
{
PPReconnectWrapper wrapper = iter.next();
if (wrapper.getProvider().equals(provider))
{
iter.remove();
wrapper.clear();
}
}
}
}
/**
* Adds a wrapper to the list of the wrappers we will handle reconnecting.
* Marks one successful connection if needed.
* @param wrapper the provider wrapper.
*/
static void addReconnectEnabledProvider(PPReconnectWrapper wrapper)
{
ProtocolProviderService pp = wrapper.getProvider();
synchronized(reconnectEnabledProviders)
{
if (!hasAtLeastOneSuccessfulConnection(pp))
{
setAtLeastOneSuccessfulConnection(pp, true);
}
reconnectEnabledProviders.put(
wrapper, new ArrayList<>(connectedInterfaces));
}
}
/**
* Removes the wrapper from the list, will not reconnect it.
* @param wrapper the wrapper to remove.
*/
static void removeReconnectEnabledProviders(PPReconnectWrapper wrapper)
{
synchronized(reconnectEnabledProviders)
{
reconnectEnabledProviders.remove(wrapper);
}
}
/**
* Fired when a change has occurred in the computer network configuration.
*
* @param event the change event.
*/
public synchronized void configurationChanged(ChangeEvent event)
{
if(event.getType() == ChangeEvent.IFACE_UP)
{
// no connection so one is up, lets connect
if (!anyConnectedInterfaces())
{
onNetworkUp();
List<PPReconnectWrapper> wrappers;
synchronized (reconnectEnabledProviders)
{
wrappers = new LinkedList<>(
reconnectEnabledProviders.keySet());
}
wrappers.stream().forEach(PPReconnectWrapper::reconnect);
}
connectedInterfaces.add((String)event.getSource());
}
else if(event.getType() == ChangeEvent.IFACE_DOWN)
{
String ifaceName = (String)event.getSource();
connectedInterfaces.remove(ifaceName);
// one is down and at least one more is connected
if (anyConnectedInterfaces())
{
// lets reconnect all that were connected when this one was
// available, cause they maybe using it
List<PPReconnectWrapper> wrappers;
synchronized (reconnectEnabledProviders)
{
wrappers = reconnectEnabledProviders.entrySet().stream()
.filter(entry -> entry.getValue().contains(ifaceName))
.map(entry -> entry.getKey())
.collect(Collectors.toList());
}
wrappers.stream().forEach(PPReconnectWrapper::reconnect);
}
else
{
// we must disconnect every pp that is trying to reconnect
// and they will reconnect when network is back
List<PPReconnectWrapper> wrappers;
synchronized (reconnectEnabledProviders)
{
wrappers = new LinkedList<>(
reconnectEnabledProviders.keySet());
}
wrappers.stream().forEach(PPReconnectWrapper::unregister);
onNetworkDown();
}
}
if(logger.isTraceEnabled())
{
logger.trace("Event received " + event
+ " src=" + event.getSource());
traceCurrentPPState();
}
}
/**
* Whether we have any connected interface.
* @return <tt>true</tt> when there is at least one connected interface at
* the moment.
*/
static boolean anyConnectedInterfaces()
{
return !connectedInterfaces.isEmpty();
}
/**
* Trace prints of current status of the lists with protocol providers,
* that are currently in interest of the reconnect plugin.
*/
private void traceCurrentPPState()
{
logger.trace("connectedInterfaces: " + connectedInterfaces);
logger.trace("reconnectEnabledProviders: "
+ reconnectEnabledProviders.keySet());
logger.trace("----");
}
/**
* Sends network notification.
* @param title the title.
* @param i18nKey the resource key of the notification.
* @param params and parameters in any.
* @param tag extra notification tag object
*/
private static void notify(String title, String i18nKey, String[] params,
Object tag)
{
Map<String,Object> extras = new HashMap<String,Object>();
extras.put(
NotificationData.POPUP_MESSAGE_HANDLER_TAG_EXTRA,
tag);
getNotificationService().fireNotification(
NETWORK_NOTIFICATIONS,
title,
getResources().getI18NString(i18nKey, params),
null,
extras);
}
/**
* Notifies for connection failed or failed to non existing user.
* @param evt the event to notify for.
*/
static void notifyConnectionFailed(RegistrationStateChangeEvent evt)
{
if (!evt.getNewState().equals(RegistrationState.CONNECTION_FAILED))
{
return;
}
ProtocolProviderService pp = (ProtocolProviderService)evt.getSource();
if (evt.getReasonCode() ==
RegistrationStateChangeEvent.REASON_NON_EXISTING_USER_ID)
{
notify(
getResources().getI18NString("service.gui.ERROR"),
"service.gui.NON_EXISTING_USER_ID",
new String[]{pp.getAccountID().getService()},
pp.getAccountID());
}
else
{
notify(
getResources().getI18NString("service.gui.ERROR"),
"plugin.reconnectplugin.CONNECTION_FAILED_MSG",
new String[]
{ pp.getAccountID().getUserID(),
pp.getAccountID().getService() },
pp.getAccountID());
}
}
/**
* Check does the supplied protocol has the property set for at least
* one successful connection.
* @param pp the protocol provider
* @return true if property exists.
*/
static boolean hasAtLeastOneSuccessfulConnection(
ProtocolProviderService pp)
{
String value = (String)getConfigurationService().getProperty(
ATLEAST_ONE_CONNECTION_PROP + "."
+ pp.getAccountID().getAccountUniqueID());
if(value == null || !value.equals(Boolean.TRUE.toString()))
return false;
else
return true;
}
/**
* Changes the property about at least one successful connection.
* @param pp the protocol provider
* @param value the new value true or false.
*/
private static void setAtLeastOneSuccessfulConnection(
ProtocolProviderService pp, boolean value)
{
getConfigurationService().setProperty(
ATLEAST_ONE_CONNECTION_PROP + "."
+ pp.getAccountID().getAccountUniqueID(),
Boolean.valueOf(value).toString());
}
/**
* Called when first connected interface is added to
* {@link #connectedInterfaces} list.
*/
private void onNetworkUp()
{
if(delayedNetworkDown != null)
{
delayedNetworkDown.cancel();
delayedNetworkDown = null;
}
}
/**
* Called when first there are no more connected interface present in
* {@link #connectedInterfaces} list.
*/
private void onNetworkDown()
{
if(!org.jitsi.util.OSUtils.IS_ANDROID)
{
notifyNetworkDown();
}
else
{
// Android never keeps two active connection at the same time
// and it may take some time to attach next connection
// even if it was already enabled by user
if(delayedNetworkDown == null)
{
delayedNetworkDown = new Timer();
delayedNetworkDown.schedule(new TimerTask()
{
@Override
public void run()
{
notifyNetworkDown();
}
}, NETWORK_DOWN_THRESHOLD);
}
}
}
/**
* Posts "network is down" notification.
*/
private void notifyNetworkDown()
{
if (logger.isTraceEnabled())
logger.trace("Network is down!");
notify("", "plugin.reconnectplugin.NETWORK_DOWN",
new String[0], this);
}
}