aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/jabber/ServerStoredContactListJabberImpl.java
blob: e43632b88932ad4b4abbaed2bc1f870f28516fe7 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * 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.impl.protocol.jabber;

import java.util.*;

import net.java.sip.communicator.service.customavatar.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.util.*;
import org.jivesoftware.smackx.packet.*;
import org.osgi.framework.*;

/**
 * This class encapsulates the Roster class. Once created, it will
 * register itself as a listener to the encapsulated Roster and modify it's
 * local copy of Contacts and ContactGroups every time an event is generated
 * by the underlying framework. The class would also generate
 * corresponding sip-communicator events to all events coming from smack.
 *
 * @author Damian Minkov
 * @author Emil Ivov
 * @author Hristo Terezov
 */
public class ServerStoredContactListJabberImpl
{
    /**
     * The logger.
     */
    private static final Logger logger =
        Logger.getLogger(ServerStoredContactListJabberImpl.class);

    /**
     * The jabber list that we encapsulate
     */
    private Roster roster = null;

    /**
     * The root <code>ContactGroup</code>. The container for all jabber buddies
     * and groups.
     */
    private final RootContactGroupJabberImpl rootGroup;

    /**
     * The operation set that created us and that we could use when dispatching
     * subscription events.
     */
    private final OperationSetPersistentPresenceJabberImpl parentOperationSet;

    /**
     * The provider that is on top of us.
     */
    private final ProtocolProviderServiceJabberImpl jabberProvider;

    /**
     * Listeners that would receive event notifications for changes in group
     * names or other properties, removal or creation of groups.
     */
    private Vector<ServerStoredGroupListener> serverStoredGroupListeners
        = new Vector<ServerStoredGroupListener>();

    /**
     *  Thread retreiving images for contacts
     */
    private ImageRetriever imageRetriever = null;

    /**
     * Listens for roster changes.
     */
    private ChangeListener rosterChangeListener = null;

    /**
     * Retrieve contact information.
     */
    private InfoRetreiver infoRetreiver = null;

    /**
     * Whether roster has been requested and dispatched.
     */
    private boolean isRosterInitialized = false;

    /**
     * Lock object for the isRosterInitialized variable.
     */
    private Object rosterInitLock = new Object();

    /**
     * The initial status saved.
     */
    private PresenceStatus initialStatus = null;

    /**
     * The initial status message saved.
     */
    private String initialStatusMessage = null;

    /**
     * Creates a ServerStoredContactList wrapper for the specified BuddyList.
     *
     * @param parentOperationSet the operation set that created us and that
     * we could use for dispatching subscription events
     * @param provider the provider that has instantiated us.
     * @param infoRetreiver retrieve contact information.
     */
    ServerStoredContactListJabberImpl(
        OperationSetPersistentPresenceJabberImpl parentOperationSet,
        ProtocolProviderServiceJabberImpl        provider,
        InfoRetreiver infoRetreiver)
    {
        //We need to init these as early as possible to ensure that the provider
        //and the operationsset would not be null in the incoming events.
        this.parentOperationSet = parentOperationSet;

        this.jabberProvider = provider;
        this.rootGroup = new RootContactGroupJabberImpl(this.jabberProvider);
        this.infoRetreiver = infoRetreiver;
    }

    /**
     * Returns the root group of the contact list.
     *
     * @return the root ContactGroup for the ContactList
     */
    public ContactGroup getRootGroup()
    {
        return rootGroup;
    }

    /**
     * Returns the roster entry associated with the given XMPP address or
     * <tt>null</tt> if the user is not an entry in the roster.
     *
     * @param user the XMPP address of the user (e.g. "jsmith@example.com").
     * The address could be in any valid format (e.g. "domain/resource",
     * "user@domain" or "user@domain/resource").
     *
     * @return the roster entry or <tt>null</tt> if it does not exist.
     */
    RosterEntry getRosterEntry(String user)
    {
        if(roster == null)
            return null;
        else
            return roster.getEntry(user);
    }

    /**
     * Returns the roster group with the specified name, or <tt>null</tt> if the
     * group doesn't exist.
     *
     * @param name the name of the group.
     * @return the roster group with the specified name.
     */
    RosterGroup getRosterGroup(String name)
    {
        return roster.getGroup(name);
    }

    /**
     * Registers the specified group listener so that it would receive events
     * on group modification/creation/destruction.
     * @param listener the ServerStoredGroupListener to register for group events
     */
    void addGroupListener(ServerStoredGroupListener listener)
    {
        synchronized(serverStoredGroupListeners)
        {
            if(!serverStoredGroupListeners.contains(listener))
            this.serverStoredGroupListeners.add(listener);
        }
    }

    /**
     * Removes the specified group listener so that it won't receive further
     * events on group modification/creation/destruction.
     * @param listener the ServerStoredGroupListener to unregister
     */
    void removeGroupListener(ServerStoredGroupListener listener)
    {
        synchronized(serverStoredGroupListeners)
        {
            this.serverStoredGroupListeners.remove(listener);
        }
    }

    /**
     * Creates the corresponding event and notifies all
     * <tt>ServerStoredGroupListener</tt>s that the source group has been
     * removed, changed, renamed or whatever happened to it.
     * @param group the ContactGroup that has been created/modified/removed
     * @param eventID the id of the event to generate.
     */
    void fireGroupEvent(ContactGroupJabberImpl group, int eventID)
    {
        //bail out if no one's listening
        if(parentOperationSet == null){
            if (logger.isDebugEnabled())
                logger.debug("No presence op. set available. Bailing out.");
            return;
        }

        ServerStoredGroupEvent evt = new ServerStoredGroupEvent(
                  group
                , eventID
                , parentOperationSet.getServerStoredContactListRoot()
                , jabberProvider
                , parentOperationSet);

        if (logger.isTraceEnabled())
            logger.trace("Will dispatch the following grp event: " + evt);

        Iterable<ServerStoredGroupListener> listeners;
        synchronized (serverStoredGroupListeners)
        {
            listeners
                = new ArrayList<ServerStoredGroupListener>(
                        serverStoredGroupListeners);
        }

        /**
         * Sometimes contact statuses are received before the groups and
         * contacts are being created. This is a problem when we don't have
         * already created unresolved contacts. So we will check contact
         * statuses to be sure they are correct.
         */
        if(eventID == ServerStoredGroupEvent.GROUP_CREATED_EVENT)
        {
            Iterator<Contact> iter = group.contacts();
            while (iter.hasNext())
            {
                ContactJabberImpl c = (ContactJabberImpl)iter.next();

                // roster can be null, receiving system messages from server
                // before we are log in
                if(roster != null)
                {
                    parentOperationSet.firePresenceStatusChanged(
                            roster.getPresence(c.getAddress()));
                }
            }
        }

        for (ServerStoredGroupListener listener : listeners)
        {
            if (eventID == ServerStoredGroupEvent.GROUP_REMOVED_EVENT)
                listener.groupRemoved(evt);
            else if (eventID == ServerStoredGroupEvent.GROUP_RENAMED_EVENT)
                listener.groupNameChanged(evt);
            else if (eventID == ServerStoredGroupEvent.GROUP_CREATED_EVENT)
                listener.groupCreated(evt);
            else if (eventID == ServerStoredGroupEvent.GROUP_RESOLVED_EVENT)
                listener.groupResolved(evt);
        }
    }

