aboutsummaryrefslogtreecommitdiffstats
path: root/src/net/java/sip/communicator/impl/protocol/sip/OperationSetPresenceSipImpl.java
blob: 2fce57ec7fd9181b0a12397f44c153009c01586b (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
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
/*
 * Jitsi, the OpenSource Java VoIP and Instant Messaging client.
 *
 * Copyright @ 2015 Atlassian Pty Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.java.sip.communicator.impl.protocol.sip;

import java.net.URI;
import java.text.*;
import java.util.*;

import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;

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

import org.jitsi.util.xml.XMLUtils;
import org.w3c.dom.*;

/**
 * Sip presence implementation (SIMPLE).
 *
 * Compliant with rfc3261, rfc3265, rfc3856, rfc3863, rfc4480 and rfc3903
 *
 * @author Benoit Pradelle
 * @author Lyubomir Marinov
 * @author Emil Ivov
 * @author Grigorii Balutsel
 */
public class OperationSetPresenceSipImpl
    extends AbstractOperationSetPersistentPresence<ProtocolProviderServiceSipImpl>
    implements MethodProcessor,
               RegistrationStateChangeListener
{
    /**
     * Our class logger.
     */
    private static final Logger logger
        = Logger.getLogger(OperationSetPresenceSipImpl.class);


    private ServerStoredContactList ssContactList;

    /**
     * The currently active status message.
     */
    private String statusMessage = "Default Status Message";

    /**
     * Our default presence status.
     */
    private PresenceStatus presenceStatus;

    /**
     * List of all the CallIds to wait before unregister
     * Content : String
     */
    private final List<String> waitedCallIds = new Vector<String>();

    /**
     * Do we have to use a distant presence agent (default initial value)
     */
    private boolean useDistantPA;

    /**
     * Entity tag associated with the current communication with the distant PA
     */
    private String distantPAET = null;

    /**
     * The default expiration value of a request as defined for the presence
     * package in rfc3856. This is the value used when there is no Expires
     * header in the received subscription requests.
     */
    private static final int PRESENCE_DEFAULT_EXPIRE = 3600;

    /**
     * How many seconds before a timeout should we refresh our state
     */
    private static final int REFRESH_MARGIN = 60;

    /**
     * User chosen expiration value of any of our subscriptions.
     * Currently, the value is the default value defined in the rfc.
     */
    private final int subscriptionDuration;

    /**
     * The current CSeq used in the PUBLISH requests
     */
    private static long publish_cseq = 1;

    /**
     * The timer which will handle all the scheduled tasks
     */
    private final TimerScheduler timer = new TimerScheduler();

    /**
     * The re-PUBLISH task if any
     */
    private RePublishTask republishTask = null;

    /**
     * The interval between two execution of the polling task (in ms.)
     */
    private final int pollingTaskPeriod;

    /**
     * The task in charge of polling offline contacts
     */
    private PollOfflineContactsTask pollingTask = null;

    /**
     * If we should be totally silenced, just doing local operations
     */
    private final boolean presenceEnabled;

    private final SipStatusEnum sipStatusEnum;

    /**
     * The id used in <tt><tuple></tt>  and <tt><person></tt> elements
     * of pidf documents.
     */
    private static final String TUPLE_ID = "t" + (long)(Math.random() * 10000);
    private static final String PERSON_ID = "p" + (long)(Math.random() * 10000);

    /**
     * XML documents types.
     * The notify body content as said in rfc3856.
     */
    private static final String PIDF_XML        = "pidf+xml";

    /**
     * XML documents types.
     * The notify body content as said in rfc3857.
     */
    private static final String WATCHERINFO_XML = "watcherinfo+xml";

    // pidf elements and attributes
    private static final String PRESENCE_ELEMENT= "presence";
    private static final String NS_ELEMENT      = "xmlns";
    private static final String PIDF_NS_VALUE   = "urn:ietf:params:xml:ns:pidf";
    private static final String ENTITY_ATTRIBUTE= "entity";
    private static final String TUPLE_ELEMENT   = "tuple";
    private static final String ID_ATTRIBUTE    = "id";
    private static final String STATUS_ELEMENT  = "status";
    private static final String ONLINE_STATUS   = "open";
    private static final String OFFLINE_STATUS  = "closed";
    private static final String BASIC_ELEMENT   = "basic";
    private static final String CONTACT_ELEMENT = "contact";
    private static final String NOTE_ELEMENT    = "note";
    private static final String PRIORITY_ATTRIBUTE  = "priority";

    // rpid elements and attributes
    private static final String RPID_NS_ELEMENT = "xmlns:rpid";
    private static final String RPID_NS_VALUE   =
                                            "urn:ietf:params:xml:ns:pidf:rpid";
    private static final String DM_NS_ELEMENT   = "xmlns:dm";
    private static final String DM_NS_VALUE     =
                                    "urn:ietf:params:xml:ns:pidf:data-model";
    private static final String PERSON_ELEMENT  = "person";
    private static final String NS_PERSON_ELT   = "dm:person";
    private static final String ACTIVITY_ELEMENT= "activities";
    private static final String NS_ACTIVITY_ELT = "rpid:activities";
    private static final String AWAY_ELEMENT    = "away";
    private static final String NS_AWAY_ELT     = "rpid:away";
    private static final String BUSY_ELEMENT    = "busy";
    private static final String NS_BUSY_ELT     = "rpid:busy";
    private static final String OTP_ELEMENT     = "on-the-phone";
    private static final String NS_OTP_ELT      = "rpid:on-the-phone";
    private static final String STATUS_ICON_ELEMENT = "status-icon";
    private static final String NS_STATUS_ICON_ELT  = "rpid:status-icon";

    // namespace wildcard
    private static final String ANY_NS          = "*";

    private static final String WATCHERINFO_NS_VALUE
            = "urn:ietf:params:xml:ns:watcherinfo";
    private static final String WATCHERINFO_ELEMENT= "watcherinfo";
    private static final String STATE_ATTRIBUTE = "state";
    private static final String VERSION_ATTRIBUTE = "version";
    private static final String WATCHERLIST_ELEMENT= "watcher-list";
    private static final String RESOURCE_ATTRIBUTE = "resource";
    private static final String PACKAGE_ATTRIBUTE = "package";
    private static final String WATCHER_ELEMENT= "watcher";

    /**
     * The <code>EventPackageNotifier</code> which provides the ability of this
     * instance to act as a notifier for the presence event package.
     */
    private final EventPackageNotifier notifier;

    /**
     * The <code>EventPackageSubscriber</code> which provides the ability of
     * this instance to act as a subscriber for the presence event package.
     */
    private final EventPackageSubscriber subscriber;

    /**
     * The <code>EventPackageSubscriber</code> which provides the ability of
     * this instance to act as a subscriber for the presence.winfo event package.
     */
    private final EventPackageSubscriber watcherInfoSubscriber;

    /**
     * The authorization handler, asking client for authentication.
     */
    private AuthorizationHandler authorizationHandler = null;

    /**
     * Watcher status from the watchers info list.
     */
    private static enum WatcherStatus
    {
        PENDING("pending"),
        ACTIVE("active"),
        WAITING("waiting"),
        TERMINATED("terminated");

        /**
         * The value.
         */
        private final String value;

        /**
         * Creates <tt>WatcherStatus</tt>
         * @param v value.
         */
        WatcherStatus(String v)
        {
            this.value = v;
        }

        /**
         * Returns the <tt>String</tt> representation of this status.
         *
         * @return the <tt>String</tt> representation of this status
         */
        public String getValue()
        {
            return this.value;
        }
    }

    /**
     * Creates an instance of this operation set keeping a reference to the
     * specified parent <tt>provider</tt>.
     * @param provider the ProtocolProviderServiceSipImpl instance that
     * created us.
     * @param presenceEnabled if we are activated or if we don't have to
     * handle the presence informations for contacts
     * @param forceP2PMode if we should start in the p2p mode directly
     * @param pollingPeriod the period between two poll for offline contacts
     * @param subscriptionExpiration the default subscription expiration value
     * to use
     */
    public OperationSetPresenceSipImpl(
        ProtocolProviderServiceSipImpl provider,
        boolean presenceEnabled,
        boolean forceP2PMode,
        int pollingPeriod,
        int subscriptionExpiration)
    {
        super(provider);

        //this.contactListRoot = new ContactGroupSipImpl("RootGroup", provider);

        // if xivo is enabled use it, otherwise keep old behaviour
        // and enable xcap, it will check and see its not configure and will
        // silently do nothing and leave local storage
        if(provider.getAccountID().getAccountPropertyBoolean(
                SipAccountID.XIVO_ENABLE, false))
        {
            this.ssContactList = new ServerStoredContactListXivoImpl(
                    provider, this);
        }
        else
        {
            this.ssContactList = new ServerStoredContactListSipImpl(
                    provider, this);

            provider.addSupportedOperationSet(
                OperationSetContactTypeInfo.class,
                new OperationSetContactTypeInfoImpl(this));
        }

        //this.ssContactList.addGroupListener();

        //add our registration listener
        this.parentProvider.addRegistrationStateChangeListener(this);

        this.presenceEnabled = presenceEnabled;

        this.subscriptionDuration
            = (subscriptionExpiration > 0)
                ? subscriptionExpiration
                : PRESENCE_DEFAULT_EXPIRE;

        if (this.presenceEnabled)
        {
            // Subscriber part of the presence event package
            this.subscriber
                = new EventPackageSubscriber(
                        this.parentProvider,
                        "presence",
                        this.subscriptionDuration,
                        PIDF_XML,
                        this.timer,
                        REFRESH_MARGIN);
            this.notifier
                = new EventPackageNotifier(this.parentProvider, "presence",
                        PRESENCE_DEFAULT_EXPIRE, PIDF_XML, this.timer)
                {
                    /**
                     * Creates a new <tt>PresenceNotificationSubscription</tt>
                     * instance.
                     * @param fromAddress our AOR
                     * @param eventId the event id to use.
                     */
                    @Override
                    protected Subscription createSubscription(
                                Address fromAddress, String eventId)
                    {
                        return new PresenceNotifierSubscription(
                                    fromAddress, eventId);
                    }
                };

            this.watcherInfoSubscriber
                = new EventPackageSubscriber(
                        this.parentProvider,
                        "presence.winfo",
                        this.subscriptionDuration,
                        WATCHERINFO_XML,
                        this.timer,
                        REFRESH_MARGIN);
        }
        else
        {
            this.subscriber = null;
            this.notifier = null;
            this.watcherInfoSubscriber = null;
        }

        // Notifier part of the presence event package and PUBLISH
        this.parentProvider.registerMethodProcessor(Request.SUBSCRIBE, this);
        this.parentProvider.registerMethodProcessor(Request.NOTIFY, this);
        this.parentProvider.registerMethodProcessor(Request.PUBLISH, this);
        this.parentProvider.registerEvent("presence");

        if (logger.isDebugEnabled())
            logger.debug(
                    "presence initialized with :"
                    + presenceEnabled + ", "
                    + forceP2PMode + ", "
                    + pollingPeriod + ", "
                    + subscriptionExpiration
                    + " for " + this.parentProvider.getOurDisplayName());

        // retrieve the options for this account
        this.pollingTaskPeriod
            = (pollingPeriod > 0) ? (pollingPeriod * 1000) : 30000;

        // if we force the p2p mode, we start by not using a distant PA
        this.useDistantPA = !forceP2PMode;

        this.sipStatusEnum = parentProvider.getSipStatusEnum();
        this.presenceStatus = sipStatusEnum.getStatus(SipStatusEnum.OFFLINE);
    }

    /**
     * Registers a listener that would receive events upong changes in server
     * stored groups.
     *
     * @param listener a ServerStoredGroupChangeListener impl that would receive
     *                 events upong group changes.
     */
    @Override
    public void addServerStoredGroupChangeListener(
            ServerStoredGroupListener listener)
    {
        ssContactList.addGroupListener(listener);
    }

    /**
     * Removes the specified group change listener so that it won't receive
     * any further events.
     *
     * @param listener the ServerStoredGroupChangeListener to remove
     */
    @Override
    public void removeServerStoredGroupChangeListener(
            ServerStoredGroupListener listener)
    {
        ssContactList.removeGroupListener(listener);
    }

    /**
     * Returns a PresenceStatus instance representing the state this provider is
     * currently in. Note that PresenceStatus instances returned by this method
     * MUST adequately represent all possible states that a provider might
     * enter during its lifecycle, including those that would not be visible
     * to others (e.g. Initializing, Connecting, etc ..) and those that will be
     * sent to contacts/buddies (On-Line, Eager to chat, etc.).
     *
     * @return the PresenceStatus last published by this provider.
     */
    public PresenceStatus getPresenceStatus()
    {
        return this.presenceStatus;
    }

    /**
     * Sets if we should use a distant presence agent.
     *
     * @param useDistantPA
     *            <tt>true</tt> if we should use a distant presence agent
     */
    private void setUseDistantPA(boolean useDistantPA)
    {
        this.useDistantPA = useDistantPA;

        if (!this.useDistantPA && (this.republishTask != null))
        {
            this.republishTask.cancel();
            this.republishTask = null;
        }
    }

    /**
     * Returns the root group of the server stored contact list.
     *
     * @return the root ContactGroup for the ContactList stored by this
     *   service.
     */
    public ContactGroup getServerStoredContactListRoot()
    {
        return this.ssContactList.getRootGroup();
    }

    /**
     * Creates a group with the specified name and parent in the server
     * stored contact list.
     *
     * @param parentGroup the group where the new group should be created
     * @param groupName the name of the new group to create.
     * @throws OperationFailedException
     */
    public void createServerStoredContactGroup(ContactGroup parentGroup,
                                               String groupName)
            throws OperationFailedException
    {
        if (!(parentGroup instanceof ContactGroupSipImpl))
        {
            String errorMessage = String.format(
                    "Group %1s does not seem to belong to this protocol's " +
                            "contact list", parentGroup.getGroupName());
            throw new IllegalArgumentException(errorMessage);
        }
        ContactGroupSipImpl sipGroup = (ContactGroupSipImpl) parentGroup;
        ssContactList.createGroup(sipGroup, groupName, true);
    }

    /**
     * Creates and returns a unresolved contact group from the specified
     * <tt>address</tt> and <tt>persistentData</tt>. The method will not try
     * to establish a network connection and resolve the newly created
     * <tt>ContactGroup</tt> against the server or the contact itself. The
     * protocol provider will later resolve the contact group. When this happens
     * the corresponding event would notify interested subscription listeners.
     *
     * @param groupUID an identifier, returned by ContactGroup's getGroupUID,
     * that the protocol provider may use in order to create the group.
     * @param persistentData a String returned ContactGroups's
     * getPersistentData() method during a previous run and that has been
     * persistently stored locally.
     * @param parentGroup the group under which the new group is to be created
     * or null if this is group directly underneath the root.
     * @return the unresolved <tt>ContactGroup</tt> created from the specified
     * <tt>uid</tt> and <tt>persistentData</tt>
     */
    public ContactGroup createUnresolvedContactGroup(String groupUID,
        String persistentData, ContactGroup parentGroup)
    {
        //if parent is null then we're adding under root.
        if(parentGroup == null)
        {
            parentGroup = getServerStoredContactListRoot();
        }
        String groupName = ContactGroupSipImpl.createNameFromUID(groupUID);
        return ssContactList.createUnresolvedContactGroup(
                (ContactGroupSipImpl) parentGroup, groupName);
    }


    /**
     * Renames the specified group from the server stored contact list.
     *
     * @param group the group to rename.
     * @param newName the new name of the group.
     */
    public void renameServerStoredContactGroup(ContactGroup group,
                                               String newName)
    {
        if (!(group instanceof ContactGroupSipImpl))
        {
            String errorMessage = String.format(
                    "Group %1s does not seem to belong to this protocol's " +
                            "contact list", group.getGroupName());
            throw new IllegalArgumentException(errorMessage);
        }
        ssContactList.renameGroup((ContactGroupSipImpl) group, newName);
    }

    /**
     * Removes the specified contact from its current parent and places it
     * under <tt>newParent</tt>.
     *
     * @param contactToMove the <tt>Contact</tt> to move
     * @param newParent the <tt>ContactGroup</tt> where <tt>Contact</tt>
     *   would be placed.
     */
    public void moveContactToGroup(Contact contactToMove,
                                   ContactGroup newParent)
    {
        if (!(contactToMove instanceof ContactSipImpl))
        {
            return;
        }
        try
        {
            ssContactList.moveContactToGroup((ContactSipImpl) contactToMove,
                    (ContactGroupSipImpl) newParent);

            if (this.presenceEnabled)
            {
                subscriber.subscribe(new PresenceSubscriberSubscription(
                        (ContactSipImpl)contactToMove));
            }
        }
        catch (OperationFailedException ex)
        {
            throw new IllegalStateException(
                    "Failed to move contact " + contactToMove.getAddress(), ex);
        }
    }

    /**
     * Removes the specified group from the server stored contact list.
     *
     * @param group the group to remove.
     *
     * @throws IllegalArgumentException if <tt>group</tt> was not found in this
     * protocol's contact list.
     */
    public void removeServerStoredContactGroup(ContactGroup group)
    {
        if (!(group instanceof ContactGroupSipImpl))
        {
            String errorMessage = String.format(
                    "Group %1s does not seem to belong to this protocol's " +
                            "contact list", group.getGroupName());
            throw new IllegalArgumentException(errorMessage);
        }
        ContactGroupSipImpl sipGroup = (ContactGroupSipImpl) group;
        ssContactList.removeGroup(sipGroup);
    }

    /**
     * Requests the provider to enter into a status corresponding to the
     * specified parameters.
     *
     * @param status the PresenceStatus as returned by
     *   getRequestableStatusSet
     * @param statusMsg the message that should be set as the reason to
     *   enter that status
     * @throws IllegalArgumentException if the status requested is not a
     *   valid PresenceStatus supported by this provider.
     * @throws IllegalStateException if the provider is not currently
     *   registered.
     * @throws OperationFailedException with code NETWORK_FAILURE if
     *   publishing the status fails due to a network error.
     */
    public void publishPresenceStatus(
            PresenceStatus status,
            String statusMsg)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        PresenceStatus oldStatus = this.presenceStatus;
        this.presenceStatus = status;
        String oldMessage = this.statusMessage;
        this.statusMessage = statusMsg;

        if (this.presenceEnabled == false
            || parentProvider.getRegistrarConnection()
                instanceof SipRegistrarlessConnection)//no registrar-no publish
        {
            // inform the listeners of these changes in order to reflect
            // to GUI
            this.fireProviderStatusChangeEvent(oldStatus);
            this.fireProviderMsgStatusChangeEvent(oldMessage);

            return;
        }

        // in the offline status, the protocol provider is already unregistered
        if (!status.equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)))
            assertConnected();

        // now inform our distant presence agent if we have one
        if (this.useDistantPA)
        {
            Request req = null;
            if (status.equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)))
            {
                // unpublish our state
                req = createPublish(0, false);

                // remember the callid to be sure that the publish arrived
                // before unregister
                synchronized (this.waitedCallIds)
                {
                    this.waitedCallIds.add(((CallIdHeader)
                        req.getHeader(CallIdHeader.NAME)).getCallId());
                }
            }
            else
            {
                req = createPublish(this.subscriptionDuration, true);
            }

            ClientTransaction transac = null;
            try
            {
                transac = this.parentProvider
                    .getDefaultJainSipProvider().getNewClientTransaction(req);
            }
            catch (TransactionUnavailableException e)
            {
                logger.error("can't create the client transaction", e);
                throw new OperationFailedException(
                        "can't create the client transaction",
                        OperationFailedException.NETWORK_FAILURE);
            }

            try
            {
                transac.sendRequest();
            }
            catch (SipException e)
            {
                logger.error("can't send the PUBLISH request", e);
                throw new OperationFailedException(
                        "can't send the PUBLISH request",
                        OperationFailedException.NETWORK_FAILURE);
            }
        }
        // no distant presence agent, send notify to everyone
        else
        {
            String subscriptionState;
            String reason;

            if (status.equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)))
            {
                subscriptionState = SubscriptionStateHeader.TERMINATED;
                reason = SubscriptionStateHeader.PROBATION;
            }
            else
            {
                subscriptionState = SubscriptionStateHeader.ACTIVE;
                reason = null;
            }
            notifier.notifyAll(subscriptionState, reason);
        }

        // must be done in last to avoid some problem when terminating a
        // subscription of a contact who is also one of our watchers
        if (status.equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)))
        {
            unsubscribeToAllEventSubscribers();
            unsubscribeToAllContact();
        }

        // inform the listeners of these changes
        this.fireProviderStatusChangeEvent(oldStatus);
        this.fireProviderMsgStatusChangeEvent(oldMessage);
    }

    /**
     * Notifies all registered listeners of the new event.
     *
     * @param oldValue the presence status we were in before the change.
     */
    public void fireProviderMsgStatusChangeEvent(String oldValue)
    {
        fireProviderStatusMessageChangeEvent(oldValue, this.statusMessage);
    }

    /**
     * Create a valid PUBLISH request corresponding to the current presence
     * state. The request is forged to be send to the current distant presence
     * agent.
     *
     * @param expires the expires value to send
     * @param insertPresDoc if a presence document has to be added (typically
     * = false when refreshing a publication)
     *
     * @return a valid <tt>Request</tt> containing the PUBLISH
     *
     * @throws OperationFailedException if something goes wrong
     */
    private Request createPublish(int expires, boolean insertPresDoc)
        throws OperationFailedException
    {
        // Call ID
        CallIdHeader callIdHeader = this.parentProvider
            .getDefaultJainSipProvider().getNewCallId();

        // FromHeader and ToHeader
        String localTag = SipMessageFactory.generateLocalTag();
        FromHeader fromHeader = null;
        ToHeader toHeader = null;
        try
        {
            //the publish method can only be used if we have a presence agent
            //so we deliberately use our AOR and do not use the
            //getOurSipAddress() method.
            Address ourAOR = parentProvider.getRegistrarConnection()
                                                    .getAddressOfRecord();
            //FromHeader
            fromHeader = this.parentProvider.getHeaderFactory()
                .createFromHeader(ourAOR,
                                  localTag);

            //ToHeader (it's ourselves)
            toHeader = this.parentProvider.getHeaderFactory()
                .createToHeader(ourAOR, null);
        }
        catch (ParseException ex)
        {
            //these two should never happen.
            logger.error(
                "An unexpected error occurred while"
                + "constructing the FromHeader or ToHeader", ex);
            throw new OperationFailedException(
                "An unexpected error occurred while"
                + "constructing the FromHeader or ToHeader",
                OperationFailedException.INTERNAL_ERROR,
                ex);
        }

        //ViaHeaders
        ArrayList<ViaHeader> viaHeaders = parentProvider.getLocalViaHeaders(
            toHeader.getAddress());

        //MaxForwards
        MaxForwardsHeader maxForwards = this.parentProvider
            .getMaxForwardsHeader();

        // Content params
        byte[] doc = null;

        if (insertPresDoc)
        {
            //this is a publish request so we would use the default
            //getLocalContact that would return a method based on the registrar
            //address
            doc
                = getPidfPresenceStatus(
                    getLocalContactForDst(toHeader.getAddress()));
        }
        else
        {
            doc = new byte[0];
        }

        ContentTypeHeader contTypeHeader;
        try
        {
            contTypeHeader = this.parentProvider.getHeaderFactory()
                .createContentTypeHeader("application",
                                         PIDF_XML);
        }
        catch (ParseException ex)
        {
            //these two should never happen.
            logger.error(
                "An unexpected error occurred while"
                + "constructing the content headers", ex);
            throw new OperationFailedException(
                "An unexpected error occurred while"
                + "constructing the content headers"
                , OperationFailedException.INTERNAL_ERROR
                , ex);
        }

        // eventually add the entity tag
        SIPIfMatchHeader ifmHeader = null;
        try
        {
            if (this.distantPAET != null)
            {
                ifmHeader = this.parentProvider.getHeaderFactory()
                    .createSIPIfMatchHeader(this.distantPAET);
            }
        }
        catch (ParseException e)
        {
            logger.error(
                "An unexpected error occurred while"
                + "constructing the SIPIfMatch header", e);
            throw new OperationFailedException(
                "An unexpected error occurred while"
                + "constructing the SIPIfMatch header",
                OperationFailedException.INTERNAL_ERROR,
                e);
        }

        //CSeq
        CSeqHeader cSeqHeader = null;
        try
        {
            cSeqHeader = this.parentProvider.getHeaderFactory()
                .createCSeqHeader(publish_cseq++, Request.PUBLISH);
        }
        catch (InvalidArgumentException ex)
        {
            //Shouldn't happen
            logger.error(
                "An unexpected error occurred while"
                + "constructing the CSeqHeader", ex);
            throw new OperationFailedException(
                "An unexpected error occurred while"
                + "constructing the CSeqHeader"
                , OperationFailedException.INTERNAL_ERROR
                , ex);
        }
        catch (ParseException ex)
        {
            //shouldn't happen
            logger.error(
                "An unexpected error occurred while"
                + "constructing the CSeqHeader", ex);
            throw new OperationFailedException(
                "An unexpected error occurred while"
                + "constructing the CSeqHeader"
                , OperationFailedException.INTERNAL_ERROR
                , ex);
        }

        // expires
        ExpiresHeader expHeader = null;
        try
        {
            expHeader = this.parentProvider.getHeaderFactory()
                .createExpiresHeader(expires);
        }
        catch (InvalidArgumentException e)
        {
            // will never happen
            logger.error(
                    "An unexpected error occurred while"
                    + "constructing the Expires header", e);
            throw new OperationFailedException(
                    "An unexpected error occurred while"
                    + "constructing the Expires header"
                    , OperationFailedException.INTERNAL_ERROR
                    , e);
        }

        // event
        EventHeader evtHeader = null;
        try
        {
            evtHeader = this.parentProvider.getHeaderFactory()
                .createEventHeader("presence");
        }
        catch (ParseException e)
        {
            // will never happen
            logger.error(
                    "An unexpected error occurred while"
                    + "constructing the Event header", e);
            throw new OperationFailedException(
                    "An unexpected error occurred while"
                    + "constructing the Event header"
                    , OperationFailedException.INTERNAL_ERROR
                    , e);
        }

        Request req = null;
        try
        {
            req = this.parentProvider.getMessageFactory().createRequest(
                toHeader.getAddress().getURI(), Request.PUBLISH, callIdHeader,
                cSeqHeader, fromHeader, toHeader, viaHeaders, maxForwards,
                contTypeHeader, doc);
        }
        catch (ParseException ex)
        {
            //shouldn't happen
            logger.error(
                "Failed to create message Request!", ex);
            throw new OperationFailedException(
                "Failed to create message Request!"
                , OperationFailedException.INTERNAL_ERROR
                , ex);
        }

        req.setHeader(expHeader);
        req.setHeader(evtHeader);

        if (ifmHeader != null)
        {
            req.setHeader(ifmHeader);
        }

        return req;
    }

    /**
     * Returns the set of PresenceStatus objects that a user of this service
     * may request the provider to enter. Note that the provider would most
     * probably enter more states than those returned by this method as they
     * only depict instances that users may request to enter. (e.g. a user
     * may not request a "Connecting..." state - it is a temporary state
     * that the provider enters while trying to enter the "Connected" state).
     *
     * @return Iterator a PresenceStatus array containing "enterable"
     * status instances.
     */
    public Iterator<PresenceStatus> getSupportedStatusSet()
    {
        return sipStatusEnum.getSupportedStatusSet();
    }

    /**
     * Get the PresenceStatus for a particular contact.
     *
     * @param contactIdentifier the identifier of the contact whose status
     *   we're interested in.
     * @return PresenceStatus the <tt>PresenceStatus</tt> of the specified
     *   <tt>contact</tt>
     * @throws IllegalArgumentException if <tt>contact</tt> is not a contact
     *   known to the underlying protocol provider
     * @throws IllegalStateException if the underlying protocol provider is
     *   not registered/signed on a public service.
     * @throws OperationFailedException with code NETWORK_FAILURE if
     *   retrieving the status fails due to errors experienced during
     *   network communication
     */
    public PresenceStatus queryContactStatus(String contactIdentifier)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        Contact contact = resolveContactID(contactIdentifier);

        if (contact == null)
            throw
                new IllegalArgumentException(
                        "contact " + contactIdentifier + " unknown");

        return contact.getPresenceStatus();
    }

    /**
     * Adds a subscription for the presence status of the contact
     * corresponding to the specified contactIdentifier.
     *
     * @param contactIdentifier the identifier of the contact whose status
     *   updates we are subscribing for. <p>
     * @throws IllegalArgumentException if <tt>contact</tt> is not a contact
     *   known to the underlying protocol provider
     * @throws IllegalStateException if the underlying protocol provider is
     *   not registered/signed on a public service.
     * @throws OperationFailedException with code NETWORK_FAILURE if
     *   subscribing fails due to errors experienced during network
     *   communication
     */
    public void subscribe(String contactIdentifier)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        subscribe(this.ssContactList.getRootGroup(), contactIdentifier);
    }

    /**
     * Persistently adds a subscription for the presence status of the
     * contact corresponding to the specified contactIdentifier and indicates
     * that it should be added to the specified group of the server stored
     * contact list.
     *
     * @param parentGroup the parent group of the server stored contact list
     *   where the contact should be added. <p>
     * @param contactIdentifier the contact whose status updates we are
     *   subscribing for.
     * @throws IllegalArgumentException if <tt>contact</tt> or
     *   <tt>parent</tt> are not a contact known to the underlying protocol
     *   provider.
     * @throws IllegalStateException if the underlying protocol provider is
     *   not registered/signed on a public service.
     * @throws OperationFailedException with code NETWORK_FAILURE if
     *   subscribing fails due to errors experienced during network
     *   communication
     */
    public void subscribe(ContactGroup parentGroup, String contactIdentifier)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        this.subscribe(parentGroup, contactIdentifier, null);
    }

    /**
     * Persistently adds a subscription for the presence status of the
     * contact corresponding to the specified contactIdentifier and indicates
     * that it should be added to the specified group of the server stored
     * contact list.
     *
     * @param parentGroup the parent group of the server stored contact list
     *   where the contact should be added. <p>
     * @param contactIdentifier the contact whose status updates we are
     *   subscribing for.
     * @param contactType the contact type to create, if missing null.
     * @throws IllegalArgumentException if <tt>contact</tt> or
     *   <tt>parent</tt> are not a contact known to the underlying protocol
     *   provider.
     * @throws IllegalStateException if the underlying protocol provider is
     *   not registered/signed on a public service.
     * @throws OperationFailedException with code NETWORK_FAILURE if
     *   subscribing fails due to errors experienced during network
     *   communication
     */
    void subscribe(ContactGroup parentGroup, String contactIdentifier,
                         String contactType)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        assertConnected();

        if (!(parentGroup instanceof ContactGroupSipImpl))
        {
            String errorMessage = String.format(
                    "Group %1s does not seem to belong to this protocol's " +
                            "contact list",
                    parentGroup.getGroupName());
            throw new IllegalArgumentException(errorMessage);
        }
        //if the contact is already in the contact list
        ContactSipImpl contact = resolveContactID(contactIdentifier);

        if (contact != null)
        {
            if(contact.isPersistent())
            {
                throw new OperationFailedException(
                    "Contact " + contactIdentifier + " already exists.",
                    OperationFailedException.SUBSCRIPTION_ALREADY_EXISTS);
            }
            else
            {
                // we will remove it as we will created again
                // this is the case when making a non persistent contact to
                // a persistent one
                ssContactList.removeContact(contact);
            }
        }
        contact = ssContactList.createContact((ContactGroupSipImpl) parentGroup,
                contactIdentifier, true, contactType);
        if (this.presenceEnabled)
        {
            subscriber.subscribe(new PresenceSubscriberSubscription(contact));
        }
    }

    /**
     * Utility method throwing an exception if the stack is not properly
     * initialized.
     * @throws java.lang.IllegalStateException if the underlying stack is
     * not registered and initialized.
     */
    private void assertConnected()
        throws IllegalStateException
    {
        if (this.parentProvider == null)
            throw new IllegalStateException(
                "The provider must be non-null and signed on the "
                + "service before being able to communicate.");
        if (!this.parentProvider.isRegistered())
            throw new IllegalStateException(
                "The provider must be signed on the service before "
                + "being able to communicate.");
    }

    /**
     * Removes a subscription for the presence status of the specified contact.
     * @param contact the contact whose status updates we are unsubscribing
     * from.
     *
     * @throws OperationFailedException with code NETWORK_FAILURE if
     * unsubscribing fails due to errors experienced during network
     * communication
     * @throws IllegalArgumentException if <tt>contact</tt> is not a contact
     * known to the underlying protocol provider
     * @throws IllegalStateException if the underlying protocol provider is not
     * registered/signed on a public service.
     */
    public void unsubscribe(Contact contact)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        assertConnected();

        if (!(contact instanceof ContactSipImpl))
        {
            throw new IllegalArgumentException("The contact is not a SIP " +
                    "contact");
        }
        ContactSipImpl sipContact = (ContactSipImpl) contact;
        /**
         * Does not assert if there is no subscription cause if the user
         * becomes offline he has terminated the subscription and so we have
         * no subscription of this contact but we wont to remove it.
         * Does not assert on connected cause have already has made the check.
         */
        unsubscribe(sipContact, false);
        ssContactList.removeContact(sipContact);
    }

    /**
     * Removes a subscription for the presence status of the specified contact
     * and optionally asserts that the specified contact has an existing
     * subscription prior to attempting the unregistration.
     *
     * @param sipcontact
     *            the contact whose status updates we are unsubscribing from.
     * @param assertConnectedAndSubscribed
     *            <tt>true</tt> to assert that the specified contact has an
     *            existing subscription prior to attempting the unregistration;
     *            <tt>false</tt> to not perform the respective checks
     * @throws OperationFailedException
     *             with code NETWORK_FAILURE if unsubscribing fails due to
     *             errors experienced during network communication
     * @throws IllegalArgumentException
     *             if <tt>contact</tt> is not a contact known to the underlying
     *             protocol provider
     * @throws IllegalStateException
     *             if the underlying protocol provider is not registered/signed
     *             on a public service.
     */
    private void unsubscribe(
            ContactSipImpl sipcontact,
            boolean assertConnectedAndSubscribed)
        throws IllegalArgumentException,
               IllegalStateException,
               OperationFailedException
    {
        // handle the case of a distant presence agent is used
        // and test if we are subscribed to this contact
        if (this.presenceEnabled && sipcontact.isResolvable())
        {
            if (assertConnectedAndSubscribed)
                assertConnected();

            subscriber
                .unsubscribe(
                    getAddress(sipcontact),
                    assertConnectedAndSubscribed);
        }

        // remove any trace of this contact
        terminateSubscription(sipcontact);
    }

    /**
     * Analyzes the incoming <tt>responseEvent</tt> and then forwards it to the
     * proper event handler.
     *
     * @param responseEvent the responseEvent that we received
     *            ProtocolProviderService.
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processResponse(ResponseEvent responseEvent)
    {
        if (this.presenceEnabled == false)
            return false;

        ClientTransaction clientTransaction = responseEvent
            .getClientTransaction();
        Response response = responseEvent.getResponse();

        CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
        if (cseq == null)
        {
            logger.error("An incoming response did not contain a CSeq header");
            return false;
        }
        String method = cseq.getMethod();

        boolean processed = false;

        // PUBLISH
        if (method.equals(Request.PUBLISH))
        {
            // if it's a final response to a PUBLISH, we try to remove it from
            // the list of waited PUBLISH end
            if (response.getStatusCode() != Response.UNAUTHORIZED
                && response.getStatusCode() != Response
                    .PROXY_AUTHENTICATION_REQUIRED
                && response.getStatusCode() != Response.INTERVAL_TOO_BRIEF)
            {
                synchronized (this.waitedCallIds)
                {
                    this.waitedCallIds.remove(((CallIdHeader) response
                        .getHeader(CallIdHeader.NAME)).getCallId());
                }
            }

            // OK (200)
            if (response.getStatusCode() == Response.OK)
            {
                // remember the entity tag
                SIPETagHeader etHeader = (SIPETagHeader)
                    response.getHeader(SIPETagHeader.NAME);

                // must be one (rfc3903)
                if (etHeader == null)
                {
                    if (logger.isDebugEnabled())
                        logger.debug("can't find the ETag header");
                    return false;
                }

                this.distantPAET = etHeader.getETag();

                // schedule a re-publish task
                ExpiresHeader expires = (ExpiresHeader)
                    response.getHeader(ExpiresHeader.NAME);

                if (expires == null)
                {
                    logger.error("no Expires header in the response");
                    return false;
                }

                // if it's a response to an unpublish request (Expires: 0),
                // invalidate the etag and don't schedule a republish
                if (expires.getExpires() == 0)
                {
                    this.distantPAET = null;
                    return true;
                }

                // just to be sure to not have two refreshing task
                if (this.republishTask != null)
                    this.republishTask.cancel();

                this.republishTask = new RePublishTask();

                int republishDelay = expires.getExpires();
                // try to keep a margin if the refresh delay allows it
                if (republishDelay >= (2*REFRESH_MARGIN))
                    republishDelay -= REFRESH_MARGIN;
                timer.schedule(this.republishTask, republishDelay * 1000);

            // UNAUTHORIZED (401/407)
            }
            else if (response.getStatusCode() == Response.UNAUTHORIZED
                    || response.getStatusCode() == Response
                        .PROXY_AUTHENTICATION_REQUIRED)
            {
                try
                {
                    processAuthenticationChallenge(
                        clientTransaction,
                        response,
                        (SipProvider) responseEvent.getSource());
                }
                catch (OperationFailedException e)
                {
                    logger.error("can't handle the challenge", e);
                    return false;
                }
            // INTERVAL TOO BRIEF (423)
            }
            else if (response.getStatusCode() == Response.INTERVAL_TOO_BRIEF)
            {
                // we get the Min expires and we use it as the interval
                MinExpiresHeader min = (MinExpiresHeader)
                    response.getHeader(MinExpiresHeader.NAME);

                if (min == null)
                {
                    logger.error("can't find a min expires header in the 423" +
                            " error message");
                    return false;
                }

                // send a new publish with the new expires value
                Request req = null;
                try
                {
                    req = createPublish(min.getExpires(), true);
                }
                catch (OperationFailedException e)
                {
                    logger.error("can't create the new publish request", e);
                    return false;
                }

                ClientTransaction transac = null;
                try
                {
                    transac = this.parentProvider
                        .getDefaultJainSipProvider()
                        .getNewClientTransaction(req);
                }
                catch (TransactionUnavailableException e)
                {
                    logger.error("can't create the client transaction", e);
                    return false;
                }

                try
                {
                    transac.sendRequest();
                }
                catch (SipException e)
                {
                    logger.error("can't send the PUBLISH request", e);
                    return false;
                }

            // CONDITIONAL REQUEST FAILED (412)
            }
            else if (response.getStatusCode() == Response
                                                .CONDITIONAL_REQUEST_FAILED)
            {
                // as recommanded in rfc3903#5, we start a totally new
                // publication
                this.distantPAET = null;
                Request req = null;
                try
                {
                    req = createPublish(this.subscriptionDuration, true);
                }
                catch (OperationFailedException e)
                {
                    logger.error("can't create the new publish request", e);
                    return false;
                }

                ClientTransaction transac = null;
                try
                {
                    transac = this.parentProvider
                        .getDefaultJainSipProvider()
                        .getNewClientTransaction(req);
                }
                catch (TransactionUnavailableException e)
                {
                    logger.error("can't create the client transaction", e);
                    return false;
                }

                try
                {
                    transac.sendRequest();
                }
                catch (SipException e)
                {
                    logger.error("can't send the PUBLISH request", e);
                    return false;
                }
            }
            // PROVISIONAL RESPONSE (1XX)
            else if (response.getStatusCode() >= 100
                    && response.getStatusCode() < 200)
            {
                // Ignore provisional response: simply wait for a next response
                // with a SUCCESS (2XX) code.
            }
            // with every other error, we consider that we have to start a new
            // communication.
            // Enter p2p mode if the distant PA mode fails
            else
            {
                if (logger.isDebugEnabled())
                    logger.debug("error received from the network" + response);

                this.distantPAET = null;

                if (this.useDistantPA)
                {
                    if (logger.isDebugEnabled())
                        logger.debug(
                                "we enter into the peer-to-peer mode"
                                + " as the distant PA mode fails");

                    setUseDistantPA(false);

                    // if we are here, we don't have any watcher so no need to
                    // republish our presence state
                }
            }

            processed = true;
        }

        return processed;
    }

    /**
     * Finalize the subscription of a contact and transform the pending contact
     * into a real contact.
     *
     * @param contact the contact concerned
     *
     * @throws NullPointerException if contact is null
     */
    private void finalizeSubscription(ContactSipImpl contact)
        throws NullPointerException
    {
        // remember the dialog created to be able to send SUBSCRIBE
        // refresh and to unsubscribe
        if (contact == null)
            throw new NullPointerException("contact");

        contact.setResolved(true);

        // inform the listeners that the contact is created
        this.fireSubscriptionEvent(
                contact,
                contact.getParentContactGroup(),
                SubscriptionEvent.SUBSCRIPTION_RESOLVED);

        if (logger.isDebugEnabled())
            logger.debug("contact " + contact + " resolved");
    }

    /**
     * Terminate the subscription to a contact presence status
     *
     * @param contact the contact concerned
     */
    private void terminateSubscription(ContactSipImpl contact)
    {
        if (contact == null)
        {
            logger.error("null contact provided, can't terminate" +
                    " subscription");
            return;
        }

        // we don't remove the contact
        changePresenceStatusForContact(
            contact,
            sipStatusEnum.getStatus(SipStatusEnum.UNKNOWN));
        contact.setResolved(false);
    }

    /**
     * Process a request from a distant contact
     *
     * @param requestEvent the <tt>RequestEvent</tt> containing the newly
     *            received request.
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processRequest(RequestEvent requestEvent)
    {
        if (this.presenceEnabled == false)
            return false;

        Request request = requestEvent.getRequest();
        EventHeader eventHeader
            = (EventHeader) request.getHeader(EventHeader.NAME);

        if (eventHeader == null)
        {
            /*
             * We are not concerned by this request, perhaps another listener
             * is. So don't send a 489 / Bad event response here.
             */
            return false;
        }

        String eventType = eventHeader.getEventType();

        if (!"presence".equalsIgnoreCase(eventType)
                && !"presence.winfo".equalsIgnoreCase(eventType))
            return false;

        String requestMethod = request.getMethod();
        boolean processed = false;

        // presence PUBLISH and presence.winfo SUBSCRIBE
        if (("presence".equalsIgnoreCase(eventType)
                        && Request.PUBLISH.equals(requestMethod))
                || ("presence.winfo".equalsIgnoreCase(eventType)
                        && Request.SUBSCRIBE.equals(requestMethod)))
        {
            /*
             * We aren't supposed to receive a PUBLISH so just say "not
             * implemented". This behavior is useful for SC to SC communication
             * with the PA auto detection feature and a server which proxy the
             * PUBLISH requests.
             *
             * We support presence.winfo only as a subscriber, not as a
             * notifier. So say "not implemented" in order to not have its
             * ServerTransaction remaining in the SIP stack forever.
             */
            processed
                = EventPackageSupport.sendNotImplementedResponse(
                        parentProvider,
                        requestEvent);
        }

        return processed;
    }

    /**
     * Called when a dialog is terminated
     *
     * @param dialogTerminatedEvent DialogTerminatedEvent
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processDialogTerminated(
            DialogTerminatedEvent dialogTerminatedEvent)
    {
        // never fired
        return false;
    }

    /**
     * Called when an IO error occurs
     *
     * @param exceptionEvent IOExceptionEvent
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processIOException(IOExceptionEvent exceptionEvent)
    {
        // never fired
        return false;
    }

    /**
     * Called when a transaction is terminated
     *
     * @param transactionTerminatedEvent TransactionTerminatedEvent
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processTransactionTerminated(
        TransactionTerminatedEvent transactionTerminatedEvent)
    {
        // nothing to do
        return false;
    }

    /**
     * Called when a timeout occur
     *
     * @param timeoutEvent TimeoutEvent
     * @return <tt>true</tt> if the specified event has been handled by this
     *         processor and shouldn't be offered to other processors registered
     *         for the same method; <tt>false</tt>, otherwise
     */
    public boolean processTimeout(TimeoutEvent timeoutEvent)
    {
        logger.error("timeout reached, it looks really abnormal: " +
                timeoutEvent.toString());
        return false;
    }

    /**
     * Attempts to re-generate the corresponding request with the proper
     * credentials.
     *
     * @param clientTransaction
     *            the corresponding transaction
     * @param response
     *            the challenge
     * @param jainSipProvider
     *            the provider that received the challenge
     * @throws OperationFailedException
     *             if processing the authentication challenge fails.
     */
    private void processAuthenticationChallenge(
            ClientTransaction clientTransaction,
            Response response,
            SipProvider jainSipProvider)
        throws OperationFailedException
    {
        EventPackageSupport.processAuthenticationChallenge(
            parentProvider,
            clientTransaction,
            response,
            jainSipProvider);
    }

    /**
     * Sets the presence status of <tt>contact</tt> to <tt>newStatus</tt>.
     *
     * @param contact the <tt>ContactSipImpl</tt> whose status we'd like
     * to set.
     * @param newStatus the new status we'd like to set to <tt>contact</tt>.
     */
    private void changePresenceStatusForContact(
        ContactSipImpl contact,
        PresenceStatus newStatus)
    {
        PresenceStatus oldStatus = contact.getPresenceStatus();

        contact.setPresenceStatus(newStatus);
        fireContactPresenceStatusChangeEvent(
                contact, contact.getParentContactGroup(), oldStatus);
    }

    /**
     * Returns a <code>ContactSipImpl</code> with a specific ID in case we have
     * a subscription for it and <tt>null<tt> otherwise.
     *
     * @param contactID
     *            a String identifier of the contact which is to be retrieved
     * @return the <code>ContactSipImpl</code> with the specified
     *         <code>contactID</code> or <tt>null</tt> if we don't have a
     *         subscription for the specified identifier
     */
    public ContactSipImpl findContactByID(String contactID)
    {
        return this.ssContactList.getRootGroup().findContactByID(contactID);
    }

    /**
     * Returns the protocol specific contact instance representing the local
     * user.
     *
     * @param destination the destination that we would be sending our contact
     * information to.
     *
     * @return a ContactSipImpl instance that represents us.
     */
    public ContactSipImpl getLocalContactForDst(ContactSipImpl destination)
    {
        return getLocalContactForDst(destination.getSipAddress());
    }

    /**
     * Returns the protocol specific contact instance representing the local
     * user.
     *
     * @param destination the destination that we would be sending our contact
     * information to.
     *
     * @return a ContactSipImpl instance that represents us.
     */
    public ContactSipImpl getLocalContactForDst(Address destination)
    {
        Address sipAddress = parentProvider.getOurSipAddress(destination);
        ContactSipImpl res
            = new ContactSipImpl(sipAddress, this.parentProvider);

        res.setPresenceStatus(this.presenceStatus);
        return res;
    }

    /**
     * Handler for incoming authorization requests.
     *
     * @param handler an instance of an AuthorizationHandler for
     *   authorization requests coming from other users requesting
     *   permission add us to their contact list.
     */
    public void setAuthorizationHandler(AuthorizationHandler handler)
    {
        this.authorizationHandler = handler;
    }

    /**
     * Returns the status message that was confirmed by the server
     *
     * @return the last status message that we have requested and the server
     * has confirmed.
     */
    public String getCurrentStatusMessage()
    {
        return this.statusMessage;
    }

    /**
     * Creates and returns a unresolved contact from the specified
     * <tt>address</tt> and <tt>persistentData</tt>. The method will not try
     * to establish a network connection and resolve the newly created Contact
     * against the server. The protocol provider may will later try and resolve
     * the contact. When this happens the corresponding event would notify
     * interested subscription listeners.
     *
     * @param address an identifier of the contact that we'll be creating.
     * @param persistentData a String returned Contact's getPersistentData()
     * method during a previous run and that has been persistently stored
     * locally.
     *
     * @return the unresolved <tt>Contact</tt> created from the specified
     * <tt>address</tt> and <tt>persistentData</tt>
     */
    public Contact createUnresolvedContact(
        String address, String persistentData)
    {
        return createUnresolvedContact(address
                , persistentData
                , getServerStoredContactListRoot());
    }

    /**
    * Creates and returns a unresolved contact from the specified
    * <tt>address</tt> and <tt>persistentData</tt>. The method will not try
    * to establish a network connection and resolve the newly created Contact
    * against the server. The protocol provider may will later try and resolve
    * the contact. When this happens the corresponding event would notify
    * interested subscription listeners.
    *
    * @param contactId an identifier of the contact that we'll be creating.
    * @param persistentData a String returned Contact's getPersistentData()
    * method during a previous run and that has been persistently stored
    * locally.
    * @param parent the group where the unresolved contact is
    * supposed to belong to.
    *
    * @return the unresolved <tt>Contact</tt> created from the specified
    * <tt>address</tt> and <tt>persistentData</tt>
    */
    public Contact createUnresolvedContact(String contactId,
                         String persistentData,
                         ContactGroup parent)
    {
        return ssContactList.createUnresolvedContact((ContactGroupSipImpl)
                parent, contactId, persistentData);
    }

    /**
     * Creates a non persistent contact for the specified address. This would
     * also create (if necessary) a group for volatile contacts that would not
     * be added to the server stored contact list. This method would have no
     * effect on the server stored contact list.
     *
     * @param contactAddress the address of the volatile contact we'd like to
     * create.
     * @param displayName the Display Name of the volatile contact we'd like to
     * create.
     * @return the newly created volatile contact.
     */
    public ContactSipImpl createVolatileContact(String contactAddress,
                                                String displayName)
    {
        try
        {
            // Check whether a volatile group already exists and if not create one
            ContactGroupSipImpl volatileGroup = getNonPersistentGroup();
            // if the parent volatile group is null then we create it
            if (volatileGroup == null)
            {
                ContactGroupSipImpl rootGroup =
                        this.ssContactList.getRootGroup();
                volatileGroup = ssContactList
                        .createGroup(rootGroup,
                            SipActivator.getResources().getI18NString(
                                "service.gui.NOT_IN_CONTACT_LIST_GROUP_NAME"),
                            false);
            }

            if (displayName != null)
                return ssContactList.createContact( volatileGroup,
                                                    contactAddress,
                                                    displayName,
                                                    false, null);
            else
                return ssContactList.createContact( volatileGroup,
                                                    contactAddress,
                                                    false, null);
        }
        catch (OperationFailedException ex)
        {
            return null;
        }
    }

    /**
     * Creates a non persistent contact for the specified address. This would
     * also create (if necessary) a group for volatile contacts that would not
     * be added to the server stored contact list. This method would have no
     * effect on the server stored contact list.
     *
     * @param contactAddress the address of the volatile contact we'd like to
     * create.
     *
     * @return the newly created volatile contact.
     */
    public ContactSipImpl createVolatileContact(String contactAddress)
    {
        return createVolatileContact(contactAddress, null);
    }

    /**
     * Returns the volatile group or null if this group has not yet been
     * created.
     *
     * @return a volatile group existing in our contact list or <tt>null</tt>
     * if such a group has not yet been created.
     */
    private ContactGroupSipImpl getNonPersistentGroup()
    {
        for (int i = 0;
             i < getServerStoredContactListRoot().countSubgroups();
             i++)
        {
            ContactGroupSipImpl gr = (ContactGroupSipImpl)
                getServerStoredContactListRoot().getGroup(i);

            if(!gr.isPersistent())
            {
                return gr;
            }
        }

        return null;
    }

    /**
     * Tries to find a <code>ContactSipImpl</code> which is identified either by
     * a specific <code>contactID</code> or by a derivation of it.
     *
     * @param contactID
     *            the identifier of the <code>ContactSipImpl</code> to retrieve
     *            either by directly using it or by deriving it
     * @return a <code>ContactSipImpl</code> which is identified either by the
     *         specified <code>contactID</code> or by a derivation of it
     */
    ContactSipImpl resolveContactID(String contactID)
    {
        ContactSipImpl res = findContactByID(contactID);

        if (res == null)
        {
            // we try to resolve the conflict by removing "sip:" from the id
            if (contactID.startsWith("sip:"))
                res = findContactByID(contactID.substring(4));

            if (res == null)
            {
                int domainBeginIndex = contactID.indexOf('@');

                // we try to remove the part after the '@'
                if (domainBeginIndex > -1)
                {
                    res
                        = findContactByID(
                            contactID.substring(0, domainBeginIndex));

                    // try the same thing without sip:
                    if ((res == null) && contactID.startsWith("sip:"))
                        res
                            = findContactByID(
                                contactID.substring(4, domainBeginIndex));
                }

                if (res == null)
                {
                    // sip:user_name@ip_address:5060;transport=udp
                    int domainEndIndex = contactID.indexOf(":", 4);

                    // if port is absent try removing the params after ;
                    if (domainEndIndex < 0)
                        domainEndIndex = contactID.indexOf(";", 4);

                    if (domainEndIndex > -1)
                        res
                            = findContactByID(
                                contactID.substring(4, domainEndIndex));
                }
            }
        }
        return res;
    }

    /**
     * Returns a new valid xml document.
     *
     * @return a correct xml document or null if an error occurs
     */
    Document createDocument()
    {
        try
        {
            return XMLUtils.createDocument();
        }
        catch (Exception e)
        {
            logger.error("Can't create xml document", e);
            return null;
        }
    }

    /**
     * Convert a xml document
     *
     * @param document the document to convert
     *
     * @return a string representing <tt>document</tt> or null if an error
     * occur
     */
    String convertDocument(Document document)
    {
        try
        {
            return XMLUtils.createXml(document);
        }
        catch (Exception e)
        {
            logger.error("Can't convert the xml document into a string", e);
            return null;
        }
    }

    /**
     * Convert a xml document
     *
     * @param document the document as a String
     *
     * @return a <tt>Document</tt> representing the document or null if an
     * error occur
     */
    Document convertDocument(String document)
    {
        try
        {
            return XMLUtils.createDocument(document);
        }
        catch (Exception e)
        {
            logger.error("Can't convert the string into a xml document", e);
            return null;
        }
    }

    /**
     * Converts the <tt>PresenceStatus</tt> of <tt>contact</tt> into a PIDF
     * document.
     *
     * @param contact The contact which interest us
     *
     * @return a PIDF document representing the current presence status of
     * this contact or null if an error occurs.
     */
     public byte[] getPidfPresenceStatus(ContactSipImpl contact)
     {
         Document doc = this.createDocument();

         if (doc == null)
             return null;

         String contactUri = contact.getSipAddress().getURI().toString();

         // <presence>
         Element presence = doc.createElement(PRESENCE_ELEMENT);
         presence.setAttribute(NS_ELEMENT, PIDF_NS_VALUE);
         presence.setAttribute(RPID_NS_ELEMENT, RPID_NS_VALUE);
         presence.setAttribute(DM_NS_ELEMENT, DM_NS_VALUE);
         presence.setAttribute(ENTITY_ATTRIBUTE, contactUri);
         doc.appendChild(presence);

         // <person>
         Element person = doc.createElement(NS_PERSON_ELT);
         person.setAttribute(ID_ATTRIBUTE, PERSON_ID);
         presence.appendChild(person);

         // <activities>
         Element activities = doc.createElement(NS_ACTIVITY_ELT);
         person.appendChild(activities);

         // <status-icon>
         URI imageUri = ssContactList.getImageUri();
         if(imageUri != null)
         {
             Element statusIcon = doc.createElement(NS_STATUS_ICON_ELT);
             statusIcon.setTextContent(imageUri.toString());
             person.appendChild(statusIcon);
         }

         // the correct activity
         if (contact.getPresenceStatus()
                         .equals(sipStatusEnum.getStatus(SipStatusEnum.AWAY)))
         {
             Element away = doc.createElement(NS_AWAY_ELT);
             activities.appendChild(away);
         }
         else if (contact.getPresenceStatus()
                         .equals(sipStatusEnum.getStatus(SipStatusEnum.BUSY)))
         {
             Element busy = doc.createElement(NS_BUSY_ELT);
             activities.appendChild(busy);
         }
         else if (contact.getPresenceStatus()
                 .equals(sipStatusEnum.getStatus(SipStatusEnum.ON_THE_PHONE)))
         {
             Element otp = doc.createElement(NS_OTP_ELT);
             activities.appendChild(otp);
         }

         // <tuple>
         Element tuple = doc.createElement(TUPLE_ELEMENT);
         tuple.setAttribute(ID_ATTRIBUTE, TUPLE_ID);
         presence.appendChild(tuple);

         // <status>
         Element status = doc.createElement(STATUS_ELEMENT);
         tuple.appendChild(status);

         // <basic>
         Element basic = doc.createElement(BASIC_ELEMENT);
         if (contact.getPresenceStatus()
                     .equals(sipStatusEnum.getStatus(SipStatusEnum.OFFLINE)))
         {
             basic.appendChild(doc.createTextNode(OFFLINE_STATUS));
         }
         else
         {
             basic.appendChild(doc.createTextNode(ONLINE_STATUS));
         }
         status.appendChild(basic);

         // <contact>
         Element contactUriEl = doc.createElement(CONTACT_ELEMENT);
         Node cValue = doc.createTextNode(contactUri);
         contactUriEl.appendChild(cValue);
         tuple.appendChild(contactUriEl);

         // <note> we write our real status here, this status SHOULD not be
         // used for automatic parsing but some (bad) IM clients do this...
         // we don't use xml:lang here because it's not really relevant
         Element noteNodeEl = doc.createElement(NOTE_ELEMENT);
         noteNodeEl.appendChild(doc.createTextNode(contact.getPresenceStatus()
                 .getStatusName()));
         tuple.appendChild(noteNodeEl);

         String res = convertDocument(doc);
         if (res == null)
             return null;

         return res.getBytes();
     }

     /**
      * Sets the contact's presence status using the PIDF document provided.
      * In case of conflict (more than one status per contact) the last valid
      * status in the document is used.
      * This implementation is very tolerant to be more compatible with bad
      * implementations of SIMPLE. The limit of the tolerance is defined by
      * the CPU cost: as far as the tolerance costs nothing more in well
      * structured documents, we do it.
      *
      * @param presenceDoc the pidf document to use
      */
     public void setPidfPresenceStatus(String presenceDoc)
     {
         Document doc = convertDocument(presenceDoc);

         if (doc == null)
             return;

         if (logger.isDebugEnabled())
             logger.debug("parsing:\n" + presenceDoc);

         // <presence>
         NodeList presList = doc.getElementsByTagNameNS(PIDF_NS_VALUE,
                 PRESENCE_ELEMENT);

         if (presList.getLength() == 0)
         {
             presList = doc.getElementsByTagNameNS(ANY_NS, PRESENCE_ELEMENT);

             if (presList.getLength() == 0)
             {
                 logger.error("no presence element in this document");
                 return;
             }
         }
         if (presList.getLength() > 1)
         {
             logger.warn("more than one presence element in this document");
         }
         Node presNode = presList.item(0);
         if (presNode.getNodeType() != Node.ELEMENT_NODE)
         {
             logger.error("the presence node is not an element");
             return;
         }
         Element presence = (Element) presNode;

         // RPID area

         // due to a lot of changes in the past years to this functionality,
         // the namespace used by servers and clients are often wrong so we just
         // ignore namespaces here

         PresenceStatus personStatus = null;
         URI personStatusIcon = null;
         NodeList personList = presence.getElementsByTagNameNS(ANY_NS,
                 PERSON_ELEMENT);

         //if (personList.getLength() > 1) {
         //    logger.error("more than one person in this document");
         //    return;
         //}

         if (personList.getLength() > 0)
         {
             Node personNode = personList.item(0);
             if (personNode.getNodeType() != Node.ELEMENT_NODE)
             {
                 logger.error("the person node is not an element");
                 return;
             }
             Element person = (Element) personNode;

             NodeList activityList =
                 person.getElementsByTagNameNS(ANY_NS, ACTIVITY_ELEMENT);
             if (activityList.getLength() > 0)
             {
                 Element activity = null;
                 // find the first correct activity
                 for (int i = 0; i < activityList.getLength(); i++)
                 {
                     Node activityNode = activityList.item(i);

                     if (activityNode.getNodeType() != Node.ELEMENT_NODE)
                         continue;

                     activity = (Element) activityNode;

                     NodeList statusList = activity.getChildNodes();
                     for (int j = 0; j < statusList.getLength(); j++)
                     {
                         Node statusNode = statusList.item(j);
                         if (statusNode.getNodeType() == Node.ELEMENT_NODE)
                         {
                             String statusname = statusNode.getLocalName();
                             if (statusname.equals(AWAY_ELEMENT))
                             {
                                 personStatus = sipStatusEnum
                                     .getStatus(SipStatusEnum.AWAY);
                                 break;
                             }
                             else if (statusname.equals(BUSY_ELEMENT))
                             {
                                 personStatus = sipStatusEnum
                                     .getStatus(SipStatusEnum.BUSY);
                                 break;
                             }
                             else if (statusname.equals(OTP_ELEMENT))
                             {
                                 personStatus = sipStatusEnum
                                     .getStatus(SipStatusEnum.ON_THE_PHONE);
                                 break;
                             }
                         }
                     }
                     if (personStatus != null)
                         break;
                 }
             }
             NodeList statusIconList = person.getElementsByTagNameNS(ANY_NS,
                     STATUS_ICON_ELEMENT);
             if (statusIconList.getLength() > 0)
             {
                 Element statusIcon;
                 Node statusIconNode = statusIconList.item(0);
                 if (statusIconNode.getNodeType() == Node.ELEMENT_NODE)
                 {
                     statusIcon = (Element) statusIconNode;
                     String content = getTextContent(statusIcon);
                     if (content != null && content.trim().length() != 0)
                     {
                         try
                         {
                             personStatusIcon = URI.create(content);
                         }
                         catch (IllegalArgumentException ex)
                         {
                             logger.error("Person's status icon uri: " +
                                     content + " is invalid");
                         }
                     }
                 }
             }
         }

          if(personStatusIcon != null)
          {
              String contactID =
                  XMLUtils.getAttribute(presNode, ENTITY_ATTRIBUTE);

              if (contactID.startsWith("pres:"))
              {
                  contactID = contactID.substring("pres:".length());
              }
              Contact contact = resolveContactID(contactID);
              updateContactIcon((ContactSipImpl) contact, personStatusIcon);
         }

         // Vector containing the list of status to set for each contact in
         // the presence document ordered by priority (highest first).
         // <SipContact, Float (priority), SipStatusEnum>
         List<Object[]> newPresenceStates = new Vector<Object[]>(3, 2);

         // <tuple>
         NodeList tupleList = getPidfChilds(presence, TUPLE_ELEMENT);
         for (int i = 0; i < tupleList.getLength(); i++)
         {
             Node tupleNode = tupleList.item(i);

             if (tupleNode.getNodeType() != Node.ELEMENT_NODE)
                 continue;

             Element tuple = (Element) tupleNode;

             // <contact>
             NodeList contactList = getPidfChilds(tuple, CONTACT_ELEMENT);

             // we use a vector here and not an unique contact to handle an
             // error case where many contacts are associated with a status
             // Vector<ContactSipImpl>
             List<Object[]> sipcontact = new Vector<Object[]>(1, 3);
             String contactID = null;
             if (contactList.getLength() == 0)
             {
                 // use the entity attribute of the presence node
                 contactID = XMLUtils.getAttribute(
                         presNode, ENTITY_ATTRIBUTE);
                 // also accept entity URIs starting with pres: instead of sip:
                 if (contactID.startsWith("pres:"))
                 {
                     contactID = contactID.substring("pres:".length());
                 }
                 Contact tmpContact = resolveContactID(contactID);

                 if (tmpContact != null)
                 {
                     sipcontact.add(new Object[] { tmpContact, new Float(0f) });
                 }
             }
             else
             {
                 // this is normally not permitted by RFC3863
                 for (int j = 0; j < contactList.getLength(); j++)
                 {
                     Node contactNode = contactList.item(j);

                     if (contactNode.getNodeType() != Node.ELEMENT_NODE)
                         continue;

                     Element contact = (Element) contactNode;

                     contactID = getTextContent(contact);
                     // also accept entity URIs starting with pres: instead
                     // of sip:
                     if (contactID.startsWith("pres:"))
                     {
                         contactID = contactID.substring("pres:".length());
                     }
                     Contact tmpContact = resolveContactID(contactID);
                     if (tmpContact == null)
                         continue;

                     // defines an array containing the contact and its
                     // priority
                     Object tab[] = new Object[2];

                     // search if the contact has a priority
                     String prioStr = contact.getAttribute(PRIORITY_ATTRIBUTE);
                     Float prio = null;
                     try
                     {
                         if (prioStr == null || prioStr.length() == 0)
                         {
                             prio = new Float(0f);
                         }
                         else
                         {
                             prio = Float.valueOf(prioStr);
                         }
                     }
                     catch (NumberFormatException e)
                     {
                         if (logger.isDebugEnabled())
                             logger.debug("contact priority is not a valid float",
                                     e);
                         prio = new Float(0f);
                     }

                     // 0 <= priority <= 1 according to rfc
                     if (prio.floatValue() < 0)
                     {
                         prio = new Float(0f);
                     }

                     if (prio.floatValue() > 1)
                     {
                         prio = new Float(1f);
                     }

                     tab[0] = tmpContact;
                     tab[1] = prio;

                     // search if the contact hasn't already been added
                     boolean contactAlreadyListed = false;
                     for (int k = 0; k < sipcontact.size(); k++)
                     {
                         Object[] tmp = sipcontact.get(k);

                         if (tmp[0].equals(tmpContact))
                         {
                             contactAlreadyListed = true;

                             // take the highest priority
                             if (((Float) tmp[1]).floatValue() <
                                     prio.floatValue())
                             {
                                 sipcontact.remove(k);
                                 sipcontact.add(tab);
                             }
                             break;
                         }
                     }

                     // add the contact and its priority to the list
                     if (!contactAlreadyListed)
                     {
                         sipcontact.add(tab);
                     }
                 }
             }

             if (sipcontact.isEmpty())
             {
                 if (logger.isDebugEnabled())
                     logger.debug("no contact found for id: " + contactID);
                 continue;
             }

             // <status>
             NodeList statusList = getPidfChilds(tuple, STATUS_ELEMENT);

             // in case of many status, just consider the last one
             // this is normally not permitted by RFC3863
             int index = statusList.getLength() - 1;
             Node statusNode = null;
             do
             {
                 Node temp = statusList.item(index);
                 if (temp.getNodeType() == Node.ELEMENT_NODE)
                 {
                     statusNode = temp;
                     break;
                 }
                 index--;
             }
             while (index >= 0);

             Element basic = null;

             if (statusNode == null)
             {
                 if (logger.isDebugEnabled())
                     logger.debug("no valid status in this tuple");
             }
             else
             {
                 Element status = (Element) statusNode;

                 // <basic>
                 NodeList basicList = getPidfChilds(status, BASIC_ELEMENT);

                 // in case of many basic, just consider the last one
                 // this is normally not permitted by RFC3863
                 index = basicList.getLength() - 1;
                 Node basicNode = null;
                 do
                 {
                     Node temp = basicList.item(index);
                     if (temp.getNodeType() == Node.ELEMENT_NODE)
                     {
                         basicNode = temp;
                         break;
                     }
                     index--;
                 }
                 while (index >= 0);

                 if (basicNode == null)
                 {
                     if (logger.isDebugEnabled())
                         logger.debug("no valid <basic> in this status");
                 }
                 else
                 {
                     basic = (Element) basicNode;
                 }
             }

             // search for a <note> that can define a more precise
             // status this is not recommended by RFC3863 but some im
             // clients use this.
             NodeList noteList = getPidfChilds(tuple, NOTE_ELEMENT);

             boolean changed = false;
             for (int k = 0; k < noteList.getLength() && !changed; k++)
             {
                 Node noteNode = noteList.item(k);

                 if (noteNode.getNodeType() != Node.ELEMENT_NODE)
                     continue;

                 Element note = (Element) noteNode;

                 String state = getTextContent(note);

                 Iterator<PresenceStatus> states
                     = sipStatusEnum.getSupportedStatusSet();
                 while (states.hasNext())
                 {
                     PresenceStatus current = states.next();

                     if (current.getStatusName().equalsIgnoreCase(state))
                     {
                         changed = true;
                         newPresenceStates = setStatusForContacts(current,
                                 sipcontact,
                                 newPresenceStates);
                         break;
                     }
                 }
             }

             if (changed == false && basic != null)
             {
                 if (getTextContent(basic).equalsIgnoreCase(ONLINE_STATUS))
                 {
                     // if its online(open) we use the person status
                     // if any, otherwise just mark as online
                     if(personStatus != null)
                     {
                         newPresenceStates = setStatusForContacts(
                                 personStatus,
                                 sipcontact,
                                 newPresenceStates);
                     }
                     else
                     {
                         newPresenceStates = setStatusForContacts(
                                 sipStatusEnum.getStatus(SipStatusEnum.ONLINE),
                                 sipcontact,
                                 newPresenceStates);
                     }
                 }
                 else if (getTextContent(basic).equalsIgnoreCase(
                         OFFLINE_STATUS))
                 {
                     // if its offline we ignore person status
                     newPresenceStates = setStatusForContacts(
                             sipStatusEnum.getStatus(SipStatusEnum.OFFLINE),
                             sipcontact,
                             newPresenceStates);
                 }
             }
             else
             {
                 if (changed == false)
                 {
                     if (logger.isDebugEnabled())
                         logger.debug("no suitable presence state found in this "
                                 + "tuple");
                 }
             }
         } // for each <tuple>

         // Now really set the new presence status for the listed contacts
         // newPresenceStates is ordered so priority order is respected
         for (Object[] tab : newPresenceStates)
         {
             ContactSipImpl contact = (ContactSipImpl) tab[0];
             PresenceStatus status = (PresenceStatus) tab[2];

             changePresenceStatusForContact(contact, status);
         }
     }

    /**
     * Parses watchers info document rfc3858.
     * @param watcherInfoDoc the doc.
     * @param subscriber the subscriber which receives lists.
     */
    public void setWatcherInfoStatus(
            WatcherInfoSubscriberSubscription subscriber,
            String watcherInfoDoc)
    {
        if(this.authorizationHandler == null)
        {
            logger.warn("AuthorizationHandler missing!");
            return;
        }

        Document doc = convertDocument(watcherInfoDoc);

         if (doc == null)
             return;

         if (logger.isDebugEnabled())
             logger.debug("parsing:\n" + watcherInfoDoc);

        // <watcherinfo>
        NodeList watchList = doc.getElementsByTagNameNS(
                WATCHERINFO_NS_VALUE, WATCHERINFO_ELEMENT);
        if (watchList.getLength() == 0)
        {
            watchList = doc.getElementsByTagNameNS(
                     ANY_NS, WATCHERINFO_ELEMENT);

            if (watchList.getLength() == 0)
            {
                logger.error("no watcherinfo element in this document");
                return;
            }
        }
        if (watchList.getLength() > 1)
        {
            logger.warn("more than one watcherinfo element in this document");
        }
        Node watcherInfoNode = watchList.item(0);
        if (watcherInfoNode.getNodeType() != Node.ELEMENT_NODE)
        {
            logger.error("the watcherinfo node is not an element");
            return;
        }

        Element watcherInfo = (Element)watcherInfoNode;

        // we don't take in account whether the state is full or partial.
        if(logger.isDebugEnabled())
            logger.debug("Watcherinfo is with state: "
                    + watcherInfo.getAttribute(STATE_ATTRIBUTE));

        int currentVersion = -1;
        try
        {
            currentVersion =
                Integer.parseInt(watcherInfo.getAttribute(VERSION_ATTRIBUTE));
        }
        catch(Throwable t)
        {
            logger.error("Cannot parse version!", t);
        }

        if(currentVersion != -1 && currentVersion <= subscriber.version)
        {
            logger.warn("Document version is old, ignore it.");
            return;
        }
        else
            subscriber.version = currentVersion;

        // we need watcher list only for our resource
        Element wlist = XMLUtils.locateElement(
                watcherInfo, WATCHERLIST_ELEMENT, RESOURCE_ATTRIBUTE,
                parentProvider.getRegistrarConnection()
                    .getAddressOfRecord().getURI().toString());

        if(wlist == null ||
            !wlist.getAttribute(PACKAGE_ATTRIBUTE).equals(PRESENCE_ELEMENT))
        {
            logger.error("Watcher list for us is missing in this document!");
            return;
        }

        NodeList watcherList = wlist.getElementsByTagNameNS(ANY_NS,
                 WATCHER_ELEMENT);
        for(int i = 0; i < watcherList.getLength(); i++)
        {
            Node watcherNode = watcherList.item(i);
            if (watcherNode.getNodeType() != Node.ELEMENT_NODE)
            {
                logger.error("the watcher node is not an element");
                return;
            }

            Element watcher = (Element)watcherNode;

            String status = watcher.getAttribute(STATUS_ELEMENT);
            String contactID = getTextContent(watcher);

            //String event - subscribe, approved, deactivated, probation,
            //rejected, timeout, giveup, noresource

            if(status == null || contactID == null)
            {
                logger.warn("Status or contactID missing for watcher!");
                continue;
            }

            if(status.equals("waiting") || status.equals("pending"))
            {
                ContactSipImpl contact = resolveContactID(contactID);

                if(contact != null)
                {
                    logger.warn("We are not supposed to have this contact in our " +
                            "list or its just rerequest of authorization!");

                    // if we have this contact in the list
                    // means we have this request already and have shown
                    // dialog to user so skip further processing
                    return;
                }
                else
                {
                    contact = createVolatileContact(contactID);
                }

                AuthorizationRequest req = new AuthorizationRequest();
                AuthorizationResponse response = authorizationHandler
                        .processAuthorisationRequest(req, contact);

                if(response.getResponseCode() == AuthorizationResponse.ACCEPT)
                {
                    ssContactList.authorizationAccepted(contact);
                }
                else if(response.getResponseCode()
                            == AuthorizationResponse.REJECT)
                {
                    ssContactList.authorizationRejected(contact);
                }
                else if(response.getResponseCode()
                            == AuthorizationResponse.IGNORE)
                {
                    ssContactList.authorizationIgnored(contact);
                }
            }
        }
    }

     /**
      * Checks whether to URIs are equal with safe null check.
      * @param uri1 to be compared.
      * @param uri2 to be compared.
      * @return if uri1 is equal to uri2.
      */
    public static boolean isEquals(URI uri1, URI uri2) {
        return (uri1 == null && uri2 == null)
            || (uri1 != null && uri1.equals(uri2));
    }

    /**
     * Changes the Contact image
     * @param contact
     * @param imageUri
     */
    private void updateContactIcon(ContactSipImpl contact, URI imageUri)
    {
        if(isEquals(contact.getImageUri(), imageUri) || imageUri == null)
        {
            return;
        }
        byte[] oldImage = contact.getImage();
        byte[] newImage = ssContactList.getImage(imageUri);

        if(oldImage == null && newImage == null)
            return;

        contact.setImageUri(imageUri);
        contact.setImage(newImage);
        fireContactPropertyChangeEvent(
                ContactPropertyChangeEvent.PROPERTY_IMAGE,
                contact,
                oldImage,
                newImage);
    }

     /**
      * Secured call to XMLUtils.getText (no null returned but an empty string)
      *
      * @param node the node with which call <tt>XMLUtils.getText()</tt>
      *
      * @return the string contained in the node or an empty string if there is
      * no text information in the node.
      */
     private String getTextContent(Element node)
     {
         String res = XMLUtils.getText(node);

         if (res == null)
         {
             logger.warn("no text for element '" + node.getNodeName() + "'");
             return "";
         }

         return res;
     }

     /**
      * Gets the list of the descendant of an element in the pidf namespace.
      * If the list is empty, we try to get this list in any namespace.
      * This method is useful for being able to read pidf document without any
      * namespace or with a wrong namespace.
      *
      * @param element the base element concerned.
      * @param childName the name of the descendants to match on.
      *
      * @return The list of all the descendant node.
      */
     private NodeList getPidfChilds(Element element, String childName)
     {
         NodeList res;

         res = element.getElementsByTagNameNS(PIDF_NS_VALUE, childName);

         if (res.getLength() == 0)
         {
             res = element.getElementsByTagNameNS(ANY_NS, childName);
         }

         return res;
     }

     /**
      * Associate the provided presence state to the contacts considering the
      * current presence states and priorities.
      *
      * @param presenceState The presence state to associate to the contacts
      * @param contacts A list of <contact, priority> concerned by the
      *  presence status.
      * @param curStatus The list of the current presence status ordered by
      *  priority (highest priority first).
      *
      * @return a Vector containing a list of <contact, priority, status>
      *  ordered by priority (highest first). Null if a parameter is null.
      */
     private List<Object[]> setStatusForContacts(
         PresenceStatus presenceState,
         Iterable<Object[]> contacts,
         List<Object[]> curStatus)
     {
         // test parameters
         if (presenceState == null || contacts == null || curStatus == null)
             return null;

         // for each contact in the list
         for (Object[] tab : contacts)
         {
             Contact contact = (Contact) tab[0];
             float priority = ((Float) tab[1]).floatValue();

             // for each existing contact
             int pos = 0;
             boolean skip = false;
             for (int i = 0; i < curStatus.size(); i++)
             {
                 Object tab2[] = curStatus.get(i);
                 Contact curContact = (Contact) tab2[0];
                 float curPriority = ((Float) tab2[1]).floatValue();

                 // save the place where to add this contact in the list
                 if (pos == 0 && curPriority <= priority)
                 {
                     pos = i;
                 }

                 if (curContact.equals(contact))
                 {
                     // same contact but with an higher priority
                     // simply ignore this new status affectation
                     if (curPriority > priority)
                     {
                         skip = true;
                         break;
                     // same contact but with a lower priority
                     // replace the old status with this one
                     }
                     else if (curPriority < priority)
                     {
                         curStatus.remove(i);
                     // same contact and same priority
                     // consider the reachability of the status
                     }
                     else
                     {
                         PresenceStatus curPresence = (PresenceStatus) tab2[2];
                         if (curPresence.getStatus() >=
                             presenceState.getStatus())
                         {
                             skip = true;
                             break;
                         }

                         curStatus.remove(i);
                     }

                     i--;

                 }
             }

             if (skip)
                 continue;

             // insert the new entry
             curStatus.add(
                 pos,
                 new Object[] { contact, new Float(priority), presenceState });
         }

         return curStatus;
     }

     /**
      * Forces the poll of a contact to update its current state.
      *
      * @param contact the contact to poll
      */
     public void forcePollContact(ContactSipImpl contact)
     {
         if (this.presenceEnabled == false
             || !contact.isResolvable()
             || !contact.isPersistent())
             return;

         // Attempt to subscribe.
         try
         {
             subscriber.poll(new PresenceSubscriberSubscription(contact));
         }
         catch (OperationFailedException ex)
         {
             logger.error("Failed to create and send the subcription", ex);
         }
     }

    /**
     * Unsubscribe to every contact.
     */
    public void unsubscribeToAllContact()
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("Trying to unsubscribe to every contact");
        }
        // Send event notifications saying that all our buddies are offline.
        for (ContactSipImpl contact : ssContactList
                .getUniqueContacts(ssContactList.getRootGroup()))
        {
            try
            {
                unsubscribe(contact, false);
            }
            catch (Throwable ex)
            {
                logger.error("Failed to unsubscribe to contact " + contact, ex);
            }
        }
    }

    /**
     * Unsubscribe to every event we have subscribes, as it is done normally
     * on exit or logout do it silently if it fails.
     */
    private void unsubscribeToAllEventSubscribers()
    {
        if(this.watcherInfoSubscriber != null)
        {
            try
            {
                watcherInfoSubscriber.unsubscribe(
                    parentProvider.getRegistrarConnection()
                        .getAddressOfRecord(), false);
            }
            catch (Throwable ex)
            {
                logger.error("Failed to send the unsubscription " +
                        "for watcher info.", ex);
            }
        }
    }

    /**
     * Sets the display name for <tt>contact</tt> to be <tt>newName</tt>.
     * <p>
     * @param contact the <tt>Contact</tt> that we are renaming
     * @param newName a <tt>String</tt> containing the new display name for
     * <tt>metaContact</tt>.
     * @throws IllegalArgumentException if <tt>contact</tt> is not an
     * instance that belongs to the underlying implementation.
     */
    @Override
    public void setDisplayName(Contact contact, String newName)
        throws IllegalArgumentException
    {
        assertConnected();

        if (!(contact instanceof ContactSipImpl))
        {
            throw new IllegalArgumentException("The contact is not a SIP " +
                    "contact");
        }

        ssContactList.renameContact((ContactSipImpl) contact, newName);
    }

    /**
     * Return current server-stored contact list implementation.
     * @return current server-stored contact list implementation.
     */
    protected ServerStoredContactList getSsContactList()
    {
        return ssContactList;
    }

     /**
      * Cancels the timer which handles all scheduled tasks and disposes of the
      * currently existing tasks scheduled with it.
      */
     private void cancelTimer()
     {

         /*
          * The timer is being canceled so the tasks schedules with it are being
          * made obsolete.
          */
         if (republishTask != null)
             republishTask = null;
         if (pollingTask != null)
             pollingTask = null;

         timer.cancel();
     }

     /**
      * A <tt>TimerTask</tt> handling refresh of PUBLISH requests.
      */
     private class RePublishTask extends TimerTask
     {
         /**
          * Send a new PUBLISH request to refresh the publication
          */
         @Override
        public void run()
         {
             Request req = null;
             try
             {
                 if (distantPAET != null)
                 {
                     req = createPublish(subscriptionDuration, false);
                 }
                 else
                 {
                     // if the last publication failed for any reason, send a
                     // new publication, not a refresh
                     req = createPublish(subscriptionDuration, true);
                 }
             }
             catch (OperationFailedException e)
             {
                 logger.error("can't create a new PUBLISH message", e);
                 return;
             }

             ClientTransaction transac = null;
             try
             {
                 transac = parentProvider
                     .getDefaultJainSipProvider().getNewClientTransaction(req);
             }
             catch (TransactionUnavailableException e)
             {
                 logger.error("can't create the client transaction", e);
                 return;
             }

             try
             {
                 transac.sendRequest();
             }
             catch (SipException e)
             {
                 logger.error("can't send the PUBLISH request", e);
                 return;
             }
         }
     }

     /**
      * A task handling polling of offline contacts.
      */
     private class PollOfflineContactsTask extends TimerTask
     {
         /**
          * Check if we can't subscribe to this contact now
          */
         @Override
        public void run()
         {
             // send a subscription for every contact
             Iterator<Contact> rootContactsIter
                = getServerStoredContactListRoot().contacts();

            while (rootContactsIter.hasNext())
            {
                ContactSipImpl contact =
                    (ContactSipImpl) rootContactsIter.next();

                 // poll this contact
                 forcePollContact(contact);
             }

             Iterator<ContactGroup> groupsIter
                 = getServerStoredContactListRoot().subgroups();

             while (groupsIter.hasNext())
             {
                 ContactGroup group = groupsIter.next();
                 Iterator<Contact> contactsIter = group.contacts();

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

                     // poll this contact
                     forcePollContact(contact);
                 }
             }
         }
     }

     /**
     * Will wait for every SUBSCRIBE, NOTIFY and PUBLISH transaction
     * to finish before continuing the unsubscription
     */
    private void stopEvents()
    {
        for (byte i = 0; i < 10; i++)
        {
            synchronized (waitedCallIds)
            {
                if (waitedCallIds.size() == 0)
                {
                    break;
                }
            }
            synchronized (this)
            {
                try
                {
                    // Wait 5 s. max
                    wait(500);
                }
                catch (InterruptedException e)
                {
                    if (logger.isDebugEnabled())
                    {
                        logger.debug("abnormal behavior, may cause unnecessary CPU use", e);
                    }
                }
            }
        }
    }

    /**
     * The method is called by a ProtocolProvider implementation whenever
     * a change in the registration state of the corresponding provider had
     * occurred. The method is particularly interested in events stating
     * that the SIP provider has unregistered so that it would fire
     * status change events for all contacts in our buddy list.
     *
     * @param evt ProviderStatusChangeEvent the event describing the status
     *            change.
     */
    public void registrationStateChanged(RegistrationStateChangeEvent evt)
    {
        if (evt.getNewState().equals(RegistrationState.UNREGISTERING))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Enter unregistering state");
            }
            // Stop any task associated with the timer
            cancelTimer();
            // Destroy XCAP contacts
            ssContactList.destroy();
            // This will not be called by anyone else, so call it the method
            // will terminate every active subscription
            try
            {
                publishPresenceStatus(
                        sipStatusEnum.getStatus(SipStatusEnum.OFFLINE), "");
            }
            catch (OperationFailedException e)
            {
                logger.error("can't set the offline mode", e);
            }
            stopEvents();
        }
        else if (evt.getNewState().equals(RegistrationState.REGISTERED))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("enter registered state");
            }
            // Init XCAP contacts
            ssContactList.init();
            /*
            * If presence support is enabled and the keep-alive method
            * is REGISTER, we'll get RegistrationState.REGISTERED more
            * than one though we're already registered. If we're
            * receiving such subsequent REGISTERED, we don't have to do
            * anything because we've already set it up in response to
            * the first REGISTERED.
            */
            if ((!presenceEnabled) || (pollingTask != null))
            {
                return;
            }

            // Subcribe to each contact in the list
            for (ContactSipImpl contact : ssContactList
                    .getAllContacts(ssContactList.getRootGroup()))
            {
                forcePollContact(contact);
            }

            // create the new polling task
            pollingTask = new PollOfflineContactsTask();

            // start polling the offline contacts
            timer.schedule(pollingTask, pollingTaskPeriod, pollingTaskPeriod);

            if(this.useDistantPA)
            {
                try
                {
                    watcherInfoSubscriber.subscribe(
                        new WatcherInfoSubscriberSubscription(
                            parentProvider.getRegistrarConnection()
                                .getAddressOfRecord()));
                }
                catch (OperationFailedException ex)
                {
                    logger.error("Failed to create and send the subcription " +
                            "for watcher info.", ex);
                }
            }
        }
        else if (evt.getNewState().equals(RegistrationState.CONNECTION_FAILED)
            || evt.getNewState().equals(
                        RegistrationState.AUTHENTICATION_FAILED))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("Enter connction failed state");
            }
            // Destroy XCAP contacts
            ssContactList.destroy();
            // if connection failed we have lost network connectivity
            // we must fire that all contacts has gone offline
            for (ContactSipImpl contact : ssContactList
                    .getAllContacts(ssContactList.getRootGroup()))
            {
                PresenceStatus oldContactStatus
                        = contact.getPresenceStatus();
                if (subscriber != null)
                {
                    try
                    {
                        subscriber.removeSubscription(getAddress(contact));
                    }
                    catch (OperationFailedException ex)
                    {
                        if (logger.isDebugEnabled())
                        {
                            logger.debug(
                                    "Failed to remove subscription to contact "
                                            + contact);
                        }
                    }
                }
                if (!oldContactStatus.isOnline())
                {
                    continue;
                }
                contact.setPresenceStatus(
                        sipStatusEnum.getStatus(SipStatusEnum.OFFLINE));
                fireContactPresenceStatusChangeEvent(
                        contact
                        , contact.getParentContactGroup()
                        , oldContactStatus);
            }

            if(this.useDistantPA)
            {
                try
                {
                    watcherInfoSubscriber.removeSubscription(
                        parentProvider.getRegistrarConnection()
                            .getAddressOfRecord());
                }
                catch (Throwable ex)
                {
                    logger.error("Failed to remove subscription " +
                            "for watcher info.", ex);
                }
            }

            // stop any task associated with the timer
            cancelTimer();
            waitedCallIds.clear();

            // update ourself and the UI that our status is OFFLINE
            // don't call publishPresenceStatus as we are in connection failed
            // and it seems we have no connectivity and there is no sense in
            // sending packest(PUBLISH)
            PresenceStatus oldStatus = this.presenceStatus;
            this.presenceStatus = sipStatusEnum.getStatus(SipStatusEnum.OFFLINE);

            this.fireProviderStatusChangeEvent(oldStatus);
        }
    }

    /**
     * Gets the identifying address of a specific <code>ContactSipImpl</code> in
     * the form of a <code>Address</code> value.
     *
     * @param contact
     *            the <code>ContactSipImpl</code> to get the address of
     * @return a new <code>Address</code> instance representing the identifying
     *         address of the specified <code>ContactSipImpl</code>
     *
     * @throws OperationFailedException parsing this contact's address fails.
     */
    private Address getAddress(ContactSipImpl contact)
        throws OperationFailedException
    {
        try
        {
            return parentProvider.parseAddressString(contact.getAddress());
        }
        catch (ParseException ex)
        {
            //Shouldn't happen
            ProtocolProviderServiceSipImpl.throwOperationFailedException(
                "An unexpected error occurred while constructing the address",
                OperationFailedException.INTERNAL_ERROR, ex, logger);
            return null;//unreachable but necessary.
        }
    }

    /**
     * Frees allocated resources.
     */
    void shutdown()
    {
        parentProvider.removeRegistrationStateChangeListener(this);
    }

    /**
     * Represents a subscription of a specific <code>ContactSipImpl</code> to
     * our presence event package.
     *
     * @author Lubomir Marinov
     */
    private class PresenceNotifierSubscription
        extends EventPackageNotifier.Subscription
    {

        /**
         * The <code>ContactSipImpl</code> which is the subscriber this
         * subscription notifies.
         */
        private final ContactSipImpl contact;

        /**
         * Initializes a new <code>PresenceNotifierSubscription</code> instance
         * which is to represent a subscription of a <code>ContactSipImpl</code>
         * specified by <code>Address</code> to our presence event package.
         *
         * @param fromAddress
         *            the <code>Address</code> of the
         *            <code>ContactSipImpl</code> subscribed to our presence
         *            event package. If no <code>ContactSipImpl</code> with the
         *            specified <code>Address</code> exists in our contact list,
         *            a new one will be created.
         * @param eventId
         *            the value of the id tag to be placed in the Event headers
         *            of the NOTIFY requests created for the new instance and to
         *            be present in the received Event headers in order to have
         *            the new instance associated with them
         */
        public PresenceNotifierSubscription(Address fromAddress, String eventId)
        {
            super(fromAddress, eventId);

            // if we received a subscribe, our network probably doesn't have
            // a distant PA
            setUseDistantPA(false);

            // try to find which contact is concerned
            ContactSipImpl contact
                = resolveContactID(fromAddress.getURI().toString());

            // if we don't know him, create him
            if (contact == null)
            {
                contact = new ContactSipImpl(fromAddress, parentProvider);

                // <tricky time>
                // this ensure that we will publish our status to this contact
                // without trying to subscribe to him
                contact.setResolved(true);
                contact.setResolvable(false);
                // </tricky time>
            }

            if (logger.isDebugEnabled())
                    logger.debug(contact + " wants to watch your presence status");

            this.contact = contact;
        }

        /**
         * Determines whether the <tt>Address</tt>/Request URI of this
         * <tt>Subscription</tt> is equal to a specific <tt>Address</tt> in the
         * sense of identifying one and the same resource.
         *
         * @param address the <tt>Address</tt> to be checked for value equality
         * to the <tt>Address</tt>/Request URI of this <tt>Subscription</tt>
         * @return <tt>true</tt> if the <tt>Address</tt>/Request URI of this
         * <tt>Subscription</tt> is equal to the specified <tt>Address</tt> in
         * the sense of identifying one and the same resource
         * @see EventPackageSupport.Subscription#addressEquals(Address)
         */
        @Override
        protected boolean addressEquals(Address address)
        {
            String addressString = address.getURI().toString();
            String id1 = addressString;
            // without sip:
            String id2 = addressString.substring(4);
            int domainBeginIndex = addressString.indexOf('@');
            // without the domain
            String id3 = addressString.substring(0, domainBeginIndex);
            // without sip: and the domain
            String id4 = addressString.substring(4, domainBeginIndex);

            String contactAddressString = contact.getAddress();

            // test by order of probability to be true will probably save 1ms :)
            return
                contactAddressString.equals(id2)
                    || contactAddressString.equals(id1)
                    || contactAddressString.equals(id4)
                    || contactAddressString.equals(id3);
        }

        /**
         * Creates content for a notify request using the specified
         * <tt>subscriptionState</tt> and <tt>reason</tt> string.
         *
         * @param subscriptionState the state that we'd like to deliver in the
         * newly created <tt>Notify</tt> request.
         * @param reason the reason string that  we'd like to deliver in the
         * newly created <tt>Notify</tt> request.
         *
         * @return the String bytes of the newly created content.
         */
        @Override
        protected byte[] createNotifyContent(String subscriptionState,
                        String reason)
        {
            return getPidfPresenceStatus(getLocalContactForDst(contact));
        }
    }

    /**
     * Represents a subscription to the presence event package of a specific
     * <code>ContactSipImpl</code>.
     *
     * @author Lubomir Marinov
     */
    private class PresenceSubscriberSubscription
        extends EventPackageSubscriber.Subscription
    {

        /**
         * The <code>ContactSipImpl</code> which is the notifier this
         * subscription is subscribed to.
         */
        private final ContactSipImpl contact;

        /**
         * Initializes a new <code>PresenceSubscriberSubscription</code>
         * instance which is to represent a subscription to the presence event
         * package of a specific <code>ContactSipImpl</code>.
         *
         * @param contact the <code>ContactSipImpl</code> which is the notifier
         * the new subscription is to subscribed to
         *
         * @throws OperationFailedException if we fail extracting
         * <tt>contact</tt>'s address.
         */
        public PresenceSubscriberSubscription(ContactSipImpl contact)
            throws OperationFailedException
        {
            super(OperationSetPresenceSipImpl.this.getAddress(contact));

            this.contact = contact;
        }

        /*
         * Implements
         * EventPackageSubscriber.Subscription#processActiveRequest(RequestEvent
         * , byte[]).
         */
        @Override
        protected void processActiveRequest(
            RequestEvent requestEvent,
            byte[] rawContent)
        {
            if (rawContent != null)
                setPidfPresenceStatus(new String(rawContent));

            SubscriptionStateHeader stateHeader =
                (SubscriptionStateHeader)requestEvent.getRequest()
                        .getHeader(SubscriptionStateHeader.NAME);

            if(stateHeader != null)
            {
                if(SubscriptionStateHeader.PENDING
                        .equals(stateHeader.getState()))
                {
                    contact.setSubscriptionState(
                            SubscriptionStateHeader.PENDING);
                }
                else if(SubscriptionStateHeader.ACTIVE
                        .equals(stateHeader.getState()))
                {
                    // if contact was in pending state
                    // our authorization request was accepted
                    if(SubscriptionStateHeader.PENDING
                            .equals(contact.getSubscriptionState())
                       && authorizationHandler != null)
                    {
                        authorizationHandler.processAuthorizationResponse(
                                new AuthorizationResponse(
                                        AuthorizationResponse.ACCEPT, ""),
                                contact);
                    }
                    contact.setSubscriptionState(
                            SubscriptionStateHeader.ACTIVE);
                }
            }
        }

        /*
         * Implements
         * EventPackageSubscriber.Subscription#processFailureResponse(
         * ResponseEvent, int).
         */
        @Override
        protected void processFailureResponse(
            ResponseEvent responseEvent,
            int statusCode)
        {
            // we probably won't be able to communicate with the contact
            changePresenceStatusForContact(
                contact, sipStatusEnum.getStatus(
                    (Response.TEMPORARILY_UNAVAILABLE == statusCode)
                        ? SipStatusEnum.OFFLINE
                        : SipStatusEnum.UNKNOWN));

            // we'll never be able to resolve this contact
            if ((Response.UNAUTHORIZED != statusCode)
                    && (Response.PROXY_AUTHENTICATION_REQUIRED != statusCode))
                contact.setResolvable(false);
        }

        /*
         * Implements
         * EventPackageSubscriber.Subscription#processSuccessResponse(
         * ResponseEvent, int).
         */
        @Override
        protected void processSuccessResponse(
            ResponseEvent responseEvent,
            int statusCode)
        {
            switch (statusCode)
            {
            case Response.OK:
            case Response.ACCEPTED:
                try
                {
                    if (!contact.isResolved())
                    {
                        // if contact is not in the contact list
                        // create it, and add to parent, later will be resolved
                        if(resolveContactID(contact.getAddress()) == null)
                        {
                            ContactGroup parentGroup =
                                contact.getParentContactGroup();
                            ((ContactGroupSipImpl) parentGroup)
                                .addContact(contact);

                            // pretend that the contact is created
                            fireSubscriptionEvent(
                                contact,
                                parentGroup,
                                SubscriptionEvent.SUBSCRIPTION_CREATED);
                        }

                        finalizeSubscription(contact);
                    }
                }
                catch (NullPointerException e)
                {
                    // should not happen
                    if (logger.isDebugEnabled())
                        logger.debug(
                                "failed to finalize the subscription of the contact",
                                e);
                }
                break;
            }
        }

        /**
         * Implements the corresponding <tt>SipListener</tt> method by
         * terminating the corresponding subscription and polling the related
         * contact.
         *
         * @param requestEvent the event containing the request that was \
         * terminated.
         * @param reasonCode a String indicating the reason of the termination.
         */
        @Override
        protected void processTerminatedRequest(
                            RequestEvent requestEvent, String reasonCode)
        {
            terminateSubscription(contact);

            // if the reason is "de-activated" we remove the contact
            // as he unsubscribed, we won't bother him with subscribe requests
            if (SubscriptionStateHeader.DEACTIVATED.equals(reasonCode))
                try
                {
                    ssContactList.removeContact(contact);
                }
                catch(OperationFailedException e)
                {
                    logger.error(
                            "Cannot remove contact that unsubscribed.", e);
                }

            SubscriptionStateHeader stateHeader =
                (SubscriptionStateHeader)requestEvent.getRequest()
                        .getHeader(SubscriptionStateHeader.NAME);

            if(stateHeader != null
                && SubscriptionStateHeader.TERMINATED
                    .equals(stateHeader.getState()))
            {
                if(SubscriptionStateHeader.REJECTED
                        .equals(stateHeader.getReasonCode()))
                {
                    if(SubscriptionStateHeader.PENDING
                        .equals(contact.getSubscriptionState()))
                    {
                        authorizationHandler.processAuthorizationResponse(
                            new AuthorizationResponse(
                                AuthorizationResponse.REJECT, ""),
                                contact);
                    }

                    // as this contact is rejected we mark it as not resolvable
                    // so we won't subscribe again (in offline poll task)
                    contact.setResolvable(false);
                }

                contact.setSubscriptionState(
                        SubscriptionStateHeader.TERMINATED);
            }
        }
    }

    /**
     * Represents a subscription to the presence.winfo event package.
     *
     * @author Damian Minkov
     */
    private class WatcherInfoSubscriberSubscription
        extends EventPackageSubscriber.Subscription
    {
        private int version = -1;

        /**
         * Initializes a new <tt>Subscription</tt> instance with a specific
         * subscription <tt>Address</tt>/Request URI and an id tag of the
         * associated Event headers of value <tt>null</tt>.
         *
         * @param toAddress the subscription <tt>Address</tt>/Request URI which
         * is to be the target of the SUBSCRIBE requests associated with
         * the new instance
         */
        public WatcherInfoSubscriberSubscription(Address toAddress)
        {
            super(toAddress);
        }


        /**
         * Notifies this <tt>Subscription</tt> that an active NOTIFY
         * <tt>Request</tt> has been received and it may process the
         * specified raw content carried in it.
         *
         * @param requestEvent the <tt>RequestEvent</tt> carrying the full
         * details of the received NOTIFY <tt>Request</tt> including the raw
         * content which may be processed by this <tt>Subscription</tt>
         * @param rawContent   an array of bytes which represents the raw
         * content carried in the body of the received NOTIFY <tt>Request</tt>
         * and extracted from the specified <tt>RequestEvent</tt>
         * for the convenience of the implementers
         */
        @Override
        protected void processActiveRequest(
                RequestEvent requestEvent, byte[] rawContent)
        {
            if (rawContent != null)
                setWatcherInfoStatus(this, new String(rawContent));
        }

        /**
         * Notifies this <tt>Subscription</tt> that a <tt>Response</tt>
         * to a previous SUBSCRIBE <tt>Request</tt> has been received with a
         * status code in the failure range and it may process the status code
         * carried in it.
         *
         * @param responseEvent the <tt>ResponseEvent</tt> carrying the
         * full details of the received <tt>Response</tt> including the status
         * code which may be processed by this <tt>Subscription</tt>
         * @param statusCode the status code carried in the <tt>Response</tt>
         * and extracted from the specified <tt>ResponseEvent</tt>
         * for the convenience of the implementers
         */
        @Override
        protected void processFailureResponse(
                ResponseEvent responseEvent, int statusCode)
        {
            if(logger.isDebugEnabled())
                logger.debug("Cannot subscripe to presence watcher info!");
        }

        /**
         * Notifies this <tt>Subscription</tt> that a <tt>Response</tt>
         * to a previous SUBSCRIBE <tt>Request</tt> has been received with a
         * status code in the success range and it may process the status code
         * carried in it.
         *
         * @param responseEvent the <tt>ResponseEvent</tt> carrying the
         * full details of the received <tt>Response</tt> including the status
         * code which may be processed by this <tt>Subscription</tt>
         * @param statusCode the status code carried in the <tt>Response</tt>
         * and extracted from the specified <tt>ResponseEvent</tt>
         * for the convenience of the implementers
         */
        @Override
        protected void processSuccessResponse(
                ResponseEvent responseEvent, int statusCode)
        {
            if(logger.isDebugEnabled())
                logger.debug("Subscriped to presence watcher info! status:"
                        + statusCode);
        }

        /**
         * Notifies this <tt>Subscription</tt> that a terminating NOTIFY
         * <tt>Request</tt> has been received and it may process the reason
         * code carried in it.
         *
         * @param requestEvent the <tt>RequestEvent</tt> carrying the
         * full details of the received NOTIFY <tt>Request</tt> including the
         * reason code which may be processed by this <tt>Subscription</tt>
         * @param reasonCode the code of the reason for the termination carried
         * in the NOTIFY <tt>Request</tt> and extracted from the specified
         * <tt>RequestEvent</tt> for the convenience of the implementers.
         */
        @Override
        protected void processTerminatedRequest(
                RequestEvent requestEvent, String reasonCode)
        {
            logger.error("Subscription to presence watcher info terminated!");
        }
    }
}