aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/contactlist/MetaContactListServiceImpl.java
blob: 26ba6dc70471d80f263b09c8c97232e734b42806 (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
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
/*
 * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package net.java.sip.communicator.impl.contactlist;

import java.util.*;

import org.osgi.framework.*;

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

/**
 * An implementation of the MetaContactListService that would connect to
 * protocol service providers and build it  s contact list accordingly
 * basing itself on the contact list stored by the various protocol provider
 * services and the contact list instance saved on the hard disk.
 * <p>
 *
 * @author Emil Ivov
 */
public class MetaContactListServiceImpl
    implements MetaContactListService,
               ServiceListener,
               ContactPresenceStatusListener,
               ContactCapabilitiesListener
{
    /**
     * The <tt>Logger</tt> used by the <tt>MetaContactListServiceImpl</tt> class
     * and its instances for logging output.
     */
    private static final Logger logger
        = Logger.getLogger(MetaContactListServiceImpl.class);

    /**
     * The BundleContext that we got from the OSGI bus.
     */
    private BundleContext bundleContext = null;

    /**
     * The list of protocol providers that we're currently aware of.
     */
    private final Map<String, ProtocolProviderService> currentlyInstalledProviders
        = new Hashtable<String, ProtocolProviderService>();

    /**
     * The root of the meta contact list.
     */
    final MetaContactGroupImpl rootMetaGroup;

    /**
     * The event handler that will be handling our subscription events.
     */
    private final ContactListSubscriptionListener clSubscriptionEventHandler
        = new ContactListSubscriptionListener();

    /**
     * The event handler that will be handling group events.
     */
    private final ContactListGroupListener clGroupEventHandler
        = new ContactListGroupListener();

    /**
     * The number of milliseconds to wait for confirmations of account
     * modifications before deciding to drop.
     */
    public static final int CONTACT_LIST_MODIFICATION_TIMEOUT = 10000;

    /**
     * Listeners interested in events dispatched upon modification of the meta
     * contact list.
     */
    private final List<MetaContactListListener> metaContactListListeners
        = new Vector<MetaContactListListener>();

    /**
     * Contains (as keys) <tt>MetaContactGroup</tt> names that are currently
     * being resolved against a given protocol and that this class's
     * <tt>ContactGroupListener</tt> should ignore as corresponding events will
     * be handled by the corresponding methods. The table maps the meta contact
     * group names against lists of protocol providers. An incoming group event
     * would therefore be ignored by the class group listener if and only if it
     * carries a name present in this table and is issued by one of the
     * providers mapped against this groupName.
     */
    private final Hashtable<String, List<ProtocolProviderService>>
        groupEventIgnoreList = new Hashtable<String,
                                             List<ProtocolProviderService>>();

    /**
     * Contains (as keys) <tt>Contact</tt> addresses that are currently
     * being resolved against a given protocol and that this class's
     * <tt>ContactListener</tt> should ignore as corresponding events will
     * be handled by the corresponding methods. The table maps the meta contact
     * addresses against lists of protocol providers. An incoming group event
     * would therefore be ignored by the class group listener if and only if it
     * carries a name present in this table and is issued by one of the
     * providers mapped against this groupName.
     */
    private final Hashtable<String, List<ProtocolProviderService>>
        contactEventIgnoreList = new Hashtable<String,
                                               List<ProtocolProviderService>>();

    /**
     * The instance of the storage manager which is handling the local copy of
     * our contact list.
     */
    private final MclStorageManager storageManager = new MclStorageManager();

    /**
     * Creates an instance of this class.
     */
    public MetaContactListServiceImpl()
    {
        rootMetaGroup
            = new MetaContactGroupImpl(
                    this,
                    "RootMetaContactGroup",
                    "RootMetaContactGroup");
    }

    /**
     * Starts this implementation of the MetaContactListService. The
     * implementation would first restore a default contact list from what has
     * been stored in a file. It would then connect to OSGI and retrieve any
     * existing protocol providers and if <br>
     * 1) They provide implementations of OperationSetPersistentPresence, it
     * would synchronize their contact lists with the local one (adding
     * subscriptions for contacts that do not exist in the server stored contact
     * list and adding locally contacts that were found on the server but not in
     * the local file).
     * <p>
     * 2) The only provide non persistent implementations of
     * OperationSetPresence, the meta contact list impl would create
     * subscriptions for all local contacts in the corresponding protocol
     * provider.
     * <p>
     * This implementation would also start listening for any newly registered
     * protocol provider implementations and perform the same algorithm with
     * them.
     * <p>
     *
     * @param bc the currently valid OSGI bundle context.
     */
    public void start(BundleContext bc)
    {
        if (logger.isDebugEnabled())
            logger.debug("Starting the meta contact list implementation.");
        this.bundleContext = bc;

        //initialize the meta contact list from what has been stored locally.
        try
        {
            storageManager.start(bundleContext, this);
        }
        catch (Exception exc)
        {
            logger.error("Failed loading the stored contact list.", exc);
        }

        // start listening for newly register or removed protocol providers
        bc.addServiceListener(this);

        // first discover the icq service
        // then find the protocol provider service
        ServiceReference[] protocolProviderRefs = null;
        try
        {
            protocolProviderRefs = bc.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, retrieve the root groups for all protocol
        // providers and create the meta contact list
        if (protocolProviderRefs != null)
        {
            if (logger.isDebugEnabled())
                logger.debug("Found "
                         + protocolProviderRefs.length
                         + " already installed providers.");
            for (ServiceReference providerRef : protocolProviderRefs)
            {
                ProtocolProviderService provider
                    = (ProtocolProviderService) bc.getService(providerRef);

                this.handleProviderAdded(provider);
            }
        }
    }

    /**
     * Prepares the meta contact list service for shutdown.
     *
     * @param bc the currently active bundle context.
     */
    public void stop(BundleContext bc)
    {
        storageManager.storeContactListAndStopStorageManager();
        bc.removeServiceListener(this);

        //stop listening to all currently installed providers
        for (ProtocolProviderService pp : currentlyInstalledProviders.values())
        {
            OperationSetPersistentPresence opSetPersPresence =
                pp.getOperationSet(OperationSetPersistentPresence.class);

            if(opSetPersPresence !=null)
            {
                opSetPersPresence
                    .removeContactPresenceStatusListener(this);
                opSetPersPresence
                    .removeSubscriptionListener(clSubscriptionEventHandler);
                opSetPersPresence
                    .removeServerStoredGroupChangeListener(clGroupEventHandler);
            }
            else
            {
                //check if a non persistent presence operation set exists.
                OperationSetPresence opSetPresence =
                    pp.getOperationSet(OperationSetPresence.class);

                if(opSetPresence != null)
                {
                    opSetPresence
                        .removeContactPresenceStatusListener(this);
                    opSetPresence
                        .removeSubscriptionListener(clSubscriptionEventHandler);
                }
            }
        }
        currentlyInstalledProviders.clear();
        storageManager.stop();
    }

    /**
     * Adds a listener for <tt>MetaContactListChangeEvent</tt>s posted after
     * the tree changes.
     *
     * @param listener the listener to add
     */
    public void addMetaContactListListener(MetaContactListListener listener)
    {
        synchronized (metaContactListListeners)
        {
            if(!metaContactListListeners.contains(listener))
                metaContactListListeners.add(listener);
        }
    }

    /**
     * First makes the specified protocol provider create the contact as
     * indicated by <tt>contactID</tt>, and then associates it to the
     * _existing_ <tt>metaContact</tt> given as an argument.
     *
     * @param provider
     *            the ProtocolProviderService that should create the contact
     *            indicated by <tt>contactID</tt>.
     * @param metaContact
     *            the meta contact where that the newly created contact should
     *            be associated to.
     * @param contactID
     *            the identifier of the contact that the specified provider
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public void addNewContactToMetaContact(
        ProtocolProviderService provider,
        MetaContact metaContact, String contactID)
            throws MetaContactListException
    {
        addNewContactToMetaContact(provider, metaContact, contactID, true);
    }

    /**
     * First makes the specified protocol provider create the contact as
     * indicated by <tt>contactID</tt>, and then associates it to the
     * _existing_ <tt>metaContact</tt> given as an argument.
     *
     * @param provider
     *            the ProtocolProviderService that should create the contact
     *            indicated by <tt>contactID</tt>.
     * @param metaContact
     *            the meta contact where that the newly created contact should
     *            be associated to.
     * @param contactID
     *            the identifier of the contact that the specified provider
     * @param fireEvent
     *            specifies whether or not an even is to be fire at
     * the end of the method.Used when this method is called upon creation of a
     * new meta contact and not only a new contact.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public void addNewContactToMetaContact( ProtocolProviderService provider,
                                            MetaContact metaContact,
                                            String contactID,
                                            boolean fireEvent)
        throws MetaContactListException
    {
        //find the parent group in the corresponding protocol.
        MetaContactGroup parentMetaGroup
            = findParentMetaContactGroup(metaContact);

        if (parentMetaGroup == null)
        {
            throw new MetaContactListException(
                "orphan Contact: " + metaContact
                , null
                , MetaContactListException.CODE_NETWORK_ERROR);
        }

        addNewContactToMetaContact(provider, parentMetaGroup, metaContact,
                contactID, fireEvent);
    }

    /**
     * First makes the specified protocol provider create the contact as
     * indicated by <tt>contactID</tt>, and then associates it to the
     * _existing_ <tt>metaContact</tt> given as an argument.
     *
     * @param provider
     *            the ProtocolProviderService that should create the contact
     *            indicated by <tt>contactID</tt>.
     * @param parentMetaGroup
     *            the meta contact group which is the parent group of the newly
     *            created contact
     * @param metaContact
     *            the meta contact where that the newly created contact should
     *            be associated to.
     * @param contactID
     *            the identifier of the contact that the specified provider
     * @param fireEvent
     *            specifies whether or not an even is to be fired at
     * the end of the method.Used when this method is called upon creation of a
     * new meta contact and not only a new contact.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    private void addNewContactToMetaContact( ProtocolProviderService provider,
                                            MetaContactGroup parentMetaGroup,
                                            MetaContact metaContact,
                                            String contactID,
                                            boolean fireEvent)
        throws MetaContactListException
    {
        OperationSetPersistentPresence opSetPersPresence =
            provider.getOperationSet(OperationSetPersistentPresence.class);
        if (opSetPersPresence == null)
        {
            /** @todo handle non-persistent presence operation sets as well */
            return;
        }

        if (! (metaContact instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(
                    metaContact
                    + " is not an instance of MetaContactImpl");
        }

        ContactGroup parentProtoGroup
            = resolveProtoPath(provider, (MetaContactGroupImpl) parentMetaGroup);

        if (parentProtoGroup == null)
        {
            throw new MetaContactListException(
                "Could not obtain proto group parent for " + metaContact
                , null
                , MetaContactListException.CODE_NETWORK_ERROR);
        }

        BlockingSubscriptionEventRetriever evtRetriever
            = new BlockingSubscriptionEventRetriever(contactID);

        addContactToEventIgnoreList(contactID, provider);

        opSetPersPresence.addSubscriptionListener(evtRetriever);
        opSetPersPresence.addServerStoredGroupChangeListener(evtRetriever);

        try
        {
            //create the contact in the group
            // if its the root group just call subscribe
            if(parentMetaGroup.equals(rootMetaGroup))
                opSetPersPresence.subscribe(contactID);
            else
                opSetPersPresence.subscribe(parentProtoGroup, contactID);

            //wait for a confirmation event
            evtRetriever.waitForEvent(CONTACT_LIST_MODIFICATION_TIMEOUT);
        }
        catch(OperationFailedException ex)
        {
            if(ex.getErrorCode()
               == OperationFailedException.SUBSCRIPTION_ALREADY_EXISTS)
            {
                throw new MetaContactListException(
                "failed to create contact " + contactID
                , ex
                , MetaContactListException.CODE_CONTACT_ALREADY_EXISTS_ERROR);
            }

            throw new MetaContactListException(
                "failed to create contact " + contactID
                , ex
                , MetaContactListException.CODE_NETWORK_ERROR);

        }
        catch (Exception ex)
        {
            throw new MetaContactListException(
                "failed to create contact " + contactID
                , ex
                , MetaContactListException.CODE_NETWORK_ERROR);
        }
        finally
        {
            //whatever happens we need to remove the event collector
            //end the ignore filter.
            removeContactFromEventIgnoreList(contactID, provider);
            opSetPersPresence.removeSubscriptionListener(evtRetriever);
        }

        //attach the newly created contact to a meta contact
        if (evtRetriever.evt == null)
        {
            throw new MetaContactListException(
                "Failed to create a contact with address: "
                + contactID
                , null
                , MetaContactListException.CODE_NETWORK_ERROR);
        }

        if (evtRetriever.evt instanceof SubscriptionEvent &&
            ((SubscriptionEvent)evtRetriever.evt).getEventID() ==
            SubscriptionEvent.SUBSCRIPTION_FAILED)
        {
            throw new MetaContactListException(
                "Failed to create a contact with address: "
                + contactID + " "
                + ((SubscriptionEvent)evtRetriever.evt).getErrorReason()
                , null
                , MetaContactListException.CODE_UNKNOWN_ERROR);
        }

        //now finally - add the contact to the meta contact
        ( (MetaContactImpl) metaContact).addProtoContact(
            evtRetriever.sourceContact);

        //only fire an event here if the calling method wants us to. in case
        //this is the creation of a new contact and not only addition of a
        //proto contact we should remain silent and the calling method will
        //do the eventing.
        if(fireEvent)
        {
            this.fireProtoContactEvent(evtRetriever.sourceContact,
                                       ProtoContactEvent.PROTO_CONTACT_ADDED,
                                       null,
                                       metaContact);
        }
        ((MetaContactGroupImpl) parentMetaGroup).addMetaContact(
                (MetaContactImpl)metaContact);
    }

    /**
     * Makes sure that directories in the whole path from the root to the
     * specified group have corresponding directories in the protocol indicated
     * by <tt>protoProvider</tt>. The method does not return before creating
     * all groups has completed.
     *
     * @param protoProvider a reference to the protocol provider where the
     * groups should be created.
     * @param metaGroup a ref to the last group of the path that should be
     * created in the specified <tt>protoProvider</tt>
     *
     * @return e reference to the newly created <tt>ContactGroup</tt>
     */
    private ContactGroup resolveProtoPath(ProtocolProviderService protoProvider,
                                          MetaContactGroupImpl metaGroup)
    {
        Iterator<ContactGroup> contactGroupsForProv = metaGroup
            .getContactGroupsForProvider(protoProvider);

        if (contactGroupsForProv.hasNext())
        {
            //we already have at least one group corresponding to the meta group
            return contactGroupsForProv.next();
        }
        //we don't have a proto group here. obtain a ref to the parent
        //proto group (which may be created along the way) and create it.
        MetaContactGroupImpl parentMetaGroup = (MetaContactGroupImpl)
            findParentMetaContactGroup(metaGroup);
        if (parentMetaGroup == null)
        {
            if (logger.isDebugEnabled())
                logger.debug("Resolve failed at group" + metaGroup);
            throw new NullPointerException("Internal Error. Orphan group.");
        }

        OperationSetPersistentPresence opSetPersPresence =
            protoProvider.getOperationSet(OperationSetPersistentPresence.class);

        //if persistent presence is not supported - just bail
        //we should have verified this earlier anyway
        if (opSetPersPresence == null)
        {
            return null;
        }

        ContactGroup parentProtoGroup;
        // special treatment for the root group (stop the recursion)
        if (parentMetaGroup.getParentMetaContactGroup() == null) {
            parentProtoGroup = opSetPersPresence.
                                    getServerStoredContactListRoot();
        } else {
            parentProtoGroup = resolveProtoPath(protoProvider, parentMetaGroup);
        }

        //create the proto group
        BlockingGroupEventRetriever evtRetriever
            = new BlockingGroupEventRetriever(metaGroup.getGroupName());

        opSetPersPresence.addServerStoredGroupChangeListener(evtRetriever);

        addGroupToEventIgnoreList(metaGroup.getGroupName(), protoProvider);

        try
        {
            //create the group
            opSetPersPresence.createServerStoredContactGroup(
                parentProtoGroup, metaGroup.getGroupName());

            //wait for a confirmation event
            evtRetriever.waitForEvent(CONTACT_LIST_MODIFICATION_TIMEOUT);
        }
        catch (Exception ex)
        {
            throw new MetaContactListException(
                "failed to create contact group " + metaGroup.getGroupName()
                , ex
                , MetaContactListException.CODE_NETWORK_ERROR);
        }
        finally
        {
            //whatever happens we need to remove the event collector
            //and the ignore filter.
            removeGroupFromEventIgnoreList(metaGroup.getGroupName()
                                           , protoProvider);
            opSetPersPresence.removeServerStoredGroupChangeListener(
                evtRetriever);
        }

        //sth went wrong.
        if (evtRetriever.evt == null)
        {
            throw new MetaContactListException(
                "Failed to create a proto group named: "
                + metaGroup.getGroupName()
                , null
                , MetaContactListException.CODE_NETWORK_ERROR);
        }

        //now add the proto group to the meta group.
        metaGroup.addProtoGroup(evtRetriever.evt.getSourceGroup());

        fireMetaContactGroupEvent(
            metaGroup
            , evtRetriever.evt.getSourceProvider()
            , evtRetriever.evt.getSourceGroup()
            , MetaContactGroupEvent.CONTACT_GROUP_ADDED_TO_META_GROUP);

        return evtRetriever.evt.getSourceGroup();
    }

    /**
     * Returns the meta contact group that is a direct parent of the specified
     * <tt>child</tt>. If no parent is found <tt>null</tt> is returned.
     * @param child the <tt>MetaContactGroup</tt> whose parent group we're
     * looking for. If no parent is found <tt>null</tt> is returned.
     *
     * @return the <tt>MetaContactGroup</tt> that contains <tt>child</tt> or
     * null if no parent was found.
     */
    public MetaContactGroup findParentMetaContactGroup(MetaContactGroup child)
    {
        return findParentMetaContactGroup(rootMetaGroup, child);
    }

    /**
     * Returns the meta contact group that is a direct parent of the specified
     * <tt>child</tt>, beginning the search at the specified root. If
     * no parent is found <tt>null</tt> is returned.
     * @param child the <tt>MetaContactGroup</tt> whose parent group we're
     * looking for.
     * @param root the parent where the search should start.
     * @return the <tt>MetaContactGroup</tt> that contains <tt>child</tt> or
     * null if no parent was found.
     */
    private MetaContactGroup findParentMetaContactGroup(
        MetaContactGroupImpl root, MetaContactGroup child)
    {
        return child.getParentMetaContactGroup();
    }

    /**
     * Returns the meta contact group that is a direct parent of the specified
     * <tt>child</tt>.
     * @param child the <tt>MetaContact</tt> whose parent group we're looking
     * for.
     *
     * @return the <tt>MetaContactGroup</tt>
     * @throws IllegalArgumentException if <tt>child</tt> is not an instance of
     * MetaContactImpl
     */
    public MetaContactGroup findParentMetaContactGroup(MetaContact child)
    {
        if (! (child instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(child
                                       + " is not a MetaContactImpl instance.");
        }
        return ( (MetaContactImpl) child).getParentGroup();
    }

    /**
     * First makes the specified protocol provider create a contact
     * corresponding to the specified <tt>contactID</tt>, then creates a new
     * MetaContact which will encapsulate the newly created protocol specific
     * contact.
     *
     * @param provider
     *            a ref to <tt>ProtocolProviderService</tt> instance which
     *            will create the actual protocol specific contact.
     * @param metaContactGroup
     *            the MetaContactGroup where the newly created meta contact
     *            should be stored.
     * @param contactID
     *            a protocol specific string identifier indicating the contact
     *            the protocol provider should create.
     * @return the newly created <tt>MetaContact</tt>
     *
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public MetaContact createMetaContact(  ProtocolProviderService provider,
                                    MetaContactGroup metaContactGroup,
                                    String contactID)
        throws MetaContactListException
    {
        if (! (metaContactGroup instanceof MetaContactGroupImpl))
        {
            throw new IllegalArgumentException(metaContactGroup
                + " is not an instance of MetaContactGroupImpl");
        }

        MetaContactImpl newMetaContact = new MetaContactImpl();

        this.addNewContactToMetaContact(provider, metaContactGroup,
            newMetaContact, contactID, false);
            //don't fire a PROTO_CONT_ADDED event we'll
            //fire our own event here.

        fireMetaContactEvent(   newMetaContact,
                                findParentMetaContactGroup(newMetaContact),
                                MetaContactEvent.META_CONTACT_ADDED);

        return newMetaContact;
    }

    /**
     * Creates a <tt>MetaContactGroup</tt> with the specified group name.
     * The meta contact group would only be created locally and resolved
     * against the different server stored protocol contact lists upon the
     * creation of the first protocol specific child contact in the respective
     * group.
     *
     * @param parent
     *            the meta contact group inside which the new child group must
     *            be created.
     * @param groupName the name of the <tt>MetaContactGroup</tt> to create.
     * @return the newly created <tt>MetaContactGroup</tt>
     *
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public MetaContactGroup createMetaContactGroup(MetaContactGroup parent,
                                       String groupName)
        throws MetaContactListException
    {
        if (! (parent instanceof MetaContactGroupImpl))
        {
            throw new IllegalArgumentException(
                parent
                + " is not an instance of MetaContactGroupImpl");
        }

        //make sure that "parent" does not already contain a subgroup called
        //"groupName"
        Iterator<MetaContactGroup> subgroups = parent.getSubgroups();

        while(subgroups.hasNext())
        {
            MetaContactGroup group = subgroups.next();

            if(group.getGroupName().equals(groupName))
            {
                throw new MetaContactListException(
                    "Parent " + parent.getGroupName() + " already contains a "
                    + "group called " + groupName,
                    new CloneNotSupportedException("just testing nested exc-s"),
                    MetaContactListException.CODE_GROUP_ALREADY_EXISTS_ERROR);
            }
        }

        // we only have to create the meta contact group here.
        // we don't care about protocol specific groups.
        MetaContactGroupImpl newMetaGroup
            = new MetaContactGroupImpl(this, groupName);

        ( (MetaContactGroupImpl) parent).addSubgroup(newMetaGroup);

        //fire the event
        fireMetaContactGroupEvent(newMetaGroup
            , null, null, MetaContactGroupEvent. META_CONTACT_GROUP_ADDED);

        return newMetaGroup;
    }

    /**
     * Renames the specified <tt>MetaContactGroup</tt> as indicated by the
     * <tt>newName</tt> param.
     * The operation would only affect the local meta group and would not
     * "touch" any encapsulated protocol specific group.
     * <p>
     * @param group the group to rename.
     * @param newGroupName the new name of the <tt>MetaContactGroup</tt> to
     * rename.
     */
    public void renameMetaContactGroup(MetaContactGroup group,
                                       String newGroupName)
    {
        ( (MetaContactGroupImpl) group).setGroupName(newGroupName);

        fireMetaContactGroupEvent(group, null, null
            , MetaContactGroupEvent.META_CONTACT_GROUP_RENAMED);
    }

    /**
     * Returns the root <tt>MetaContactGroup</tt> in this contact list.
     *
     * @return the root <tt>MetaContactGroup</tt> for this contact list.
     */
    public MetaContactGroup getRoot()
    {
        return rootMetaGroup;
    }

    /**
     * Sets the display name for <tt>metaContact</tt> to be <tt>newName</tt>.
     * <p>
     * @param metaContact the <tt>MetaContact</tt> that we are renaming
     * @param newDisplayName a <tt>String</tt> containing the new display name
     * for <tt>metaContact</tt>.
     * @throws IllegalArgumentException if <tt>metaContact</tt> is not an
     * instance that belongs to the underlying implementation.
     */
    public void renameMetaContact(MetaContact metaContact, String newDisplayName)
        throws IllegalArgumentException
    {
        if (! (metaContact instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(
                metaContact + " is not a MetaContactImpl instance.");
        }

        String oldDisplayName = metaContact.getDisplayName();

        ((MetaContactImpl)metaContact).setDisplayName(newDisplayName);

        fireMetaContactEvent(new MetaContactRenamedEvent(
            metaContact, oldDisplayName, newDisplayName));

        //changing the display name has surely brought a change in the order as
        //well so let's tell the others
        fireMetaContactGroupEvent(
                    findParentMetaContactGroup( metaContact )
                    , null
                    , null
                    , MetaContactGroupEvent.CHILD_CONTACTS_REORDERED);
    }

    /**
     * Sets the avatar for <tt>metaContact</tt> to be <tt>newAvatar</tt>.
     * <p>
     * @param metaContact the <tt>MetaContact</tt> that change avatar
     * @param protoContact the <tt>Contact> that change avatar
     * @param newAvatar avatar image bytes
     * @throws IllegalArgumentException if <tt>metaContact</tt> is not an
     * instance that belongs to the underlying implementation.
     */
    public void changeMetaContactAvatar(MetaContact metaContact,
                                        Contact protoContact,
                                        byte[] newAvatar)
        throws IllegalArgumentException
    {
        if (! (metaContact instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(
                metaContact + " is not a MetaContactImpl instance.");
        }

        byte[] oldAvatar = metaContact.getAvatar(true);
        ((MetaContactImpl) metaContact).cacheAvatar(protoContact, newAvatar);

        fireMetaContactEvent(
            new MetaContactAvatarUpdateEvent(metaContact, oldAvatar, newAvatar));
    }

    /**
     * Makes the specified <tt>contact</tt> a child of the
     * <tt>newParentMetaGroup</tt> MetaContactGroup. If <tt>contact</tt> was
     * previously a child of a meta contact, it will be removed from its
     * old parent and to a newly created one even if they both are in the same
     * group. If the specified contact was the only child of its previous
     * parent, then the meta contact will also be moved.
     *
     *
     * @param contact the <tt>Contact</tt> to move to the
     * @param newParentMetaGroup the MetaContactGroup where we'd like contact to be moved.
     * @throws MetaContactListException with an appropriate code if the
     * operation fails for some reason.
     */
    public void moveContact(Contact contact,
                            MetaContactGroup newParentMetaGroup)
        throws MetaContactListException
    {
        /** first create the new meta contact */
        MetaContactImpl metaContactImpl = new MetaContactImpl();

        MetaContactGroupImpl newParentMetaGroupImpl
            = (MetaContactGroupImpl)newParentMetaGroup;

        newParentMetaGroupImpl.addMetaContact(metaContactImpl);

        fireMetaContactEvent(metaContactImpl
                             , newParentMetaGroupImpl
                             , MetaContactEvent.META_CONTACT_ADDED);

        /** then move the sub contactact to the new metacontact container */
        moveContact(contact, metaContactImpl);
    }

    /**
     * Makes the specified <tt>contact</tt> a child of the <tt>newParent</tt>
     * MetaContact.
     *
     * @param contact
     *            the <tt>Contact</tt> to move to the
     * @param newParentMetaContact
     *            the MetaContact where we'd like contact to be moved.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public void moveContact(Contact contact,
                            MetaContact newParentMetaContact) throws
        MetaContactListException
    {
        if (! (newParentMetaContact instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(
                newParentMetaContact + " is not a MetaContactImpl instance.");
        }

        MetaContactImpl currentParentMetaContact
            = (MetaContactImpl)this.findMetaContactByContact(contact);

        currentParentMetaContact.removeProtoContact(contact);

        //get a persistent  presence operation set
        OperationSetPersistentPresence opSetPresence
            = contact
                .getProtocolProvider()
                    .getOperationSet(OperationSetPersistentPresence.class);

        if (opSetPresence == null)
        {
            /** @todo handle non persistent presence operation sets */
        }

        MetaContactGroup newParentGroup
            = findParentMetaContactGroup(newParentMetaContact);

        ContactGroup parentProtoGroup = resolveProtoPath(contact
            .getProtocolProvider(), (MetaContactGroupImpl) newParentGroup);

        //if the contact is not currently in the proto group corresponding to
        //its new metacontact group parent then move it
        if(contact.getParentContactGroup() != parentProtoGroup && opSetPresence != null)
            opSetPresence.moveContactToGroup(contact, parentProtoGroup);

        ( (MetaContactImpl) newParentMetaContact).addProtoContact(contact);

        //fire an event telling everyone that contact has been added to its new
        //parent.
        fireProtoContactEvent(contact, ProtoContactEvent.PROTO_CONTACT_MOVED
            , currentParentMetaContact , newParentMetaContact);

        //if this was the last contact in the meta contact - remove it.
        //it is true that in some cases the move would be followed by some kind
        //of protocol provider events indicating the change which on its turn
        //may trigger the removal of empty meta contacts. Yet in many cases
        //particularly if parent groups were not changed in the protocol contact
        //list no event would come and the meta contact will remain empty
        //that's why we delete it here and if an event follows it would simply
        //be ignored.
        if (currentParentMetaContact.getContactCount() == 0)
        {
            MetaContactGroupImpl parentMetaGroup =
                currentParentMetaContact.getParentGroup();
            parentMetaGroup.removeMetaContact(currentParentMetaContact);

            fireMetaContactEvent(currentParentMetaContact, parentMetaGroup
                                     , MetaContactEvent.META_CONTACT_REMOVED);
        }
    }

    /**
     * Moves the specified <tt>MetaContact</tt> to <tt>newGroup</tt>.
     *
     * @param metaContact
     *            the <tt>MetaContact</tt> to move.
     * @param newMetaGroup
     *            the <tt>MetaContactGroup</tt> that should be the new parent
     *            of <tt>contact</tt>.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     * @throws IllegalArgumentException if <tt>newMetaGroup</tt> or
     * <tt>metaCOntact</tt> do not come from this implementation.
     */
    public void moveMetaContact(MetaContact metaContact,
                                MetaContactGroup newMetaGroup) throws
        MetaContactListException, IllegalArgumentException
    {
        if (! (newMetaGroup instanceof MetaContactGroupImpl))
        {
            throw new IllegalArgumentException(newMetaGroup
                                               +
                                               " is not a MetaContactGroupImpl instance");
        }

        if (! (metaContact instanceof MetaContactImpl))
        {
            throw new IllegalArgumentException(metaContact
                                               +
                                               " is not a MetaContactImpl instance");
        }

        //first remove the meta contact from its current parent:
        MetaContactGroupImpl currentParent
            = (MetaContactGroupImpl) findParentMetaContactGroup(metaContact);
        currentParent.removeMetaContact( (MetaContactImpl) metaContact);

        ( (MetaContactGroupImpl) newMetaGroup).addMetaContact(
            (MetaContactImpl) metaContact);

        try
        {
            //first make sure that the new meta contact group path is resolved
            //against all protocols that the MetaContact requires. then move
            //the meta contact in there and move all prot contacts inside it.
            Iterator<Contact> contacts = metaContact.getContacts();

            while (contacts.hasNext())
            {
                Contact protoContact =  contacts.next();

                ContactGroup protoGroup = resolveProtoPath(protoContact
                    .getProtocolProvider(), (MetaContactGroupImpl) newMetaGroup);

                //get a persistent or non persistent presence operation set
                OperationSetPersistentPresence opSetPresence
                    = protoContact
                        .getProtocolProvider()
                            .getOperationSet(
                                OperationSetPersistentPresence.class);

                if (opSetPresence == null)
                {
                    /** @todo handle non persistent presence operation sets */
                }
                else
                {
                    opSetPresence.moveContactToGroup(protoContact, protoGroup);
                }
            }
        }
        catch (Exception ex)
        {
            logger.error("Cannot move contact", ex);

            // now move the contact to prevoius parent
            ((MetaContactGroupImpl)newMetaGroup).
                removeMetaContact( (MetaContactImpl) metaContact);

            currentParent.addMetaContact((MetaContactImpl) metaContact);

            throw new MetaContactListException(ex.getMessage(),
                MetaContactListException.CODE_MOVE_CONTACT_ERROR);
        }

        //fire the mved event.
        fireMetaContactEvent(new MetaContactMovedEvent(
                                    metaContact, currentParent, newMetaGroup));
    }

    /**
     * Deletes the specified contact from both the local contact list and (if
     * applicable) the server stored contact list if supported by the
     * corresponding protocol.
     *
     * @param contact the contact to remove.
     * @throws MetaContactListException with an appropriate code if the
     * operation fails for some reason.
     */
    public void removeContact(Contact contact) throws MetaContactListException
    {
        //remove the contact from the provider and do nothing else
        //updating and/or removing the corresponding meta contact would happen
        //once a confirmation event is received from the underlying protocol
        //provider
        OperationSetPresence opSetPresence
            = contact
                .getProtocolProvider()
                    .getOperationSet(OperationSetPresence.class);

        //in case the provider only has a persistent operation set:
        if (opSetPresence == null)
        {
            opSetPresence =
                (OperationSetPresence) contact.getProtocolProvider()
                    .getOperationSet(OperationSetPersistentPresence.class);

            if (opSetPresence == null)
            {
                throw new IllegalStateException(
                    "Cannot remove a contact from a provider with no presence "
                    + "operation set.");
            }
        }

        try
        {
            opSetPresence.unsubscribe(contact);
        }
        catch (Exception ex)
        {
            throw new MetaContactListException("Failed to remove "
                                               + contact +
                                               " from its protocol provider.",
                                               ex
                                               ,
                                               MetaContactListException.
                                               CODE_NETWORK_ERROR);
        }
    }

    /**
     * Removes a listener previously added with <tt>addContactListListener</tt>.
     *
     * @param listener the listener to remove
     */
    public void removeMetaContactListListener(
        MetaContactListListener listener)
    {
        synchronized (metaContactListListeners)
        {
            this.metaContactListListeners.remove(listener);
        }
    }

    /**
     * Removes the specified <tt>metaContact</tt> as well as all of its
     * underlying contacts.
     *
     * @param metaContact
     *            the metaContact to remove.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public void removeMetaContact(MetaContact metaContact) throws
        MetaContactListException
    {
        Iterator<Contact> protoContactsIter = metaContact.getContacts();

        while (protoContactsIter.hasNext())
        {
            removeContact( protoContactsIter.next());
        }

        //do not fire events. that will be done by the contact listener as soon
        //as it gets confirmation events of proto contact removal

        //the removal of the last contact would also generate an even for the
        //removal of the meta contact itself.
    }

    /**
     * Removes the specified meta contact group, all its corresponding protocol
     * specific groups and all their children.
     *
     * @param groupToRemove
     *            the <tt>MetaContactGroup</tt> to have removed.
     * @throws MetaContactListException
     *             with an appropriate code if the operation fails for some
     *             reason.
     */
    public void removeMetaContactGroup(
        MetaContactGroup groupToRemove) throws MetaContactListException
    {
        if (! (groupToRemove instanceof MetaContactGroupImpl))
        {
            throw new IllegalArgumentException(groupToRemove
                                               +
                                               " is not an instance of MetaContactGroupImpl");
        }

        try
        {
            //remove all proto groups and then remove the meta group as well.
            Iterator<ContactGroup> protoGroups = groupToRemove.getContactGroups();

            while (protoGroups.hasNext())
            {
                ContactGroup protoGroup = protoGroups.next();

                OperationSetPersistentPresence opSetPersPresence
                    = protoGroup
                        .getProtocolProvider()
                            .getOperationSet(
                                OperationSetPersistentPresence.class);

                if (opSetPersPresence == null)
                {
                    /** @todo handle removal of non persistent proto groups */
                    return;
                }

                opSetPersPresence.removeServerStoredContactGroup(protoGroup);
            }
        }catch(Exception ex)
        {
            throw new MetaContactListException(ex.getMessage(),
                MetaContactListException.CODE_REMOVE_GROUP_ERROR);
        }


        MetaContactGroupImpl parentMetaGroup = (MetaContactGroupImpl)
            findParentMetaContactGroup(groupToRemove);

        parentMetaGroup.removeSubgroup(groupToRemove);

        fireMetaContactGroupEvent( groupToRemove, null, null
            , MetaContactGroupEvent.META_CONTACT_GROUP_REMOVED);
    }

    /**
     * Removes the protocol specific group from the specified meta contact group
     * and removes from meta contacts all proto contacts that belong to the
     * same provider as the group which is being removed.
     * @param metaContainer the MetaContactGroup that we'd like to remove a
     * contact group from.
     * @param groupToRemove the ContactGroup that we'd like removed.
     * @param sourceProvider the ProtocolProvider that the contact group belongs
     * to.
     */
    public void removeContactGroupFromMetaContactGroup(
        MetaContactGroupImpl metaContainer,
        ContactGroup groupToRemove,
        ProtocolProviderService sourceProvider)
    {

        /*
         * Go through all meta contacts and remove all contacts that belong to
         * the same provider and are therefore children of the group that is
         * being removed.
         */
        locallyRemoveAllContactsForProvider(metaContainer, groupToRemove);

        fireMetaContactGroupEvent(
            metaContainer,
            sourceProvider,
            groupToRemove,
            MetaContactGroupEvent.CONTACT_GROUP_REMOVED_FROM_META_GROUP);
    }

    /**
     * Removes local resources storing copies of the meta contact list. This
     * method is meant primarily to aid automated testing which may depend on
     * beginning the tests with an empty local contact list.
     */
    public void purgeLocallyStoredContactListCopy()
    {
        this.storageManager.storeContactListAndStopStorageManager();
        this.storageManager.removeContactListFile();
        if (logger.isTraceEnabled())
            logger.trace("Removed meta contact list storage file.");
    }

    /**
     * Goes through the specified group and removes from all meta contacts,
     * protocol specific contacts belonging to the specified
     * <tt>groupToRemove</tt>. Note that this method won't undertake any calls
     * to the protocol itself as it is used only to update the local contact
     * list as a result of a server generated event.
     *
     * @param parentMetaGroup  the MetaContactGroup whose children we should go
     * through
     * @param groupToRemove the proto group that we want removed together with
     * its children.
     */
    private void locallyRemoveAllContactsForProvider(
                        MetaContactGroupImpl parentMetaGroup,
                        ContactGroup         groupToRemove)
    {
        Iterator<MetaContact> childrenContactsIter
                                        = parentMetaGroup.getChildContacts();

        //first go through all direct children.
        while (childrenContactsIter.hasNext())
        {
            MetaContactImpl child = (MetaContactImpl) childrenContactsIter.next();

            //Get references to all contacts that will be removed in case we
            //need to fire an event.
            Iterator<Contact> contactsToRemove
                = child.getContactsForContactGroup(groupToRemove);

            child.removeContactsForGroup(groupToRemove);

            //if this was the last proto contact inside this meta contact,
            //then remove the meta contact as well. Otherwise only fire an
            //event.
            if (child.getContactCount() == 0)
            {
                parentMetaGroup.removeMetaContact(child);
                fireMetaContactEvent(child, parentMetaGroup
                                     , MetaContactEvent.META_CONTACT_REMOVED);
            }
            else
            {
                // there are other proto contacts left in the contact child
                //meta contact so we'll have to send an event for each of the
                //removed contacts and not only a single event for the whole
                //meta contact.
                while (contactsToRemove.hasNext())
                {
                    fireProtoContactEvent(
                          contactsToRemove.next()
                        , ProtoContactEvent.PROTO_CONTACT_REMOVED
                        , child
                        , null);
                }
            }
        }

        Iterator<MetaContactGroup> subgroupsIter
            = parentMetaGroup.getSubgroups();

        //then go through all subgroups.
        while (subgroupsIter.hasNext())
        {
            MetaContactGroupImpl subMetaGroup
                = (MetaContactGroupImpl) subgroupsIter.next();

            Iterator<ContactGroup> contactGroups
                = subMetaGroup.getContactGroups();

            ContactGroup protoGroup = null;
            while(contactGroups.hasNext())
            {
                protoGroup = contactGroups.next();
                if(groupToRemove == protoGroup.getParentContactGroup())
                    this.locallyRemoveAllContactsForProvider(
                            subMetaGroup, protoGroup);
            }

            //remove the group if there are no children left.
            if(subMetaGroup.countSubgroups() == 0
               && subMetaGroup.countChildContacts() == 0)
            {
                parentMetaGroup.removeSubgroup(subMetaGroup);
                fireMetaContactGroupEvent(
                    subMetaGroup
                    , groupToRemove.getProtocolProvider()
                    , protoGroup
                    , MetaContactGroupEvent.META_CONTACT_GROUP_REMOVED);
            }
        }

        parentMetaGroup.removeProtoGroup(groupToRemove);
    }

    /**
     * Returns the MetaContactGroup corresponding to the specified contactGroup
     * or null if no such MetaContactGroup was found.
     * @return the MetaContactGroup corresponding to the specified contactGroup
     * or null if no such MetaContactGroup was found.
     * @param contactGroup
     *            the protocol specific <tt>contactGroup</tt> that we're looking
     *            for.
     */
    public MetaContactGroup findMetaContactGroupByContactGroup
        (ContactGroup contactGroup)
    {
        return rootMetaGroup.findMetaContactGroupByContactGroup(contactGroup);
    }

    /**
     * Returns the MetaContact containing the specified contact or null if no
     * such MetaContact was found. The method can be used when for example we
     * need to find the MetaContact that is the author of an incoming message
     * and the corresponding ProtocolProviderService has only provided a
     * <tt>Contact</tt> as its author.
     *
     * @param contact the protocol specific <tt>contact</tt> that we're looking
     *  for.
     *
     * @return the MetaContact containing the specified contact or null if no
     *         such contact is present in this contact list.
     */
    public MetaContact findMetaContactByContact(Contact contact)
    {
        return rootMetaGroup.findMetaContactByContact(contact);
    }

    /**
     * Returns the MetaContact containing a contact with an address equal to
     * <tt>contactAddress</tt> and with a source provider matching
     * <tt>accountID</tt>, or null if no such MetaContact was found. The method
     * can be used when for example we
     * need to find the MetaContact that is the author of an incoming message
     * and the corresponding ProtocolProviderService has only provided a
     * <tt>Contact</tt> as its author.
     *
     * @param contactAddress the address of the  protocol specific
     * <tt>contact</tt> that we're looking for.
     * @param accountID the ID of the account that the contact we're looking for
     * must belong to.
     *
     * @return the MetaContact containing the specified contact or null if no
     *         such contact is present in this contact list.
     */
    public MetaContact findMetaContactByContact(String contactAddress,
                                                String accountID)
    {
        return rootMetaGroup.findMetaContactByContact(contactAddress
                                                      , accountID);
    }

    /**
     * Returns the MetaContact that corresponds to the specified metaContactID.
     *
     * @param metaContactID
     *            a String identifier of a meta contact.
     * @return the MetaContact with the specified string identifier or null if
     *         no such meta contact was found.
     */
    public MetaContact findMetaContactByMetaUID(String metaContactID)
    {

        return rootMetaGroup.findMetaContactByMetaUID(metaContactID);
    }

    /**
     * Returns the MetaContactGroup that corresponds to the specified
     * metaGroupID.
     *
     * @param metaGroupID
     *            a String identifier of a meta contact group.
     * @return the MetaContactGroup with the specified string identifier or null
     *          if no such meta contact was found.
     */
    public MetaContactGroup findMetaContactGroupByMetaUID(String metaGroupID)
    {
        return rootMetaGroup.findMetaContactGroupByMetaUID(metaGroupID);
    }

    /**
     * Returns a list of all <tt>MetaContact</tt>s containing a protocol contact
     * from the given <tt>ProtocolProviderService</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> whose
     * contacts we're looking for.
     * @return a list of all <tt>MetaContact</tt>s containing a protocol contact
     * from the given <tt>ProtocolProviderService</tt>.
     */
    public Iterator<MetaContact> findAllMetaContactsForProvider(
                                    ProtocolProviderService protocolProvider)
    {
        List<MetaContact> resultList = new ArrayList<MetaContact>();

        this.findAllMetaContactsForProvider(protocolProvider,
                                            rootMetaGroup,
                                            resultList);

        return resultList.iterator();
    }

    /**
     * Returns a list of all <tt>MetaContact</tt>s contained in the given group
     * and containing a protocol contact from the given
     * <tt>ProtocolProviderService</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> whose
     * contacts we're looking for.
     * @param metaContactGroup the parent group.
     *
     * @return a list of all <tt>MetaContact</tt>s containing a protocol contact
     * from the given <tt>ProtocolProviderService</tt>.
     */
    public Iterator<MetaContact> findAllMetaContactsForProvider(
        ProtocolProviderService protocolProvider,
        MetaContactGroup metaContactGroup)
    {
        List<MetaContact> resultList = new LinkedList<MetaContact>();

        this.findAllMetaContactsForProvider(protocolProvider,
            metaContactGroup, resultList);

        return resultList.iterator();
    }

    /**
     * Returns a list of all <tt>MetaContact</tt>s contained in the given group
     * and containing a protocol contact from the given
     * <tt>ProtocolProviderService</tt>.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt> whose
     * contacts we're looking for.
     * @param metaContactGroup the parent group.
     * @param resultList the list containing the result of the search.
     */
    private void findAllMetaContactsForProvider(
        ProtocolProviderService protocolProvider,
        MetaContactGroup metaContactGroup,
        List<MetaContact> resultList)
    {
        Iterator<MetaContact> childContacts
            = metaContactGroup.getChildContacts();

        while (childContacts.hasNext())
        {
            MetaContact metaContact = childContacts.next();

            Iterator<Contact> protocolContacts
                = metaContact.getContactsForProvider(protocolProvider);

            if (protocolContacts.hasNext())
            {
                resultList.add(metaContact);
            }
        }

        Iterator<MetaContactGroup> subGroups
            = metaContactGroup.getSubgroups();

        while (subGroups.hasNext())
        {
            MetaContactGroup subGroup = subGroups.next();

            Iterator<ContactGroup> protocolSubgroups
                = subGroup.getContactGroupsForProvider(protocolProvider);

            if (protocolSubgroups.hasNext())
            {
                this.findAllMetaContactsForProvider(protocolProvider,
                                                    subGroup,
                                                    resultList);
            }
        }
    }

    /**
     * Goes through the server stored ContactList of the specified operation
     * set, retrieves all protocol specific contacts it contains and makes sure
     * they are all present in the local contact list.
     *
     * @param presenceOpSet
     *            the presence operation set whose contact list we'd like to
     *            synchronize with the local contact list.
     */
    private void synchronizeOpSetWithLocalContactList(
        OperationSetPersistentPresence presenceOpSet)
    {
        ContactGroup rootProtoGroup = presenceOpSet
            .getServerStoredContactListRoot();

        if (rootProtoGroup != null)
        {

            if (logger.isTraceEnabled())
                logger.trace("subgroups: "
                         + rootProtoGroup.countSubgroups());
            if (logger.isTraceEnabled())
                logger.trace("child contacts: "
                         + rootProtoGroup.countContacts());

            addContactGroupToMetaGroup(rootProtoGroup, rootMetaGroup, true);
        }

        presenceOpSet
            .addSubscriptionListener(clSubscriptionEventHandler);

        presenceOpSet
            .addServerStoredGroupChangeListener(clGroupEventHandler);
    }

    /**
     * Creates meta contacts and meta contact groups for all children of the
     * specified <tt>contactGroup</tt> and adds them to <tt>metaGroup</tt>
     * @param protoGroup the <tt>ContactGroup</tt> to add.
     * <p>
     * @param metaGroup the <tt>MetaContactGroup</tt> where <tt>ContactGroup</tt>
     * should be added.
     * @param fireEvents indicates whether or not events are to be fired upon
     * adding subcontacts and subgroups. When this method is called recursively,
     * the parameter should will be false in order to generate a minimal number
     * of events for the whole addition and not an event per every subgroup
     * and child contact.
     */
    private void addContactGroupToMetaGroup(ContactGroup protoGroup,
                                            MetaContactGroupImpl metaGroup,
                                            boolean fireEvents)
    {
        // first register the root group
        metaGroup.addProtoGroup(protoGroup);

        // register subgroups and contacts
        Iterator<ContactGroup> subgroupsIter = protoGroup.subgroups();

        while (subgroupsIter.hasNext())
        {
            ContactGroup group = subgroupsIter.next();

            //continue if we have already loaded this group from the locally
            //stored contact list.
            if(metaGroup.findMetaContactGroupByContactGroup(group) != null)
                continue;

            // right now we simply map this group to an existing one
            // without being cautious and verify whether we already have it
            // registered
            MetaContactGroupImpl newMetaGroup
                = new MetaContactGroupImpl(this, group.getGroupName());

            metaGroup.addSubgroup(newMetaGroup);

            addContactGroupToMetaGroup(group, newMetaGroup, false);

            if (fireEvents)
            {
                this.fireMetaContactGroupEvent(
                        newMetaGroup
                        , group.getProtocolProvider()
                        , group
                        , MetaContactGroupEvent.
                        META_CONTACT_GROUP_ADDED);
            }
        }

        // now add all contacts, located in this group
        Iterator<Contact> contactsIter = protoGroup.contacts();
        while (contactsIter.hasNext())
        {
            Contact contact = contactsIter.next();

            //continue if we have already loaded this contact from the locally
            //stored contact list.
            if(metaGroup.findMetaContactByContact(contact) != null)
                continue;


            MetaContactImpl newMetaContact = new MetaContactImpl();

            newMetaContact.addProtoContact(contact);

            metaGroup.addMetaContact(newMetaContact);

            if (fireEvents)
            {
                this.fireMetaContactEvent(newMetaContact,
                                          metaGroup,
                                          MetaContactEvent.META_CONTACT_ADDED);
            }
        }
    }

    /**
     * Adds the specified provider to the list of currently known providers. In
     * case the provider supports persistent presence the method would also
     * extract all contacts and synchronize them with the local contact list.
     * Otherwise it would start a process where local contacts would be added on
     * the server.
     *
     * @param provider the ProtocolProviderService that we've just detected.
     */
    private synchronized void handleProviderAdded(
                        ProtocolProviderService provider)
    {
        if (logger.isDebugEnabled())
            logger.debug("Adding protocol provider "
                     + provider.getAccountID().getAccountUniqueID());

        // check whether the provider has a persistent presence op set
        OperationSetPersistentPresence opSetPersPresence =
            provider.getOperationSet(OperationSetPersistentPresence.class);

        this.currentlyInstalledProviders.put(
                           provider.getAccountID().getAccountUniqueID(),
                           provider);

        //If we have a persistent presence op set - then retrieve its contact
        //list and merge it with the local one.
        if (opSetPersPresence != null)
        {
            //load contacts, stored in the local contact list and corresponding to
            //this provider.
            try
            {
                storageManager.extractContactsForAccount(
                    provider.getAccountID().getAccountUniqueID());
                if (logger.isDebugEnabled())
                    logger.debug("All contacts loaded for account "
                                + provider.getAccountID().getAccountUniqueID());
            }
            catch (XMLException exc)
            {
                logger.error("Failed to load contacts for account "
                             + provider.getAccountID().getAccountUniqueID(), exc);
            }
            synchronizeOpSetWithLocalContactList(opSetPersPresence);
        }
        else
        {
            if (logger.isDebugEnabled())
                logger.debug("Service did not have a pers. pres. op. set.");
        }

        /** @todo implement handling non persistent presence operation sets */

        //add a presence status listener so that we could reorder contacts upon
        //status change. NOTE that we MUST NOT add the presence listener before
        //extracting the locally stored contact list or  otherwise we'll get
        //events for all contacts that we have already extracted
        if(opSetPersPresence != null)
            opSetPersPresence.addContactPresenceStatusListener(this);

        // Check if the capabilities operation set is available for this
        // contact and add a listener to it in order to track capabilities'
        // changes for all contained protocol contacts.
        OperationSetContactCapabilities capOpSet
            = provider.getOperationSet(OperationSetContactCapabilities.class);

        if (capOpSet != null)
            capOpSet.addContactCapabilitiesListener(this);
    }

    /**
     * Removes the specified provider from the list of currently known providers
     * and ignores all the contacts that it has registered locally.
     *
     * @param provider
     *            the ProtocolProviderService that has been unregistered.
     */
    private void handleProviderRemoved(
        ProtocolProviderService provider)
    {
        if (logger.isDebugEnabled())
            logger.debug("Removing protocol provider "
                     + provider.getProtocolName());

        this.currentlyInstalledProviders.
            remove(provider.getAccountID().getAccountUniqueID());

        //get the root group for the provider so that we could remove it.
        OperationSetPersistentPresence persPresOpSet =
            provider.getOperationSet(OperationSetPersistentPresence.class);

        //ignore if persistent presence is not supported.
        if(persPresOpSet != null)
        {
          //we don't gare about subscription and presence status events here any
            //longer
            persPresOpSet.removeContactPresenceStatusListener(this);
            persPresOpSet.removeSubscriptionListener(
                clSubscriptionEventHandler);
            persPresOpSet.removeServerStoredGroupChangeListener(
                clGroupEventHandler);

            ContactGroup rootGroup
                = persPresOpSet.getServerStoredContactListRoot();

            //iterate all sub groups and remove them one by one
            //(we dont simply remove the root group because the mcl storage
            // manager is stupid (i wrote it) and doesn't know root groups exist.
            // that's why it needs to hear an event for every single group.)
            Iterator<ContactGroup> subgroups = rootGroup.subgroups();

            while(subgroups.hasNext())
            {
                ContactGroup group = subgroups.next();
                //remove the group
                this.removeContactGroupFromMetaContactGroup(
                    (MetaContactGroupImpl) findMetaContactGroupByContactGroup(
                                                                        group),
                    group,
                    provider);
            }

            //remove the root group
            this.removeContactGroupFromMetaContactGroup(
                this.rootMetaGroup, rootGroup, provider);
        }

        // Check if the capabilities operation set is available for this
        // contact and remove previously added listeners.
        OperationSetContactCapabilities capOpSet
            = provider.getOperationSet(OperationSetContactCapabilities.class);

        if (capOpSet != null)
            capOpSet.removeContactCapabilitiesListener(this);
    }

    /**
     * Registers <tt>group</tt> to the event ignore list. This would make the
     * method that is normally handling events for newly created groups ignore
     * any events for that particular group and leave the responsibility to the
     * method that added the group to the ignore list.
     *
     * @param group the name of the group that we'd like to
     * register.
     * @param ownerProvider the protocol provider that we expect the addition
     * to come from.
     */
    private void addGroupToEventIgnoreList(
        String group,
        ProtocolProviderService ownerProvider)
    {
        //first check whether registrations in the ignore list already
        //exist for this group.

        if (isGroupInEventIgnoreList(group, ownerProvider))
        {
            return;
        }

        List<ProtocolProviderService> existingProvList
                                        = this.groupEventIgnoreList.get(group);

        if (existingProvList == null)
        {
            existingProvList = new LinkedList<ProtocolProviderService>();
        }

        existingProvList.add(ownerProvider);
        groupEventIgnoreList.put(group, existingProvList);
    }

    /**
     * Verifies whether the specified group is in the group event ignore list.
     * @return true if the group is in the group event ignore list and false
     * otherwise.
     * @param group the group whose presence in the ignore list we'd like to
     * verify.
     * @param ownerProvider the provider that <tt>group</tt> belongs to.
     */
    private boolean isGroupInEventIgnoreList(
        String group, ProtocolProviderService ownerProvider)
    {
        List<ProtocolProviderService> existingProvList
            = this.groupEventIgnoreList.get(group);

        return existingProvList != null
            && existingProvList.contains(ownerProvider);
    }

    /**
     * Removes the <tt>group</tt> from the group event ignore list so that
     * events concerning this group get treated.
     *
     * @param group the group whose that we'd want out of the ignore list.
     * @param ownerProvider the provider that <tt>group</tt> belongs to.
     */
    private void removeGroupFromEventIgnoreList(
        String group, ProtocolProviderService ownerProvider)
    {
        //first check whether the registration actually exists.
        if (!isGroupInEventIgnoreList(group, ownerProvider))
        {
            return;
        }

        List<ProtocolProviderService> existingProvList
                                    = this.groupEventIgnoreList.get(group);

        if (existingProvList.size() < 1)
        {
            groupEventIgnoreList.remove(group);
        }
        else
        {
            existingProvList.remove(ownerProvider);
        }
    }

    /**
     * Registers <tt>contact</tt> to the event ignore list. This would make the
     * method that is normally handling events for newly created contacts ignore
     * any events for that particular contact and leave the responsibility to
     * the method that added the contact to the ignore list.
     *
     * @param contact the address of the contact that we'd like to ignore.
     * @param ownerProvider the protocol provider that we expect the addition
     * to come from.
     */
    private void addContactToEventIgnoreList(
        String contact,
        ProtocolProviderService ownerProvider)
    {
        //first check whether registrations in the ignore list already
        //exist for this contact.

        if (isContactInEventIgnoreList(contact, ownerProvider))
        {
            return;
        }

        List<ProtocolProviderService> existingProvList
            = this.contactEventIgnoreList.get(contact);

        if (existingProvList == null)
        {
            existingProvList = new LinkedList<ProtocolProviderService>();
        }

        existingProvList.add(ownerProvider);
        contactEventIgnoreList.put(contact, existingProvList);
    }

    /**
     * Verifies whether the specified contact is in the contact event ignore
     * list.
     * @return true if the contact is in the contact event ignore list and false
     * otherwise.
     * @param contact the contact whose presence in the ignore list we'd like to
     * verify.
     * @param ownerProvider the provider that <tt>contact</tt> belongs to.
     */
    private boolean isContactInEventIgnoreList(
        String contact, ProtocolProviderService ownerProvider)
    {
        List<ProtocolProviderService> existingProvList
            = this.contactEventIgnoreList.get(contact);

        return existingProvList != null
            && existingProvList.contains(ownerProvider);
    }

    /**
     * Verifies whether the specified contact is in the contact event ignore
     * list. The reason we need this method in addition to the one that takes a
     * string contact address is necessary for the following reason: In some
     * cases the ID that we create a contact with (e.g. mybuddy) could be
     * different from the one returned by its getAddress() method (e.g.
     * mybuddy@hisnet.com). If this is the case we hope that the difference
     * would be handled gracefully in the equals method of the contact so
     * we also compare with it.
     *
     * @return true if the contact is in the contact event ignore list and false
     * otherwise.
     * @param contact the contact whose presence in the ignore list we'd like to
     * verify.
     * @param ownerProvider the provider that <tt>contact</tt> belongs to.
     */
    private boolean isContactInEventIgnoreList(
                                        Contact contact,
                                        ProtocolProviderService ownerProvider)
    {
        for (Map.Entry<String, List<ProtocolProviderService>> contactEventIgnoreEntry
                : contactEventIgnoreList.entrySet())
        {
            String contactAddress = contactEventIgnoreEntry.getKey();

            if(contact.getAddress().equals(contactAddress)
               || contact.equals(contactAddress))
            {
                List<ProtocolProviderService> existingProvList
                    = contactEventIgnoreEntry.getValue();

                return existingProvList != null
                    && existingProvList.contains(ownerProvider);
            }
        }

        return false;
    }

    /**
     * Removes the <tt>contact</tt> from the group event ignore list so that
     * events concerning this group get treated.
     *
     * @param contact the contact whose that we'd want out of the ignore list.
     * @param ownerProvider the provider that <tt>group</tt> belongs to.
     */
    private void removeContactFromEventIgnoreList(
        String contact, ProtocolProviderService ownerProvider)
    {
        //first check whether the registration actually exists.
        if (!isContactInEventIgnoreList(contact, ownerProvider))
        {
            return;
        }

        List<ProtocolProviderService> existingProvList
                                = this.contactEventIgnoreList.get(contact);

        if (existingProvList.size() < 1)
        {
            groupEventIgnoreList.remove(contact);
        }
        else
        {
            existingProvList.remove(ownerProvider);
        }
    }

    /**
     * Implements the <tt>ServiceListener</tt> method. Verifies whether the
     * passed event concerns a <tt>ProtocolProviderService</tt> and modifies
     * the list of registered protocol providers accordingly.
     *
     * @param event
     *            The <tt>ServiceEvent</tt> object.
     */
    public void serviceChanged(ServiceEvent event)
    {
        Object sService = bundleContext.getService(event
            .getServiceReference());

        if (logger.isTraceEnabled())
            logger.trace("Received a service event for: "
                     + sService.getClass().getName());

        // we don't care if the source service is not a protocol provider
        if (! (sService instanceof ProtocolProviderService))
        {
            return;
        }

        if (logger.isDebugEnabled())
            logger.debug("Service is a protocol provider.");

        ProtocolProviderService provider =
            (ProtocolProviderService)sService;
        //first check if the event really means that the accounts is
        //uninstalled/installed (or is it just stopped ... e.g. we could be
        // shutting down, or in the other case it could be just modified) ...
        // before that however, we'd need to get a reference to the service.
        ProtocolProviderFactory sourceFactory = null;

        ServiceReference[] allBundleServices
            = event.getServiceReference().getBundle()
                .getRegisteredServices();

        for (ServiceReference bundleServiceRef : allBundleServices)
        {
            Object service = bundleContext.getService(bundleServiceRef);
            if(service instanceof ProtocolProviderFactory)
            {
                sourceFactory = (ProtocolProviderFactory) service;
                break;
            }
        }

        if (event.getType() == ServiceEvent.REGISTERED)
        {
            if (logger.isDebugEnabled())
                logger.debug("Handling registration of a new Protocol Provider.");
            // if we have the PROVIDER_MASK property set, make sure that this
            // provider has it and if not ignore it.
            String providerMask = System
                .getProperty(MetaContactListService.PROVIDER_MASK_PROPERTY);
            if (providerMask != null
                && providerMask.trim().length() > 0)
            {
                String servRefMask = (String) event
                    .getServiceReference()
                    .getProperty(
                        MetaContactListService.PROVIDER_MASK_PROPERTY);

                if (servRefMask == null
                    || !servRefMask.equals(providerMask))
                {
                    if (logger.isDebugEnabled())
                        logger.debug("Ignoing masked provider: "
                                        + provider.getAccountID());
                    return;
                }
            }

            if(sourceFactory != null
               && currentlyInstalledProviders.containsKey(
                               provider.getAccountID().getAccountUniqueID()))
            {
                if (logger.isDebugEnabled())
                    logger.debug("An already installed account: "
                                + provider.getAccountID() + ". Modifying it.");
                // the account is already installed and this event is coming
                // from a modification. we don't return here as
                // the account is removed and added again and we must
                // create its unresolved contact and give him a chance to resolve
                // them and not fire new subscription to duplicate the already
                // existing.

                //return;
            }

            this.handleProviderAdded( (ProtocolProviderService) sService);
        }
        else if (event.getType() == ServiceEvent.UNREGISTERING)
        {
            if(sourceFactory == null)
            {
                //strange ... we must be shutting down. just bail
                return;
            }

            AccountID accountID = provider.getAccountID();

            // If the account is still registered or is just unloaded but
            // remains stored we remove its contacts but without storing this
            if(ContactlistActivator
                    .getAccountManager()
                        .getStoredAccounts()
                            .contains(accountID))
            {
                //the account is still installed it means we are modifying it.
                // we remove all its contacts from current contactlist
                // but remove the storage manager in order to avoid
                // losing those contacts from the storage
                // as its modification later unresolved contacts will be created
                // which will be resolved from the already modified account
                synchronized(this)
                {
                    this.removeMetaContactListListener(storageManager);
                    this.handleProviderRemoved(
                        (ProtocolProviderService)sService);
                    this.addMetaContactListListener(storageManager);
                }

                return;
            }

            if (logger.isDebugEnabled())
                logger.debug("Account uninstalled. acc.id="
                         +provider.getAccountID() +". Removing from meta "
                         +"contact list.");
            this.handleProviderRemoved( (ProtocolProviderService) sService);
        }
    }

    /**
     * The class would listen for events delivered to
     * <tt>SubscriptionListener</tt>s.
     */
    private class ContactListSubscriptionListener
        implements SubscriptionListener
    {

        /**
         * Creates a meta contact for the source contact indicated by the
         * specified SubscriptionEvent, or updates an existing one if there
         * is one. The method would also generate the corresponding
         * <tt>MetaContactEvent</tt>.
         *
         * @param evt the SubscriptionEvent that we'll be handling.
         */
        public void subscriptionCreated(SubscriptionEvent evt)
        {
            if (logger.isTraceEnabled())
                logger.trace("Subscription created: " + evt);

            //ignore the event if the source contact is in the ignore list
            if (isContactInEventIgnoreList(
                      evt.getSourceContact()
                    , evt.getSourceProvider()))
            {
                return;
            }

            MetaContactGroupImpl parentGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup(evt.getParentGroup());

            if (parentGroup == null)
            {
                logger.error("Received a subscription for a group that we "
                             + "hadn't seen before! ");
                return;
            }

            MetaContactImpl newMetaContact = new MetaContactImpl();

            newMetaContact.addProtoContact(evt.getSourceContact());

            newMetaContact.setDisplayName(evt
                                          .getSourceContact().getDisplayName());

            parentGroup.addMetaContact(newMetaContact);

            //fire the meta contact event.
            fireMetaContactEvent(newMetaContact,
                                 parentGroup,
                                 MetaContactEvent.META_CONTACT_ADDED);

            //make sure we have a local copy of the avatar;
            newMetaContact.getAvatar();
        }

        /**
         * Indicates that a contact/subscription has been moved from one server
         * stored group to another. The way we handle the event depends on
         * whether the source contact/subscription is the only proto contact
         * found in its current MetaContact encapsulator or not.
         * <p>
         * If this is the case (the source contact has no siblings in its current
         * meta contact list encapsulator) then we will move the whole meta
         * contact to the meta contact group corresponding to the new parent
         * ContactGroup of the source contact. In this case we would only fire
         * a MetaContactMovedEvent containing the old and new parents of the
         * MetaContact in question.
         * <p>
         * If, however, the MetaContact that currently encapsulates the source
         * contact also encapsulates other proto contacts, then we will create
         * a new MetaContact instance, place it in the MetaContactGroup
         * corresponding to the new parent ContactGroup of the source contact
         * and add the source contact inside it. In this case we would first
         * fire a metacontact added event over the empty meta contact and then,
         * once the proto contact has been moved inside it, we would also fire
         * a ProtoContactEvent with event id PROTO_CONTACT_MOVED.
         * <p>
         * @param evt a reference to the SubscriptionMovedEvent containing previous
         * and new parents as well as a ref to the source contact.
         */
        public void subscriptionMoved(SubscriptionMovedEvent evt)
        {
            if (logger.isTraceEnabled())
                logger.trace("Subscription moved: " + evt);

            //ignore the event if the source contact is in the ignore list
            if (isContactInEventIgnoreList(
                     evt.getSourceContact()
                   , evt.getSourceProvider()))
            {
                return;
            }

            MetaContactGroupImpl oldParentGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup(evt.getOldParentGroup());
            MetaContactGroupImpl newParentGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup(evt.getNewParentGroup());

            if (newParentGroup == null || oldParentGroup == null)
            {
                logger.error("Received a subscription for a group that we "
                             + "hadn't seen before! ");
                return;
            }

            MetaContactImpl currentMetaContact = (MetaContactImpl)
                               findMetaContactByContact(evt.getSourceContact());

            if(currentMetaContact == null)
            {
                logger.warn("Received a move event for a contact that is "
                            +"not in our contact list."
                            , new NullPointerException(
                                    "Received a move event for a contact that "
                                    +"is not in our contact list."));
                return;
            }

             //if the move was caused by us (when merging contacts) then chances
            //are that the contact is already in the right group
            MetaContactGroup currentParentGroup
                = currentMetaContact.getParentMetaContactGroup();

            if(currentParentGroup == newParentGroup)
            {
                return;
            }

            //if the meta contact does not have other children apart from the
            //contact that we're currently moving then move the whole meta
            //contact to the new parent group.
            if( currentMetaContact.getContactCount() == 1 )
            {
                oldParentGroup.removeMetaContact(currentMetaContact);
                newParentGroup.addMetaContact(currentMetaContact);
                fireMetaContactEvent(new MetaContactMovedEvent(
                    currentMetaContact, oldParentGroup, newParentGroup));
            }
            //if the source contact is not the only contact encapsulated by the
            //currentMetaContact, then create a new meta contact in the new
            //parent group and move the source contact to it.
            else
            {
                MetaContactImpl newMetaContact = new MetaContactImpl();
                newMetaContact.setDisplayName(evt
                                          .getSourceContact().getDisplayName());
                newParentGroup.addMetaContact(newMetaContact);

                //fire an event notifying that a new meta contact was added.
                fireMetaContactEvent(newMetaContact,
                                     newParentGroup,
                                     MetaContactEvent.META_CONTACT_ADDED);

                //move the proto contact and fire the corresponding event
                currentMetaContact.removeProtoContact(evt.getSourceContact());
                newMetaContact.addProtoContact(evt.getSourceContact());

                fireProtoContactEvent(evt.getSourceContact()
                                      , ProtoContactEvent.PROTO_CONTACT_MOVED
                                      , currentMetaContact
                                      , newMetaContact);
            }
        }

        public void subscriptionFailed(SubscriptionEvent evt)
        {
            if (logger.isTraceEnabled())
                logger.trace("Subscription failed: " + evt);
        }

        /**
         * Events delivered through this method are ignored as they are of no
         * interest to this implementation of the meta contact list service.
         * @param evt the SubscriptionEvent containing the source contact
         */
        public void subscriptionResolved(SubscriptionEvent evt)
        {
            //this was a contact we already had so all we need to do is
            //update it's details
            MetaContactImpl mc = (MetaContactImpl) findMetaContactByContact(evt
                            .getSourceContact());

            if(mc != null)
            {
                mc.getAvatar();
            }
        }

        /**
         * In the case where the event refers to a change in the display name
         * we compare the old value with the display name of the corresponding
         * meta contact. If they are equal this means that the user has not
         * specified their own display name for the meta contact and that the
         * display name was using this contact's display name for its own
         * display name. In this case we change the display name of the meta
         * contact to match the new display name of the proto contact.
         * <p>
         * @param evt the <tt>ContactPropertyChangeEvent</tt> containing the source
         * contact and the old and new values of the changed property.
         */
        public void contactModified(ContactPropertyChangeEvent evt)
        {
            MetaContactImpl mc
                = (MetaContactImpl)findMetaContactByContact(
                    evt.getSourceContact());

            if( ContactPropertyChangeEvent.PROPERTY_DISPLAY_NAME
                            .equals(evt.getPropertyName()))
            {
                if( evt.getOldValue() != null
                    && evt.getOldValue().equals(mc.getDisplayName()))
                {
                    renameMetaContact(mc, (String)evt.getNewValue());
                }
                else
                {
                    //we get here if the name of a contact has changed but the
                    //meta contact list is not going to reflect any change
                    //because it is not displaying that name. in this case we
                    //simply make sure everyone (e.g. the storage manager)
                    //knows about the change.
                    fireProtoContactEvent(evt.getSourceContact(),
                                    ProtoContactEvent.PROTO_CONTACT_MODIFIED,
                                    mc,
                                    mc);
                }
            }
            else if( ContactPropertyChangeEvent.PROPERTY_IMAGE
                            .equals(evt.getPropertyName())
                && evt.getNewValue() != null)
            {
                changeMetaContactAvatar(
                                mc,
                                evt.getSourceContact(),
                                (byte[])evt.getNewValue());
            }
        }

        /**
         * Locates the <tt>MetaContact</tt> corresponding to the contact
         * that has been removed and updates it. If the removed proto contact
         * was the last one in it, then the <tt>MetaContact</tt> is also
         * removed.
         *
         * @param evt the <tt>SubscriptionEvent</tt> containing the contact
         * that has been removed.
         */
        public void subscriptionRemoved(SubscriptionEvent evt)
        {

            if (logger.isTraceEnabled())
                logger.trace("Subscription removed: " + evt);

            MetaContactImpl metaContact = (MetaContactImpl)
                findMetaContactByContact(evt.getSourceContact());

            MetaContactGroupImpl metaContactGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup(evt.getParentGroup());

            metaContact.removeProtoContact(evt.getSourceContact());

            //if this was the last protocol specific contact in this meta
            //contact then remove the meta contact as well.
            if (metaContact.getContactCount() == 0)
            {
                metaContactGroup.removeMetaContact(metaContact);

                fireMetaContactEvent(metaContact,
                                     metaContactGroup,
                                     MetaContactEvent.META_CONTACT_REMOVED);
            }
            else
            {
                //this was not the las proto contact so only generate the
                //corresponding event.
                fireProtoContactEvent(evt.getSourceContact(),
                    ProtoContactEvent.PROTO_CONTACT_REMOVED, metaContact, null);

            }
        }
    }

    /**
     * The class would listen for events delivered to
     * <tt>ServerStoredGroupListener</tt>s.
     */
    private class ContactListGroupListener
        implements ServerStoredGroupListener
    {

        /**
         * The method is called upon receiving notification that a new server
         * stored group has been created.
         * @param parent  a reference to the <tt>MetaContactGroupImpl</tt> where
         * <tt>group</tt>'s newly created <tt>MetaContactGroup</tt> wrapper
         * should be added as a subgroup.
         * @param group the newly added <tt>ContactGroup</tt>
         * @return the <tt>MetaContactGroup</tt> that now wraps the newly
         *  created <tt>ContactGroup</tt>.
         */
        private MetaContactGroup handleGroupCreatedEvent(
                                             MetaContactGroupImpl parent,
                                             ContactGroup group)
        {
            //if parent already contains a meta group with the same name, we'll
            //reuse it as the container for the new contact group.
            MetaContactGroupImpl newMetaGroup = (MetaContactGroupImpl)parent
                .getMetaContactSubgroup(group.getGroupName());

            //if there was no meta group with the specified name, create a new
            //one
            if(newMetaGroup == null)
            {
                newMetaGroup
                    = new MetaContactGroupImpl(
                            MetaContactListServiceImpl.this,
                            group.getGroupName());
                newMetaGroup.addProtoGroup(group);
                parent.addSubgroup(newMetaGroup);
            }
            else
            {
                newMetaGroup.addProtoGroup(group);
            }

            //check if there were any subgroups
            Iterator<ContactGroup> subgroups = group.subgroups();

            while(subgroups.hasNext())
            {
                ContactGroup subgroup = subgroups.next();
                handleGroupCreatedEvent(newMetaGroup, subgroup);
            }

            Iterator<Contact> contactsIter = group.contacts();

            while (contactsIter.hasNext())
            {
                Contact contact = contactsIter.next();

                MetaContactImpl newMetaContact = new MetaContactImpl();

                newMetaContact.addProtoContact(contact);

                newMetaContact.setDisplayName(contact
                                              .getDisplayName());

                newMetaGroup.addMetaContact(newMetaContact);
            }

            return newMetaGroup;
        }

        /**
         * Adds the source group and its child contacts to the meta contact
         * list.
         * @param evt the ServerStoredGroupEvent containing the source group.
         */
        public void groupCreated(ServerStoredGroupEvent evt)
        {

            if (logger.isTraceEnabled())
                logger.trace("ContactGroup created: " + evt);

            //ignore the event if the source group is in the ignore list
            if (isGroupInEventIgnoreList(evt.getSourceGroup().getGroupName()
                                         , evt.getSourceProvider()))
            {
                return;
            }

            MetaContactGroupImpl parentMetaGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup( evt.getParentGroup());

            if (parentMetaGroup == null)
            {
                logger.error("Failed to identify a parent where group "
                    + evt.getSourceGroup().getGroupName() + "should be placed.");
            }

            // add parent group to the ServerStoredGroupEvent
            MetaContactGroup newMetaGroup
                = handleGroupCreatedEvent(parentMetaGroup, evt.getSourceGroup());

            //if this was the first contact group in the meta group fire an
            //ADDED event. otherwise fire a modification event.
            if(newMetaGroup.countContactGroups() > 1)
            {
                fireMetaContactGroupEvent(
                    newMetaGroup
                    , evt.getSourceProvider()
                    , evt.getSourceGroup()
                    , MetaContactGroupEvent.CONTACT_GROUP_ADDED_TO_META_GROUP);
            }
            else
            {
                fireMetaContactGroupEvent(
                    newMetaGroup
                    , evt.getSourceProvider()
                    , evt.getSourceGroup()
                    , MetaContactGroupEvent.META_CONTACT_GROUP_ADDED);
            }
        }

        /**
         * Dummy implementation.
         * <p>
         * @param evt a ServerStoredGroupEvent containing the source group.
         */
        public void groupResolved(ServerStoredGroupEvent evt)
        {
            //we couldn't care less :)
        }

        /**
         * Updates the local contact list by removing the meta contact group
         * corresponding to the group indicated by the delivered <tt>evt</tt>
         * @param evt the ServerStoredGroupEvent confining the group that has
         * been removed.
         */
        public void groupRemoved(ServerStoredGroupEvent evt)
        {

            if (logger.isTraceEnabled())
                logger.trace("ContactGroup removed: " + evt);

            MetaContactGroupImpl metaContactGroup = (MetaContactGroupImpl)
                findMetaContactGroupByContactGroup(evt.getSourceGroup());

            if (metaContactGroup == null)
            {
                logger.error(
                    "Received a RemovedGroup event for an orphan grp: "
                    + evt.getSourceGroup());
                return;
            }

            removeContactGroupFromMetaContactGroup(metaContactGroup,
                evt.getSourceGroup(), evt.getSourceProvider());

            //do not remove the meta contact group even if this is the las
            //protocol specific contact group. Contrary to contacts, meta
            //contact groups are to only be remove upon user indication or
            //otherwise it would be difficult for a user to create a new grp.
        }

        /**
         * Nothing to do here really. Oh yes .... we should actually trigger
         * a MetaContactGroup event indicating the change for interested parties
         * but that's all.
         * @param evt the ServerStoredGroupEvent containing the source group.
         */
        public void groupNameChanged(ServerStoredGroupEvent evt)
        {
            if (logger.isTraceEnabled())
                logger.trace("ContactGroup renamed: " + evt);

            MetaContactGroup metaContactGroup
                = findMetaContactGroupByContactGroup(evt.getSourceGroup());

            fireMetaContactGroupEvent(
                metaContactGroup
                , evt.getSourceProvider()
                , evt.getSourceGroup()
                , MetaContactGroupEvent.CONTACT_GROUP_RENAMED_IN_META_GROUP);
        }
    }

    /**
     * Creates the corresponding MetaContact event and notifies all
     * <tt>MetaContactListListener</tt>s that a MetaContact is added or
     * removed from the MetaContactList.
     *
     * @param sourceContact the contact that this event is about.
     * @param parentGroup the group that the source contact belongs or belonged
     * to.
     * @param eventID the id indicating the exavt type of the event to fire.
     */
    private synchronized void fireMetaContactEvent(MetaContact sourceContact,
                                      MetaContactGroup parentGroup,
                                      int eventID)
    {
        MetaContactEvent evt
            = new MetaContactEvent(sourceContact, parentGroup, eventID);
        if (logger.isTraceEnabled())
            logger.trace("Will dispatch the following mcl event: "
                     + evt);

        for (MetaContactListListener listener : getMetaContactListListeners())
        {
            switch (evt.getEventID())
            {
                case MetaContactEvent.META_CONTACT_ADDED:
                    listener.metaContactAdded(evt);
                    break;
                case MetaContactEvent.META_CONTACT_REMOVED:
                    listener.metaContactRemoved(evt);
                    break;
                default:
                    logger.error("Unknown event type " + evt.getEventID());
            }
        }
    }

    /**
     * Gets a copy of the list of current <code>MetaContactListListener</code>
     * interested in events fired by this instance.
     *
     * @return an array of <code>MetaContactListListener</code>s currently
     *         interested in events fired by this instance. The returned array
     *         is a copy of the internal listener storage and thus can be safely
     *         modified.
     */
    private MetaContactListListener[] getMetaContactListListeners()
    {
        MetaContactListListener[] listeners;

        synchronized (metaContactListListeners)
        {
            listeners
                = metaContactListListeners.toArray(
                        new MetaContactListListener[
                                metaContactListListeners.size()]);
        }
        return listeners;
    }

    /**
     * Creates the corresponding <tt>MetaContactPropertyChangeEvent</tt>
     * instance and notifies all <tt>MetaContactListListener</tt>s that a
     * MetaContact has been modified. Synchronized to avoid firing events
     * when we are editing the account (there we temporally remove and then
     * add again the storage manager and don't want anybody to interrupt us).
     *
     * @param event the event to dispatch.
     */
    synchronized void fireMetaContactEvent(MetaContactPropertyChangeEvent event)
    {
        if (logger.isTraceEnabled())
            logger.trace("Will dispatch the following mcl property change event: "
                     + event);

        for (MetaContactListListener listener : getMetaContactListListeners())
        {
            if (event instanceof MetaContactMovedEvent)
            {
                listener.metaContactMoved( (MetaContactMovedEvent) event);
            }
            else if (event instanceof MetaContactRenamedEvent)
            {
                listener.metaContactRenamed( (MetaContactRenamedEvent) event);
            }
            else if (event instanceof MetaContactModifiedEvent)
            {
                listener.metaContactModified( (MetaContactModifiedEvent) event);
            }
            else if (event instanceof MetaContactAvatarUpdateEvent)
            {
                listener.metaContactAvatarUpdated(
                    (MetaContactAvatarUpdateEvent) event);
            }
        }
    }

    /**
     * Creates the corresponding <tt>ProtoContactEvent</tt> instance and
     * notifies all <tt>MetaContactListListener</tt>s that a protocol specific
     * <tt>Contact</tt> has been added moved or removed.
     * Synchronized to avoid firing events
     * when we are editing the account (there we temporally remove and then
     * add again the storage manager and don't want anybody to interrupt us).
     *
     * @param source the contact that has caused the event.
     * @param eventName One of the ProtoContactEvent.PROTO_CONTACT_XXX fields
     * indicating the exact type of the event.
     * @param oldParent the <tt>MetaContact</tt> that was wrapping the source
     * <tt>Contact</tt> before the event occurred or <tt>null</tt> if the event
     * is caused by adding a new <tt>Contact</tt>
     * @param newParent the <tt>MetaContact</tt> that is wrapping the source
     * <tt>Contact</tt> after the event occurred or <tt>null</tt> if the event
     * is caused by removing a <tt>Contact</tt>
     */
    private synchronized void fireProtoContactEvent(Contact     source,
                                       String      eventName,
                                       MetaContact oldParent,
                                       MetaContact newParent)
    {
        ProtoContactEvent event
            = new ProtoContactEvent(source, eventName, oldParent, newParent );

        if (logger.isTraceEnabled())
            logger.trace("Will dispatch the following mcl property change event: "
                     + event);

        for (MetaContactListListener listener : getMetaContactListListeners())
        {
            if (eventName.equals(ProtoContactEvent.PROTO_CONTACT_ADDED))
            {
                listener.protoContactAdded(event);
            }
            else if (eventName.equals(ProtoContactEvent.PROTO_CONTACT_MOVED))
            {
                listener.protoContactMoved(event);
            }
            else if (eventName.equals(ProtoContactEvent.PROTO_CONTACT_REMOVED))
            {
                listener.protoContactRemoved(event);
            }
            else if (eventName.equals(ProtoContactEvent.PROTO_CONTACT_MODIFIED))
            {
                listener.protoContactModified(event);
            }
        }
    }

    /**
     * Upon each status notification this method finds the corresponding meta
     * contact and updates the ordering in its parent group.
     * <p>
     * @param evt the ContactPresenceStatusChangeEvent describing the status
     * change.
     */
    public void contactPresenceStatusChanged(
        ContactPresenceStatusChangeEvent evt)
    {
        MetaContactImpl metaContactImpl =
            (MetaContactImpl) findMetaContactByContact(evt.getSourceContact());

        //ignore if we have no meta contact.
        if(metaContactImpl == null)
            return;

        int oldContactIndex = metaContactImpl.getParentGroup()
            .indexOf(metaContactImpl);

        int newContactIndex = metaContactImpl.reevalContact();

        if(oldContactIndex != newContactIndex)
        {
            fireMetaContactGroupEvent(
                findParentMetaContactGroup(metaContactImpl)
                , evt.getSourceProvider()
                , null
                , MetaContactGroupEvent.CHILD_CONTACTS_REORDERED);
        }
    }


    /**
     * The method is called from the storage manager whenever a new contact
     * group has been parsed and it has to be created.
     * @param parentGroup the group that contains the meta contact group we're
     * about to load.
     * @param metaContactGroupUID the unique identifier of the meta contact
     * group.
     * @param displayName the name of the meta contact group.
     *
     * @return the newly created meta contact group.
     */
    MetaContactGroupImpl loadStoredMetaContactGroup(
        MetaContactGroupImpl parentGroup,
        String metaContactGroupUID,
        String displayName)
    {
        //first check if the group exists already.
        MetaContactGroupImpl newMetaGroup = (MetaContactGroupImpl) parentGroup
            .getMetaContactSubgroupByUID(metaContactGroupUID);

        //if the group exists then we have already loaded it for another
        //account and we should reuse the same instance.
        if(newMetaGroup != null)
            return newMetaGroup;

        newMetaGroup
            = new MetaContactGroupImpl(this, displayName, metaContactGroupUID);

        parentGroup.addSubgroup(newMetaGroup);

        //I don't think this method needs to produce events since it is
        //currently only called upon initialization ... but it doesn't hurt
        //trying
        fireMetaContactGroupEvent(newMetaGroup, null, null
            , MetaContactGroupEvent.META_CONTACT_GROUP_ADDED);

        return newMetaGroup;
    }

    /**
     * Creates a unresolved instance of the proto specific contact group
     * according to the specified arguments and adds it to
     * <tt>containingMetaContactGroup</tt>
     *
     * @param containingMetaGroup the <tt>MetaContactGroupImpl</tt> where the
     * restored contact group should be added.
     * @param contactGroupUID the unique identifier of the group.
     * @param parentProtoGroup the identifier of the parent proto group.
     * @param persistentData the persistent data last returned by the contact
     * group.
     * @param accountID the ID of the account that the proto group belongs to.
     *
     * @return a reference to the newly created (unresolved) contact group.
     */
    ContactGroup loadStoredContactGroup(MetaContactGroupImpl containingMetaGroup,
                                        String               contactGroupUID,
                                        ContactGroup         parentProtoGroup,
                                        String               persistentData,
                                        String               accountID)
    {
        //get the presence op set
        ProtocolProviderService sourceProvider =
            currentlyInstalledProviders.get(accountID);
        OperationSetPersistentPresence presenceOpSet
            = sourceProvider
                .getOperationSet(OperationSetPersistentPresence.class);

        ContactGroup newProtoGroup = presenceOpSet.createUnresolvedContactGroup(
            contactGroupUID, persistentData,
                (parentProtoGroup == null)
                    ? presenceOpSet.getServerStoredContactListRoot()
                    : parentProtoGroup);

        containingMetaGroup.addProtoGroup(newProtoGroup);

        return newProtoGroup;
    }

    /**
     * The method is called from the storage manager whenever a new contact
     * has been parsed and it has to be created.
     * @param parentGroup the group that contains the meta contact we're about
     * to load.
     * @param metaUID the unique identifier of the meta contact.
     * @param displayName the display name of the meta contact.
     * @param details the details for the contact to create.
     * @param protoContacts a list containing descriptors of proto contacts
     * encapsulated by the meta contact that we're about to create.
     * @param accountID the identifier of the account that the contacts
     * originate from.
     */
    void loadStoredMetaContact(
            MetaContactGroupImpl parentGroup,
            String metaUID,
            String displayName,
            Map<String, List<String>> details,
            List<MclStorageManager.StoredProtoContactDescriptor> protoContacts,
            String accountID)
    {
        //first check if the meta contact exists already.
        MetaContactImpl newMetaContact
            = (MetaContactImpl)findMetaContactByMetaUID(metaUID);

        if(newMetaContact == null)
        {
            newMetaContact = new MetaContactImpl(metaUID, details);
            newMetaContact.setDisplayName(displayName);
        }

        //create unresolved contacts for the protocontacts associated with this
        //mc
        ProtocolProviderService sourceProvider =
            currentlyInstalledProviders.get(accountID);
        OperationSetPersistentPresence presenceOpSet
            = sourceProvider
                .getOperationSet(OperationSetPersistentPresence.class);

        for (MclStorageManager.StoredProtoContactDescriptor contactDescriptor
                : protoContacts)
        {
            //this contact has already been registered by another meta contact
            //so we'll ignore it. If this is the only contact in the meta
            //contact, we'll throw an exception at the end of the method and
            //cause the mcl storage manager to remove it.
            MetaContact mc = findMetaContactByContact(
                contactDescriptor.contactAddress, accountID);

            if(mc != null)
            {
                logger.warn("Ignoring duplicate proto contact "
                            + contactDescriptor
                            + " accountID=" + accountID
                            + ". The contact was also present in the "
                            + "folloing meta contact:" + mc);
                continue;
            }

            Contact protoContact = presenceOpSet.createUnresolvedContact(
                contactDescriptor.contactAddress,
                contactDescriptor.persistentData,
                ( contactDescriptor.parentProtoGroup == null )
                    ? presenceOpSet.getServerStoredContactListRoot()
                    : contactDescriptor.parentProtoGroup);

            newMetaContact.addProtoContact(protoContact);
        }

        if(newMetaContact.getContactCount() == 0)
        {
            logger.error("Found an empty meta contact. Throwing an exception "
                + "so that the storage manager would remove it.");
            throw new IllegalArgumentException("MetaContact["
                + newMetaContact
                +"] contains no non-duplicating child contacts.");
        }

        parentGroup.addMetaContact(newMetaContact);

        fireMetaContactEvent(   newMetaContact,
                                parentGroup,
                                MetaContactEvent.META_CONTACT_ADDED);

        if (logger.isTraceEnabled())
            logger.trace("Created meta contact: " + newMetaContact);
    }

    /**
     * Creates the corresponding MetaContactGroup event and notifies all
     * <tt>MetaContactListListener</tt>s that a MetaContactGroup is added or
     * removed from the MetaContactList.
     * Synchronized to avoid firing events
     * when we are editing the account (there we temporally remove and then
     * add again the storage manager and don't want anybody to interrupt us).
     *
     * @param source
     *            the MetaContactGroup instance that is added to the
     *            MetaContactList
     * @param provider
     *            the ProtocolProviderService instance where this event occurred
     * @param sourceProtoGroup the proto group associated with this event or
     *            null if the event does not concern a particular source group.
     * @param eventID
     *            one of the METACONTACT_GROUP_XXX static fields indicating the
     *            nature of the event.
     */
    private synchronized void fireMetaContactGroupEvent( MetaContactGroup source,
                                            ProtocolProviderService provider,
                                            ContactGroup sourceProtoGroup,
                                            int eventID)
    {
        MetaContactGroupEvent evt = new MetaContactGroupEvent(
            source, provider, sourceProtoGroup, eventID);

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

        for (MetaContactListListener listener : getMetaContactListListeners())
        {
            switch (eventID)
            {
                case MetaContactGroupEvent.META_CONTACT_GROUP_ADDED:
                    listener.metaContactGroupAdded(evt);
                    break;
                case MetaContactGroupEvent.META_CONTACT_GROUP_REMOVED:
                    listener.metaContactGroupRemoved(evt);
                    break;
                case MetaContactGroupEvent.CHILD_CONTACTS_REORDERED:
                    listener.childContactsReordered(evt);
                    break;
                case MetaContactGroupEvent
                    .META_CONTACT_GROUP_RENAMED:
                case MetaContactGroupEvent
                    .CONTACT_GROUP_RENAMED_IN_META_GROUP:
                case MetaContactGroupEvent
                    .CONTACT_GROUP_REMOVED_FROM_META_GROUP:
                case MetaContactGroupEvent
                    .CONTACT_GROUP_ADDED_TO_META_GROUP:
                    listener.metaContactGroupModified(evt);
                    break;
                default:
                    logger.error("Unknown event type (" + eventID
                                 + ") for event: " + evt);
            }
        }
    }

    /**
     * Utility class used for blocking the current thread until an event
     * is delivered confirming the creation of a particular group.
     */
    private static class BlockingGroupEventRetriever
        implements ServerStoredGroupListener
    {
        private final String groupName;

        public ServerStoredGroupEvent evt = null;

        /**
         * Creates an instance of the retriever that will wait for events
         * confirming the creation of the group with the specified name.
         * @param groupName the name of the group whose birth we're waiting for.
         */
        BlockingGroupEventRetriever(String groupName)
        {
            this.groupName = groupName;
        }

        /**
         * Called whoever an indication is received that a new server stored
         * group is created.
         * @param evt a ServerStoredGroupChangeEvent containing a reference to
         * the newly created group.
         */
        public synchronized void groupCreated(ServerStoredGroupEvent event)
        {
            if (event.getSourceGroup().getGroupName().equals(groupName))
            {
                this.evt = event;
                this.notifyAll();
            }
        }

        /**
         * Evens delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupRemoved(ServerStoredGroupEvent event)
        {}

        /**
         * Evens delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupNameChanged(ServerStoredGroupEvent event)
        {}

        /**
         * Evens delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupResolved(ServerStoredGroupEvent event)
        {}

        /**
         * Block the execution of the current thread until either a group
         * created event is received or milis miliseconds pass.
         * @param millis the number of millis that we should wait before we
         * determine failure.
         */
        public synchronized void waitForEvent(long millis)
        {
            //no need to wait if an event is already there.
            if (evt == null)
            {
                try
                {
                    this.wait(millis);
                }
                catch (InterruptedException ex)
                {
                    logger.error("Interrupted while waiting for group creation",
                                 ex);
                }
            }
        }
    }

    /**
     * Utility class used for blocking the current thread until an event
     * is delivered confirming the creation of a particular contact.
     */
    private static class BlockingSubscriptionEventRetriever
        implements SubscriptionListener,
                   ServerStoredGroupListener
    {
        private final String      subscriptionAddress;

        public  Contact     sourceContact = null;
        public  EventObject evt = null;

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupResolved(ServerStoredGroupEvent event)
        {}

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupRemoved(ServerStoredGroupEvent event)
        {}

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void groupNameChanged(ServerStoredGroupEvent event)
        {}

        /**
         * Creates an instance of the retriever that will wait for events
         * confirming the creation of the subscription with the specified
         * address.
         * @param subscriptionAddress the name of the group whose birth we're waiting for.
         */
        BlockingSubscriptionEventRetriever(String subscriptionAddress)
        {
            this.subscriptionAddress = subscriptionAddress;
        }

        /**
         * Called whenever an indication is received that a new server stored group
         * is created.
         * @param event a ServerStoredGroupEvent containing a reference to the
         * newly created group.
         */
        public synchronized void groupCreated(ServerStoredGroupEvent event)
        {
            Contact contact
                = event.getSourceGroup().getContact(subscriptionAddress);
            if ( contact != null)
            {
                this.evt = event;
                this.sourceContact = contact;
                this.notifyAll();
            }
        }

        /**
         * Called whenever an indication is received that a subscription is
         * created.
         * @param event a <tt>SubscriptionEvent</tt> containing a reference to
         * the newly created contact.
         */
        public synchronized void subscriptionCreated(SubscriptionEvent event)
        {
            if (event.getSourceContact().getAddress()
                    .equals(subscriptionAddress)
                || event.getSourceContact().equals(subscriptionAddress))
            {
                this.evt = event;
                this.sourceContact = event.getSourceContact();
                this.notifyAll();
            }
        }

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void subscriptionRemoved(SubscriptionEvent event)
        {}

        /**
         * Called whenever an indication is received that a subscription
         * creation has failed.
         * @param event a <tt>SubscriptionEvent</tt> containing a reference to
         * the contact we are trying to subscribe.
         */
        public synchronized void subscriptionFailed(SubscriptionEvent event)
        {
            if (event.getSourceContact().getAddress()
                    .equals(subscriptionAddress))
            {
                this.evt = event;
                this.sourceContact = event.getSourceContact();
                this.notifyAll();
            }
        }

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void subscriptionMoved(SubscriptionMovedEvent event)
        {}

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void subscriptionResolved(SubscriptionEvent event)
        {}

        /**
         * Events delivered through this method are ignored
         * @param evt param ignored
         */
        public void contactModified(ContactPropertyChangeEvent event)
        {}

        /**
         * Block the execution of the current thread until either a contact
         * created event is received or milis miliseconds pass.
         * @param millis the number of milis to wait upon determining a failure.
         */
        public synchronized void waitForEvent(long millis)
        {
            //no need to wait if an event is already there.
            if (evt == null)
            {
                try
                {
                    this.wait(millis);
                }
                catch (InterruptedException ex)
                {
                    logger.error(
                        "Interrupted while waiting for contact creation"
                        , ex);
                }
            }
        }
    }

    /**
     * Notifies this listener that the list of the <tt>OperationSet</tt>
     * capabilities of a <tt>Contact</tt> has changed.
     * 
     * @param event a <tt>ContactCapabilitiesEvent</tt> with ID
     * {@link ContactCapabilitiesEvent#SUPPORTED_OPERATION_SETS_CHANGED} which
     * specifies the <tt>Contact</tt> whose list of <tt>OperationSet</tt>
     * capabilities has changed
     */
    public void supportedOperationSetsChanged(ContactCapabilitiesEvent event)
    {
        // If the source contact isn't contained in this meta contact we have
        // nothing more to do here.
        MetaContactImpl metaContactImpl
            = (MetaContactImpl) findMetaContactByContact(
                event.getSourceContact());

        //ignore if we have no meta contact.
        if(metaContactImpl == null)
            return;

        fireCapabilitiesEvent(metaContactImpl,
            MetaContactCapabilitiesEvent.SUPPORTED_OPERATION_SETS_CHANGED);
    }

    /**
     * Fires a new <tt>MetaContactCapabilitiesEvent</tt> to notify the
     * registered <tt>MetaContactCapabilitiesListener</tt>s that this
     * <tt>MetaContact</tt> has changed its list of <tt>OperationSet</tt>
     * capabilities.
     *
     * @param metaContact the source <tt>MetaContact</tt>, which capabilities
     * has changed
     * @param eventID the ID of the event to be fired which indicates the
     * specifics of the change of the list of <tt>OperationSet</tt> capabilities
     * of the specified <tt>sourceContact</tt> and the details of the event
     */
    private void fireCapabilitiesEvent(MetaContact metaContact, int eventID)
    {
        MetaContactListListener[] listeners;

        synchronized (metaContactListListeners)
        {
            listeners
                = metaContactListListeners.toArray(
                        new MetaContactListListener[
                                metaContactListListeners.size()]);
        }
        if (listeners.length != 0)
        {
            MetaContactCapabilitiesEvent event
                = new MetaContactCapabilitiesEvent(metaContact, eventID);

            for (MetaContactListListener listener : listeners)
            {
                switch (eventID)
                {
                case MetaContactCapabilitiesEvent
                        .SUPPORTED_OPERATION_SETS_CHANGED:
                    listener.metaContactCapabilitiesChanged(event);
                    break;
                default:
                    if (logger.isDebugEnabled())
                    {
                        logger.debug(
                                "Cannot fire MetaContactCapabilitiesEvent with"
                                    + " unsupported eventID: "
                                    + eventID);
                    }
                    throw new IllegalArgumentException("eventID");
                }
            }
        }
    }
}