    /**
     * Make the parent persistent presence operation set dispatch a contact
     * removed event.
     * @param parentGroup the group where that the removed contact belonged to.
     * @param contact the contact that was removed.
     */
    void fireContactRemoved( ContactGroup parentGroup,
                                     ContactJabberImpl contact)
    {
        //bail out if no one's listening
        if(parentOperationSet == null){
            if (logger.isDebugEnabled())
                logger.debug("No presence op. set available. Bailing out.");
            return;
        }
        if (logger.isTraceEnabled())
            logger.trace("Removing " + contact.getAddress()
                        + " from " + parentGroup.getGroupName());

        // dispatch
        parentOperationSet.fireSubscriptionEvent(contact, parentGroup,
            SubscriptionEvent.SUBSCRIPTION_REMOVED);
    }

    /**
     * Make the parent persistent presence operation set dispatch a subscription
     * moved event.
     * @param oldParentGroup the group where the source contact was located
     * before being moved
     * @param newParentGroup the group that the source contact is currently in.
     * @param contact the contact that was added
     */
    private void fireContactMoved( ContactGroup oldParentGroup,
                                   ContactGroup newParentGroup,
                                   ContactJabberImpl contact)
    {
        //bail out if no one's listening
        if(parentOperationSet == null){
            if (logger.isDebugEnabled())
                logger.debug("No presence op. set available. Bailing out.");
            return;
        }

        //dispatch
        parentOperationSet.fireSubscriptionMovedEvent(
            contact, oldParentGroup, newParentGroup);
    }

    /**
     * Retrns a reference to the provider that created us.
     * @return a reference to a ProtocolProviderServiceImpl instance.
     */
    ProtocolProviderServiceJabberImpl getParentProvider()
    {
        return jabberProvider;
    }

    /**
     * Returns the ConntactGroup with the specified name or null if no such
     * group was found.
     * <p>
     * @param name the name of the group we're looking for.
     * @return a reference to the ContactGroupJabberImpl instance we're looking for
     * or null if no such group was found.
     */
    public ContactGroupJabberImpl findContactGroup(String name)
    {
        Iterator<ContactGroup> contactGroups = rootGroup.subgroups();

        // make sure we ignore any whitespaces
        name = name.trim();

        while(contactGroups.hasNext())
        {
            ContactGroupJabberImpl contactGroup
                = (ContactGroupJabberImpl) contactGroups.next();

            if (contactGroup.getGroupName().trim().equals(name))
                return contactGroup;
        }

        return null;
    }

    /**
     * Find a group with the specified Copy of Name. Used to track when
     * a group name has changed
     * @param name String
     * @return ContactGroupJabberImpl
     */
    private ContactGroupJabberImpl findContactGroupByNameCopy(String name)
    {
        Iterator<ContactGroup> contactGroups = rootGroup.subgroups();

        // make sure we ignore any whitespaces
        name = name.trim();

        while(contactGroups.hasNext())
        {
            ContactGroupJabberImpl contactGroup
                = (ContactGroupJabberImpl) contactGroups.next();

            if (contactGroup.getNameCopy() != null
                && contactGroup.getNameCopy().trim().equals(name))
                return contactGroup;

        }
        return null;
    }

    /**
     * Returns the Contact with the specified id or null if
     * no such id was found.
     *
     * @param id the id of the contact to find.
     * @return the <tt>Contact</tt> carrying the specified
     * <tt>screenName</tt> or <tt>null</tt> if no such contact exits.
     */
    public ContactJabberImpl findContactById(String id)
    {
        Iterator<ContactGroup> contactGroups = rootGroup.subgroups();
        ContactJabberImpl result = null;
        String userId = StringUtils.parseBareAddress(id);

        while(contactGroups.hasNext())
        {
            ContactGroupJabberImpl contactGroup
                = (ContactGroupJabberImpl)contactGroups.next();

            result = contactGroup.findContact(userId);

            if (result != null)
                return result;
        }

        //check for private contacts
        ContactGroupJabberImpl volatileGroup
            = getNonPersistentGroup();
        if(volatileGroup != null)
        {
            result = volatileGroup.findContact(id);

            if (result != null)
                return result;
        }

        //try the root group now
        return rootGroup.findContact(userId);
    }

    /**
     * Returns the ContactGroup containing the specified contact or null
     * if no such group or contact exist.
     *
     * @param child the contact whose parent group we're looking for.
     * @return the <tt>ContactGroup</tt> containing the specified
     * <tt>contact</tt> or <tt>null</tt> if no such groupo or contact
     * exist.
     */
    public ContactGroup findContactGroup(ContactJabberImpl child)
    {
        Iterator<ContactGroup> contactGroups = rootGroup.subgroups();
        String contactAddress = child.getAddress();

        while(contactGroups.hasNext())
        {
            ContactGroupJabberImpl contactGroup
                = (ContactGroupJabberImpl)contactGroups.next();

            if( contactGroup.findContact(contactAddress)!= null)
                return contactGroup;
        }

        if ( rootGroup.findContact(contactAddress) != null)
            return rootGroup;

        return null;
    }

    /**
     * Adds a new contact with the specified screenname to the list under a
     * default location.
     * @param id the id of the contact to add.
     * @throws OperationFailedException
     */
    public void addContact(String id)
        throws OperationFailedException
    {
        addContact(null, id);
    }

    /**
     * Adds a new contact with the specified screenname to the list under the
     * specified group.
     * @param id the id of the contact to add.
     * @param parent the group under which we want the new contact placed.
     * @throws OperationFailedException if the contact already exist
     */
    public void addContact(ContactGroup parent, String id)
        throws OperationFailedException
    {
        if (logger.isTraceEnabled())
            logger.trace("Adding contact " + id + " to parent=" + parent);

        final String completeID = parseAddressString(id);
        //if the contact is already in the contact list and is not volatile,
        //then only broadcast an event
        ContactJabberImpl existingContact = findContactById(completeID);

        if( existingContact != null
            && existingContact.isPersistent() )
        {
            if(logger.isDebugEnabled())
                logger.debug("Contact " + completeID
                                + " already exists in group "
                                + findContactGroup(existingContact));
            throw new OperationFailedException(
                "Contact " + completeID + " already exists.",
                OperationFailedException.SUBSCRIPTION_ALREADY_EXISTS);
        }

        try
        {
            String[] parentNames = null;

            if(parent != null && parent != getRootGroup())
                parentNames = new String[]{parent.getGroupName()};

            PacketInterceptor presenceInterceptor = new PacketInterceptor()
            {

                @Override
                public void interceptPacket(Packet packet)
                {
                    Presence presence = (Presence) packet;
                    if(presence.getType() == Presence.Type.subscribe
                        && completeID.equals(StringUtils.parseBareAddress(
                            presence.getTo())))
                    {
                        Nick nicknameExt
                            = new Nick(
                                JabberActivator.getGlobalDisplayDetailsService()
                                    .getDisplayName(jabberProvider));
                        presence.addExtension(nicknameExt);
                    }
                }
            };
            jabberProvider.getConnection().addPacketInterceptor(
                presenceInterceptor, new PacketTypeFilter(Presence.class));
            // modify our reply timeout because some XMPP may send "result" IQ
            // late (> 5 secondes).
            SmackConfiguration.setPacketReplyTimeout(
                ProtocolProviderServiceJabberImpl.SMACK_PACKET_REPLY_TIMEOUT);

            this.roster.createEntry(completeID, completeID, parentNames);

            SmackConfiguration.setPacketReplyTimeout(5000);

            jabberProvider.getConnection().removePacketInterceptor(
                presenceInterceptor);
        }
        catch (XMPPException ex)
        {
            String errTxt = "Error adding new jabber entry";
            logger.error(errTxt, ex);

            int errorCode = OperationFailedException.INTERNAL_ERROR;

            XMPPError err = ex.getXMPPError();
            if(err != null)
            {
                if(err.getCode() > 400 && err.getCode() < 500)
                    errorCode = OperationFailedException.FORBIDDEN;
                else if(err.getCode() > 500)
                    errorCode = OperationFailedException.INTERNAL_SERVER_ERROR;

                errTxt = err.getCondition();
            }

            throw new OperationFailedException(errTxt, errorCode, ex);
        }
    }

    /**
     * Creates a non persistent contact for the specified address. This would
     * also create (if necessary) a group for volatile contacts that would not
     * be added to the server stored contact list. This method would have no
     * effect on the server stored contact list.
     * @param id the address of the contact to create.
     * @param isPrivateMessagingContact indicates if the contact should be
     * private messaging contact or not.
     * @param displayName the display name of the contact
     * @return the newly created volatile <tt>ContactImpl</tt>
     */
    ContactJabberImpl createVolatileContact(String id,
        boolean isPrivateMessagingContact, String displayName)
    {
        VolatileContactJabberImpl newVolatileContact
            = new VolatileContactJabberImpl(id, this, isPrivateMessagingContact,
                displayName);

        //Check whether a volatile group already exists and if not create
        //one
        ContactGroupJabberImpl theVolatileGroup = getNonPersistentGroup();

        //if the parent group is null then add necessary create the group
        if (theVolatileGroup == null)
        {
            theVolatileGroup = new VolatileContactGroupJabberImpl(
                JabberActivator.getResources().getI18NString(
                    "service.gui.NOT_IN_CONTACT_LIST_GROUP_NAME"),
                this);

            theVolatileGroup.addContact(newVolatileContact);

            this.rootGroup.addSubGroup(theVolatileGroup);

            fireGroupEvent(theVolatileGroup
                           , ServerStoredGroupEvent.GROUP_CREATED_EVENT);
        }
        else
        {
            theVolatileGroup.addContact(newVolatileContact);

            fireContactAdded(theVolatileGroup, newVolatileContact);
        }

        return newVolatileContact;
    }

    /**
     * Checks if the contact address is associated with private messaging
     * contact or not.
     * @param contactAddress the address of the contact.
     * @return <tt>true</tt> the contact address is associated with private
     * messaging contact and <tt>false</tt> if not.
     */
    public boolean isPrivateMessagingContact(String contactAddress)
    {
        ContactGroupJabberImpl theVolatileGroup = getNonPersistentGroup();
        if (theVolatileGroup == null)
            return false;
        ContactJabberImpl contact = theVolatileGroup.findContact(contactAddress);
        if(contact == null || !(contact instanceof VolatileContactJabberImpl))
            return false;
        return ((VolatileContactJabberImpl) contact).isPrivateMessagingContact();
    }

    /**
     * Creates a non resolved contact for the specified address and inside the
     * specified group. The newly created contact would be added to the local
     * contact list as a standard contact but when an event is received from the
     * server concerning this contact, then it will be reused and only its
     * isResolved field would be updated instead of creating the whole contact
     * again.
     *
     * @param parentGroup the group where the unersolved contact is to be
     * created
     * @param id the Address of the contact to create.
     * @return the newly created unresolved <tt>ContactImpl</tt>
     */
    synchronized ContactJabberImpl createUnresolvedContact(
        ContactGroup parentGroup, String  id)
    {
        String completeID = parseAddressString(id);

        ContactJabberImpl existingContact = findContactById(completeID);

        if( existingContact != null)
        {
            return existingContact;
        }

        ContactJabberImpl newUnresolvedContact
            = new ContactJabberImpl(id, this, true);

        if(parentGroup instanceof ContactGroupJabberImpl)
            ((ContactGroupJabberImpl)parentGroup).
                addContact(newUnresolvedContact);
        else if(parentGroup instanceof RootContactGroupJabberImpl)
            ((RootContactGroupJabberImpl)parentGroup).
                addContact(newUnresolvedContact);

        fireContactAdded(parentGroup, newUnresolvedContact);

        return newUnresolvedContact;
    }

    /**
     * Creates a non resolved contact group for the specified name. The newly
     * created group would be added to the local contact list as any other group
     * but when an event is received from the server concerning this group, then
     * it will be reused and only its isResolved field would be updated instead
     * of creating the whole group again.
     * <p>
     * @param groupName the name of the group to create.
     * @return the newly created unresolved <tt>ContactGroupImpl</tt>
     */
    synchronized ContactGroupJabberImpl createUnresolvedContactGroup(
        String groupName)
    {
        ContactGroupJabberImpl existingGroup = findContactGroup(groupName);

        if( existingGroup != null)
        {
            return existingGroup;
        }

        ContactGroupJabberImpl newUnresolvedGroup =
            new ContactGroupJabberImpl(groupName, this);

        this.rootGroup.addSubGroup(newUnresolvedGroup);

        fireGroupEvent(newUnresolvedGroup
                        , ServerStoredGroupEvent.GROUP_CREATED_EVENT);

        return newUnresolvedGroup;
    }

    /**
     * Creates the specified group on the server stored contact list.
     * @param groupName a String containing the name of the new group.
     * @throws OperationFailedException with code CONTACT_GROUP_ALREADY_EXISTS
     * if the group we're trying to create is already in our contact list.
     */
    public void createGroup(String groupName)
        throws OperationFailedException
    {
        if (logger.isTraceEnabled())
            logger.trace("Creating group: " + groupName);

        ContactGroupJabberImpl existingGroup = findContactGroup(groupName);

        if( existingGroup != null && existingGroup.isPersistent() )
        {
            if (logger.isDebugEnabled())
                logger.debug("ContactGroup " + groupName + " already exists.");
            throw new OperationFailedException(
                           "ContactGroup " + groupName + " already exists.",
                OperationFailedException.CONTACT_GROUP_ALREADY_EXISTS);
        }

        RosterGroup newRosterGroup = roster.createGroup(groupName);

        ContactGroupJabberImpl newGroup =
            new ContactGroupJabberImpl(newRosterGroup,
                                       new ArrayList<RosterEntry>().iterator(),
                                       this,
                                       true);
        rootGroup.addSubGroup(newGroup);

        fireGroupEvent(newGroup, ServerStoredGroupEvent.GROUP_CREATED_EVENT);

        if (logger.isTraceEnabled())
            logger.trace("Group " +groupName+ " created.");
    }

    /**
     * Removes the specified group from the buddy list.
     * @param groupToRemove the group that we'd like removed.
     */
    public void removeGroup(ContactGroupJabberImpl groupToRemove)
        throws OperationFailedException
    {
        try
        {
            // first copy the item that will be removed
            // when iterating over group contacts and removing them
            // concurrent exception occures
            Vector<Contact> localCopy = new Vector<Contact>();
            Iterator<Contact> iter = groupToRemove.contacts();

            while (iter.hasNext())
            {
                localCopy.add(iter.next());
            }

            iter = localCopy.iterator();
            while (iter.hasNext())
            {
                ContactJabberImpl item = (ContactJabberImpl) iter.next();
                if(item.isPersistent())
                    roster.removeEntry(item.getSourceEntry());
            }
        }
        catch (XMPPException ex)
        {
            logger.error("Error removing group", ex);
            throw new OperationFailedException(
                ex.getMessage(), OperationFailedException.GENERAL_ERROR, ex);
        }
    }

    /**
     * Removes a contact from the serverside list
     * Event will come for successful operation
     * @param contactToRemove ContactJabberImpl
     */
    void removeContact(ContactJabberImpl contactToRemove)
        throws OperationFailedException
    {
        if(contactToRemove instanceof VolatileContactJabberImpl)
        {
            contactDeleted(contactToRemove);
            return;
        }

        try
        {
            RosterEntry entry = contactToRemove.getSourceEntry();

            if (entry != null)//don't try to remove non-existing contacts.
                this.roster.removeEntry(entry);
        }
        catch (XMPPException ex)
        {
            String errTxt = "Error removing contact";
            logger.error(errTxt, ex);

            int errorCode = OperationFailedException.INTERNAL_ERROR;

            XMPPError err = ex.getXMPPError();
            if(err != null)
            {
                if(err.getCode() > 400 && err.getCode() < 500)
                    errorCode = OperationFailedException.FORBIDDEN;
                else if(err.getCode() > 500)
                    errorCode = OperationFailedException.INTERNAL_SERVER_ERROR;

                errTxt = err.getCondition();
            }

            throw new OperationFailedException(errTxt, errorCode, ex);
        }
    }


    /**
     * Renames the specified group according to the specified new name..
     * @param groupToRename the group that we'd like removed.
     * @param newName the new name of the group
     */
    public void renameGroup(ContactGroupJabberImpl groupToRename, String newName)
    {
        groupToRename.getSourceGroup().setName(newName);
        groupToRename.setNameCopy(newName);
    }

    /**
     * Moves the specified <tt>contact</tt> to the group indicated by
     * <tt>newParent</tt>.
     * @param contact the contact that we'd like moved under the new group.
     * @param newParent the group where we'd like the parent placed.
     */
    public void moveContact(ContactJabberImpl contact,
                            AbstractContactGroupJabberImpl newParent)
        throws OperationFailedException
    {
        // when the contact is not persistent, coming
        // from NotInContactList group, we need just to add it to the list
        if(!contact.isPersistent())
        {
            String contactAddress = null;
            if(contact instanceof VolatileContactJabberImpl &&
                ((VolatileContactJabberImpl)contact).isPrivateMessagingContact())
            {
               contactAddress = contact.getPersistableAddress();
            }
            else
            {
                contactAddress = contact.getAddress();
            }

            try
            {
                addContact(newParent, contactAddress);

                return;
            }
            catch(OperationFailedException ex)
            {
                logger.error("Cannot move contact! ", ex);
                throw new OperationFailedException(
                    ex.getMessage(),
                    OperationFailedException.GENERAL_ERROR, ex);
            }
        }

        try
        {
            // will create the entry with the new group so it can be removed
            // from other groups if any
            // modify our reply timeout because some XMPP may send "result" IQ
            // late (> 5 secondes).
            SmackConfiguration.setPacketReplyTimeout(
                ProtocolProviderServiceJabberImpl.SMACK_PACKET_REPLY_TIMEOUT);
            roster.createEntry(contact.getSourceEntry().getUser(),
                               contact.getDisplayName(),
                               new String[]{newParent.getGroupName()});
            SmackConfiguration.setPacketReplyTimeout(5000);

            newParent.addContact(contact);
        }
        catch (XMPPException ex)
        {
            logger.error("Cannot move contact! ", ex);
            throw new OperationFailedException(
                ex.getMessage(),
                OperationFailedException.GENERAL_ERROR, ex);
        }
    }

    /**
     * Sets a reference to the currently active and valid instance of
     * roster that this list is to use for retrieving
     * server stored information
     */
    void init(OperationSetPersistentPresenceJabberImpl.ContactChangesListener
                  presenceChangeListener)
    {
        this.roster = jabberProvider.getConnection().getRoster();
        presenceChangeListener.storeEvents();
        this.roster.addRosterListener(presenceChangeListener);
        this.roster.setSubscriptionMode(Roster.SubscriptionMode.manual);

        initRoster();

        // roster has been requested and dispatched, mark this
        synchronized(rosterInitLock)
        {
            this.isRosterInitialized = true;
        }
        // no send initial status
        sendInitialStatus();

        presenceChangeListener.processStoredEvents();

        rosterChangeListener = new ChangeListener();
        this.roster.addRosterListener(rosterChangeListener);
    }

    /**
     * Sends the initial presence to server. RFC 6121 says:
     * a client SHOULD request the roster before sending initial presence
     * We extend this and send it after we have dispatched the roster
     */
    void sendInitialStatus()
    {
        // if we have initial status saved use it
        if(initialStatus != null)
        {
            try
            {
                parentOperationSet.publishPresenceStatus(
                    initialStatus, initialStatusMessage);
            }
            catch(OperationFailedException ex)
            {
                logger.error("Error publishing initial presence", ex);
            }
        }
        else
            getParentProvider().getConnection()
                .sendPacket(new Presence(Presence.Type.available));

        // clean
        initialStatus = null;
        initialStatusMessage = null;
    }

    /**
     * Cleanups references and listeners.
     */
    void cleanup()
    {
        if(imageRetriever != null)
        {
            imageRetriever.quit();
            imageRetriever = null;
        }

        if(this.roster != null)
            this.roster.removeRosterListener(rosterChangeListener);

        this.rosterChangeListener = null;
        this.roster = null;

        synchronized(rosterInitLock)
        {
            this.isRosterInitialized = false;
        }
    }

    /**
     * When the protocol is online this method is used to fill or resolve
     * the current contact list
     */
    private synchronized void initRoster()
    {
        // first if unfiled entries will move them in a group
        if(roster.getUnfiledEntryCount() > 0)
        {
            for (RosterEntry item : roster.getUnfiledEntries())
            {
                ContactJabberImpl contact =
                    findContactById(item.getUser());

                // some services automatically add contacts from their
                // addressbook to the roster and those contacts are
                // with subscription none. If such already exist,
                // remove them. This is typically our own contact
                if(!isEntryDisplayable(item))
                {
                    if(contact != null)
                    {
                        ContactGroup parent = contact.getParentContactGroup();

                        if(parent instanceof RootContactGroupJabberImpl)
                            ((RootContactGroupJabberImpl)parent)
                                .removeContact(contact);
                        else
                            ((ContactGroupJabberImpl)parent)
                                .removeContact(contact);

                        fireContactRemoved(parent, contact);
                    }
                    continue;
                }

                if(contact == null)
                {
                    // if there is no such contact create it
                    contact = new ContactJabberImpl(item, this, true, true);
                    rootGroup.addContact(contact);

                    fireContactAdded(rootGroup, contact);
                }
                else
                {
                    ContactGroup group = contact.getParentContactGroup();
                    if(!rootGroup.equals(group))
                    {
                        contactMoved(group, rootGroup, contact);
                    }
                    // if contact exist so resolve it
                    contact.setResolved(item);

                    //fire an event saying that the unfiled contact has been
                    //resolved
                    fireContactResolved(rootGroup, contact);
                }

                try
                {
                    // process status if any that was received
                    // while the roster reply packet was received and
                    // added our presence listener
                    // Fixes a problem where Presence packets can be received
                    // before the roster items packet, and we miss it,
                    // cause we add our listener after roster is received
                    // and smack don't allow to add our listener earlier
                    parentOperationSet.firePresenceStatusChanged(
                        roster.getPresence(item.getUser()));
                }
                catch(Throwable t)
                {
                    logger.error("Error processing presence", t);
                }
            }
        }

        // now search all root contacts for unresolved ones
        Iterator<Contact> iter = rootGroup.contacts();
        List<ContactJabberImpl> contactsToRemove
            = new ArrayList<ContactJabberImpl>();
        while(iter.hasNext())
        {
            ContactJabberImpl contact = (ContactJabberImpl)iter.next();
            if(!contact.isResolved())
            {
                contactsToRemove.add(contact);
            }
        }

        for(ContactJabberImpl contact : contactsToRemove)
        {
            rootGroup.removeContact(contact);

            fireContactRemoved(rootGroup, contact);
        }
        contactsToRemove.clear();

        for (RosterGroup item : roster.getGroups())
        {
            ContactGroupJabberImpl group =
                findContactGroup(item.getName());
            if(group != null)
            {
                // the group exist so just resolved. The group will check and
                // create or resolve its entries
                group.setResolved(item);

                //fire an event saying that the group has been resolved
                fireGroupEvent(group
                               , ServerStoredGroupEvent.GROUP_RESOLVED_EVENT);
            }
        }

        Iterator<ContactGroup> iterGroups = rootGroup.subgroups();
        List<ContactGroupJabberImpl> groupsToRemove
            = new ArrayList<ContactGroupJabberImpl>();
        while(iterGroups.hasNext())
        {
            ContactGroupJabberImpl group =
                (ContactGroupJabberImpl)iterGroups.next();

            // skip non persistent groups
            if(!group.isPersistent())
                continue;

            if(!group.isResolved())
            {
                groupsToRemove.add(group);
            }

            Iterator<Contact> iterContacts = group.contacts();
            while(iterContacts.hasNext())
            {
                ContactJabberImpl contact =
                    (ContactJabberImpl)iterContacts.next();
                if(!contact.isResolved())
                {
                    contactsToRemove.add(contact);
                }
            }
            for(ContactJabberImpl contact : contactsToRemove)
            {
                group.removeContact(contact);

                fireContactRemoved(group, contact);
            }
            contactsToRemove.clear();
        }

        for(ContactGroupJabberImpl group: groupsToRemove)
        {
            rootGroup.removeSubGroup(group);

            fireGroupEvent(
                group, ServerStoredGroupEvent.GROUP_REMOVED_EVENT);
        }


        // fill in root group
        for (RosterGroup item : roster.getGroups())
        {
            ContactGroupJabberImpl group =
                findContactGroup(item.getName());

            if(group == null)
            {
                // create the group as it doesn't exist
                ContactGroupJabberImpl newGroup = new ContactGroupJabberImpl(
                    item, item.getEntries().iterator(), this, true);

                rootGroup.addSubGroup(newGroup);

                //tell listeners about the added group
                fireGroupEvent(newGroup
                               , ServerStoredGroupEvent.GROUP_CREATED_EVENT);

                // if presence was already received it,
                // we must check & dispatch it
                if(roster != null)
                {
                    Iterator<Contact> cIter = newGroup.contacts();
                    while(cIter.hasNext())
                    {
                        String address = cIter.next().getAddress();
                        parentOperationSet.firePresenceStatusChanged(
                            roster.getPresence(address));
                    }
                }
            }
        }
    }

    /**
     * Returns the volatile group that we use when creating volatile contacts.
     *
     * @return ContactGroupJabberImpl
     */
    ContactGroupJabberImpl getNonPersistentGroup()
    {
        String groupName
            = JabberActivator.getResources().getI18NString(
                "service.gui.NOT_IN_CONTACT_LIST_GROUP_NAME");

        for (int i = 0; i < getRootGroup().countSubgroups(); i++)
        {
            ContactGroupJabberImpl gr =
                (ContactGroupJabberImpl)getRootGroup().getGroup(i);

            if(!gr.isPersistent() && gr.getGroupName().equals(groupName))
                return gr;
        }

        return null;
    }

    /**
     * Make the parent persistent presence operation set dispatch a contact
     * added event.
     * @param parentGroup the group where the new contact was added
     * @param contact the contact that was added
     */
    void fireContactAdded( ContactGroup parentGroup,
                           ContactJabberImpl contact)
    {
        //bail out if no one's listening
        if(parentOperationSet == null){
            if (logger.isDebugEnabled())
                logger.debug("No presence op. set available. Bailing out.");
            return;
        }

        // if we are already registered(roster != null) and we are currently
        // creating the contact list, presences maybe already received
        // before we have created the contacts, so lets check
        if(roster != null)
        {
            parentOperationSet.firePresenceStatusChanged(
                    roster.getPresence(contact.getAddress()));
        }

        // dispatch
        parentOperationSet.fireSubscriptionEvent(contact, parentGroup,
            SubscriptionEvent.SUBSCRIPTION_CREATED);
    }

    /**
     * Make the parent persistent presence operation set dispatch a contact
     * resolved event.
     * @param parentGroup the group that the resolved contact belongs to.
     * @param contact the contact that was resolved
     */
    void fireContactResolved( ContactGroup parentGroup,
                              ContactJabberImpl contact)
    {
        //bail out if no one's listening
        if(parentOperationSet == null){
            if (logger.isDebugEnabled())
                logger.debug("No presence op. set available. Bailing out.");
            return;
        }

        // if we are already registered(roster != null) and we are currently
        // creating the contact list, presences maybe already received
        // before we have created the contacts, so lets check
        if(roster != null)
        {
            parentOperationSet.firePresenceStatusChanged(
                    roster.getPresence(contact.getAddress()));
        }

        // dispatch
        parentOperationSet.fireSubscriptionEvent(contact, parentGroup,
            SubscriptionEvent.SUBSCRIPTION_RESOLVED);
    }

    /**
     * when there is no image for contact we must retrieve it
     * add contacts for image update
     *
     * @param contact ContactJabberImpl
     */
    protected void addContactForImageUpdate(ContactJabberImpl contact)
    {
        if(contact instanceof VolatileContactJabberImpl
            && ((VolatileContactJabberImpl)contact).isPrivateMessagingContact())
            return;

        if(imageRetriever == null)
        {
            imageRetriever = new ImageRetriever();
            imageRetriever.start();
        }

        imageRetriever.addContact(contact);
    }

    /**
     * Some roster entries are not supposed to be seen.
     * Like some services automatically add contacts from their
     * addressbook to the roster and those contacts are with subscription none.
     * Best practices in XEP-0162.
     * - subscription='both' or subscription='to'
     * - ((subscription='none' or subscription='from') and ask='subscribe')
     * - ((subscription='none' or subscription='from')
     *          and (name attribute or group child))
     *
     * @param entry the entry to check.
     *
     * @return is item to be hidden/ignored.
     */
    static boolean isEntryDisplayable(RosterEntry entry)
    {
        if(entry.getType() == RosterPacket.ItemType.both
           || entry.getType() == RosterPacket.ItemType.to)
        {
            return true;
        }
        else if((entry.getType() == RosterPacket.ItemType.none
                    || entry.getType() == RosterPacket.ItemType.from)
                && (RosterPacket.ItemStatus.SUBSCRIPTION_PENDING.equals(
                    entry.getStatus())
                    || (entry.getGroups() != null
                        && entry.getGroups().size() > 0)))
        {
            return true;
        }

        return false;
    }

    /**
     * Removes contact from client side.
     *
     * @param contact the contact to be deleted.
     */
    private void contactDeleted(ContactJabberImpl contact)
    {
        ContactGroup group = findContactGroup(contact);

        if(group == null)
        {
            if (logger.isTraceEnabled())
                logger.trace("Could not find ParentGroup for deleted entry:"
                            + contact.getAddress());
            return;
        }

        if(group instanceof ContactGroupJabberImpl)
        {
            ContactGroupJabberImpl groupImpl
                = (ContactGroupJabberImpl)group;

            // remove the contact from parrent group
            groupImpl.removeContact(contact);

            // if the group is empty remove it from
            // root group. This group will be removed
            // from server if empty
            if (groupImpl.countContacts() == 0)
            {
                rootGroup.removeSubGroup(groupImpl);

                fireContactRemoved(groupImpl, contact);
                fireGroupEvent(groupImpl,
                           ServerStoredGroupEvent.GROUP_REMOVED_EVENT);
            }
            else
                fireContactRemoved(groupImpl, contact);
        }
        else if(group instanceof RootContactGroupJabberImpl)
        {
            rootGroup.removeContact(contact);

            fireContactRemoved(rootGroup, contact);
        }

    }
    /**
     * Receives changes in roster.
     */
    private class ChangeListener
        implements RosterListener
    {
        /**
         * Notifies for errors in roster packets.
         * @param error the error.
         * @param packet the source packet containing the error.
         */
        public void rosterError(XMPPError error, Packet packet)
        {
            logger.error("Error received in roster " + error.getCode() + " "
                + error.getMessage());
        }

        /**
         * Received event when entry is added to the server stored list
         * @param addresses Collection
         */
        public void entriesAdded(Collection<String> addresses)
        {
            if (logger.isTraceEnabled())
                logger.trace("entriesAdded " + addresses);

            for (String id : addresses)
            {
                addEntryToContactList(id);
            }
        }

        /**
         * Adds the entry to our local contactlist.
         * If contact exists and is persistent but not resolved, we resolve it
         * and return it without adding new contact.
         * If the contact exists and is not persistent, we remove it, to
         * avoid duplicate contacts and add the new one.
         * All entries must be displayable before we done anything with them.
         *
         * @param rosterEntryID the entry id.
         * @return the newly created contact.
         */
        private ContactJabberImpl addEntryToContactList(String rosterEntryID)
        {
            RosterEntry entry = roster.getEntry(rosterEntryID);

            if(!isEntryDisplayable(entry))
                return null;

            ContactJabberImpl contact =
                findContactById(entry.getUser());

            if(contact == null)
            {
                contact = findPrivateContactByRealId(entry.getUser());
            }

            if(contact != null)
            {
                if(contact.isPersistent())
                {
                    contact.setResolved(entry);
                    return contact;
                }
                else if(contact instanceof VolatileContactJabberImpl)
                {
                    ContactGroup oldParentGroup =
                        contact.getParentContactGroup();
                    // if contact is in 'not in contact list'
                    // we must remove it from there in order to correctly
                    // process adding contact
                    // this happens if we accept subscribe request
                    // not from sip-communicator
                    if(oldParentGroup instanceof ContactGroupJabberImpl
                        && !oldParentGroup.isPersistent())
                    {
                        ((ContactGroupJabberImpl)oldParentGroup)
                            .removeContact(contact);
                        fireContactRemoved(oldParentGroup, contact);
                    }
                }
                else
                    return contact;
            }

            contact = new ContactJabberImpl(
                    entry,
                    ServerStoredContactListJabberImpl.this,
                    true,
                    true);

            if(entry.getGroups() == null || entry.getGroups().size() == 0)
            {
                // no parent group so its in the root group
                rootGroup.addContact(contact);
                fireContactAdded(rootGroup, contact);

                return contact;
            }

            for (RosterGroup group : entry.getGroups())
            {
                ContactGroupJabberImpl parentGroup =
                    findContactGroup(group.getName());

                if(parentGroup != null)
                {
                    parentGroup.addContact(contact);
                    fireContactAdded(findContactGroup(contact), contact);
                }
                else
                {
                    // create the group as it doesn't exist
                    ContactGroupJabberImpl newGroup =
                        new ContactGroupJabberImpl(
                        group, group.getEntries().iterator(),
                        ServerStoredContactListJabberImpl.this,
                        true);

                    rootGroup.addSubGroup(newGroup);

                    //tell listeners about the added group
                    fireGroupEvent(newGroup,
                            ServerStoredGroupEvent.GROUP_CREATED_EVENT);
                }

                // as for now we only support contact only in one group
                return contact;
            }

            return contact;
        }

        /**
         * Finds private messaging contact by its jabber id.
         * @param id the jabber id.
         * @return the contact or null if the contact is not found.
         */
        private ContactJabberImpl findPrivateContactByRealId(String id)
        {
            ContactGroupJabberImpl volatileGroup
                = getNonPersistentGroup();
            if(volatileGroup == null)
                return null;
            Iterator<Contact> it = volatileGroup.contacts();
            while(it.hasNext())
            {
                Contact contact = it.next();

                if(contact.getPersistableAddress() == null)
                    continue;

                if(contact.getPersistableAddress().equals(
                    StringUtils.parseBareAddress(id)))
                {
                    return (ContactJabberImpl) contact;
                }
            }
            return null;
        }

        /**
         * Event when an entry is updated. Something for the entry data
         * or have been added to a new group or removed from one
         * @param addresses Collection
         */
        public void entriesUpdated(Collection<String> addresses)
        {
            if (logger.isTraceEnabled())
                logger.trace("entriesUpdated  " + addresses);

            // will search for group renamed
            for (String contactID : addresses)
            {
                RosterEntry entry = roster.getEntry(contactID);

                ContactJabberImpl contact = addEntryToContactList(contactID);

                if(entry.getGroups().size() == 0)
                {
                    // check for change in display name
                    checkForRename(entry.getName(), contact);

                    ContactGroup contactGroup =
                        contact.getParentContactGroup();

                    if(!rootGroup.equals(contactGroup))
                    {
                        contactMoved(contactGroup, rootGroup, contact);
                    }
                }

                for (RosterGroup gr : entry.getGroups())
                {
                    ContactGroup cgr = findContactGroup(gr.getName());
                    if(cgr == null)
                    {
                        // such group does not exist. so it must be
                        // renamed one
                        ContactGroupJabberImpl group =
                            findContactGroupByNameCopy(gr.getName());
                        if(group != null)
                        {
                            // just change the source entry
                            group.setSourceGroup(gr);

                            fireGroupEvent(group,
                                   ServerStoredGroupEvent.GROUP_RENAMED_EVENT);
                        }
                        else
                        {
                            // the group was renamed on different location
                            // so we do not have it at our side
                            // now lets find the group for the contact
                            // and rename it,
                            // - if it is the only contact in
                            // the group this is rename, otherwise it is move
                            ContactGroup currentParentGroup =
                                contact.getParentContactGroup();

                            if(currentParentGroup.countContacts() > 1)
                            {
                                cgr = currentParentGroup;
                            }
                            else
                            {
                                // make sure this group name is not present
                                // in entry groups
                                boolean present = false;
                                for (RosterGroup entryGr : entry.getGroups())
                                {
                                    if(entryGr.getName().equals(
                                            currentParentGroup.getGroupName()))
                                    {
                                        present = true;
                                        break;
                                    }
                                }

                                if(!present
                                    && currentParentGroup instanceof
                                            ContactGroupJabberImpl)
                                {
                                    ContactGroupJabberImpl currentGroup =
                                        (ContactGroupJabberImpl)
                                            currentParentGroup;
                                    currentGroup.setSourceGroup(gr);

                                    fireGroupEvent(
                                        currentGroup,
                                        ServerStoredGroupEvent
                                            .GROUP_RENAMED_EVENT);
                                }
                            }
                        }
                    }

                    if(cgr != null)
                    {
                        // the group is found the contact may be moved from
                        // one group to another
                        ContactGroup contactGroup =
                            contact.getParentContactGroup();

                        if(!gr.getName().equals(contactGroup.getGroupName()))
                        {

                            // the add it to the new one
                            ContactGroupJabberImpl newParentGroup =
                                findContactGroup(gr.getName());

                            // the new parent group maybe missing
                            if(newParentGroup == null)
                            {
                                // create the group as it doesn't exist
                                newParentGroup =
                                    new ContactGroupJabberImpl(
                                        gr,
                                        new ArrayList<RosterEntry>().iterator(),
                                        ServerStoredContactListJabberImpl.this,
                                        true);

                                rootGroup.addSubGroup(newParentGroup);

                                //tell listeners about the added group
                                fireGroupEvent(newParentGroup,
                                    ServerStoredGroupEvent.GROUP_CREATED_EVENT);
                            }

                            contactMoved(contactGroup, newParentGroup, contact);
                        }
                        else
                        {
                            // check for change in display name
                            checkForRename(entry.getName(), contact);
                        }
                    }
                }
            }
        }

        /**
         * Checks the entry and the contact whether the display name has changed.
         * @param newValue new display name value
         * @param contact the contact to check
         */
        private void checkForRename(String newValue,
                                    ContactJabberImpl contact)
        {
            // check for change in display name
            if(newValue != null
               && !newValue.equals(
                    contact.getServerDisplayName()))
            {
                String oldValue = contact.getServerDisplayName();
                contact.setServerDisplayName(newValue);
                parentOperationSet.fireContactPropertyChangeEvent(
                    ContactPropertyChangeEvent.PROPERTY_DISPLAY_NAME,
                    contact, oldValue, newValue);
            }
        }

        /**
         * Event received when entry has been removed from the list
         * @param addresses Collection
         */
        public void entriesDeleted(Collection<String> addresses)
        {
            Iterator<String> iter = addresses.iterator();
            while (iter.hasNext())
            {
                String address = iter.next();
                if (logger.isTraceEnabled())
                    logger.trace("entry deleted " + address);

                ContactJabberImpl contact = findContactById(address);

                if(contact == null)
                {
                    if (logger.isTraceEnabled())
                        logger.trace("Could not find contact for deleted entry:"
                                    + address);
                    continue;
                }

                contactDeleted(contact);
            }
        }

        /**
         * Not used here.
         * @param presence
         */
        public void presenceChanged(Presence presence)
        {}
    }

    /**
     * Thread retrieving images.
     */
    private class ImageRetriever
        extends Thread
    {
        /**
         * list with the accounts with missing image
         */
        private final List<ContactJabberImpl> contactsForUpdate
            = new Vector<ContactJabberImpl>();

        /**
         * Should we stop.
         */
        private boolean running = false;

        /**
         * Creates image retrieving.
         */
        ImageRetriever()
        {
            setDaemon(true);
        }

        /**
         * Thread entry point.
         */
        @Override
        public void run()
        {
            try
            {
                Collection<ContactJabberImpl> copyContactsForUpdate = null;
                running = true;
                while (running)
                {
                    synchronized(contactsForUpdate)
                    {
                        if(contactsForUpdate.isEmpty())
                            contactsForUpdate.wait();

                        if(!running)
                            return;

                        copyContactsForUpdate
                            = new Vector<ContactJabberImpl>(contactsForUpdate);
                        contactsForUpdate.clear();
                    }

                    Iterator<ContactJabberImpl> iter
                        = copyContactsForUpdate.iterator();
                    while (iter.hasNext())
                    {
                        ContactJabberImpl contact = iter.next();

                        byte[] imgBytes = getAvatar(contact);

                        if(imgBytes != null)
                        {
                            byte[] oldImage = contact.getImage(false);

                            contact.setImage(imgBytes);
                            parentOperationSet.fireContactPropertyChangeEvent(
                                ContactPropertyChangeEvent.PROPERTY_IMAGE,
                                contact, oldImage, imgBytes);
                        }
                        else
                            // set an empty image data so it won't be queried again
                            contact.setImage(new byte[0]);
                    }
                }
            }
            catch (InterruptedException ex)
            {
                logger.error("ImageRetriever error waiting will stop now!", ex);
            }
        }

        /**
         * Add contact for retrieving
         * if the provider is register notify the retriever to get the nicks
         * if we are not registered add a listener to wait for registering
         *
         * @param contact ContactJabberImpl
         */
        void addContact(ContactJabberImpl contact)
        {
            synchronized(contactsForUpdate)
            {
                if (!contactsForUpdate.contains(contact))
                {
                    contactsForUpdate.add(contact);
                    contactsForUpdate.notifyAll();
                }
            }
        }

        /**
         * Stops this thread.
         */
        void quit()
        {
            synchronized(contactsForUpdate)
            {
                running = false;
                contactsForUpdate.notifyAll();
            }
        }

        /**
         * Retrieves the avatar.
         * @param contact the contact.
         * @return the contact avatar.
         */
        private byte[] getAvatar(ContactJabberImpl contact)
        {
            byte[] result = null;
            try
            {
                Iterator<ServerStoredDetails.GenericDetail> iter =
                    infoRetreiver.getDetails(contact.getAddress(),
                    ServerStoredDetails.ImageDetail.class);

                if(iter.hasNext())
                {
                    ServerStoredDetails.ImageDetail imgDetail =
                        (ServerStoredDetails.ImageDetail)iter.next();
                    result = imgDetail.getBytes();
                }

                if(result == null)
                {
                    result = searchForCustomAvatar(contact.getAddress());
                }

                return result;
            }
            catch (Exception ex)
            {
                if (logger.isDebugEnabled())
                {
                    logger.debug(
                            "Cannot load image for contact "
                                + contact
                                + ": "
                                + ex.getMessage(),
                            ex);
                }

                result = searchForCustomAvatar(contact.getAddress());
                if(result == null)
                    result = new byte[0];
            }

            return result;
        }
    }

    /**
     * Query custom avatar services and returns the first found avtar.
     * @return the found avatar if any.
     */
    private byte[] searchForCustomAvatar(String address)
    {
        try
        {
            ServiceReference[] refs =  JabberActivator.bundleContext
                .getServiceReferences(CustomAvatarService.class.getName(), null);

            if(refs == null)
                return null;

            for(ServiceReference r : refs)
            {
                CustomAvatarService avatarService =
                    (CustomAvatarService)JabberActivator
                        .bundleContext.getService(r);

                byte[] res = avatarService.getAvatar(address);

                if(res != null)
                    return res;
            }
        }
        catch(Throwable t)
        {
            // if something is wrong just return empty image
        }

        return null;
    }

    /**
     * Handles moving of contact from one group to another.
     *
     * @param oldGroup old group of the contact.
     * @param newGroup new group of the contact.
     * @param contact contact to move
     */
    private void contactMoved(ContactGroup oldGroup,
        ContactGroup newGroup, ContactJabberImpl contact)
    {
        // the contact is moved to another group
        // first remove it from the original one
        if(oldGroup instanceof ContactGroupJabberImpl)
            ((ContactGroupJabberImpl)oldGroup).
                removeContact(contact);
        else if(oldGroup instanceof RootContactGroupJabberImpl)
            ((RootContactGroupJabberImpl)oldGroup).
                removeContact(contact);


        if(newGroup instanceof ContactGroupJabberImpl)
            ((ContactGroupJabberImpl)newGroup).
                addContact(contact);
        else if(newGroup instanceof RootContactGroupJabberImpl)
            ((RootContactGroupJabberImpl)newGroup).
                addContact(contact);

        fireContactMoved(oldGroup,
            newGroup,
            contact);

        if(oldGroup instanceof ContactGroupJabberImpl
           && oldGroup.countContacts() == 0)
        {
            // in xmpp if group is empty it is removed
            rootGroup.removeSubGroup(
                (ContactGroupJabberImpl)oldGroup);

            fireGroupEvent(
                (ContactGroupJabberImpl)oldGroup,
                ServerStoredGroupEvent.GROUP_REMOVED_EVENT);
        }
    }

    /**
     * Completes the identifier with the server part if no server part was
     * previously added.
     *
     * @param id the initial identifier as added by the user
     */
    private String parseAddressString(String id)
    {
        if (id.indexOf("@") < 0)
        {
            AccountID accountID
                = jabberProvider.getAccountID();

            String serverPart;
            String userID = accountID.getUserID();
            int atIndex = userID.indexOf('@');
            if (atIndex > 0)
                serverPart = userID.substring(atIndex + 1);
            else
                serverPart = accountID.getService();

            return id + "@" + serverPart;
        }

        return id;
    }

    /**
     * Return all the presences for the user.
     * @param user the id of the user to check for presences.
     * @return all the presences available for the user.
     */
    public Iterator<Presence> getPresences(String user)
    {
        return roster.getPresences(user);
    }

    /**
     * Returns whether roster is initialized.
     * @return whether roster is initialized.
     */
    boolean isRosterInitialized()
    {
        return isRosterInitialized;
    }

    /**
     * The lock around isRosterInitialized variable.
     * @return the lock around isRosterInitialized variable.
     */
    Object getRosterInitLock()
    {
        return rosterInitLock;
    }

    /**
     * Saves the initial status for later dispatching.
     * @param initialStatus to be dispatched later.
     */
    void setInitialStatus(PresenceStatus initialStatus)
    {
        this.initialStatus = initialStatus;
    }

    /**
     * Saves the initial status message for later dispatching.
     * @param initialStatusMessage to be dispatched later.
     */
    void setInitialStatusMessage(String initialStatusMessage)
    {
        this.initialStatusMessage = initialStatusMessage;
    }
}