mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Nicolas Capponi
12.29.2015 407bb81fb935e713a4a1ae1b9189b81488a944d5
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
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
package org.opends.server.replication.plugin;
 
import static org.forgerock.opendj.ldap.ResultCode.*;
import static org.opends.messages.ReplicationMessages.*;
import static org.opends.messages.ToolMessages.*;
import static org.opends.server.protocols.internal.InternalClientConnection.*;
import static org.opends.server.protocols.internal.Requests.*;
import static org.opends.server.replication.plugin.EntryHistorical.*;
import static org.opends.server.replication.protocol.OperationContext.*;
import static org.opends.server.replication.service.ReplicationMonitor.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
 
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringReader;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.zip.DataFormatException;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.server.ConfigChangeResult;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DecodeException;
import org.forgerock.opendj.ldap.ModificationType;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.SearchScope;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.meta.ReplicationDomainCfgDefn.IsolationPolicy;
import org.opends.server.admin.std.server.ExternalChangelogDomainCfg;
import org.opends.server.admin.std.server.ReplicationDomainCfg;
import org.opends.server.api.AlertGenerator;
import org.opends.server.api.Backend;
import org.opends.server.api.DirectoryThread;
import org.opends.server.api.SynchronizationProvider;
import org.opends.server.api.Backend.BackendOperation;
import org.opends.server.backends.task.Task;
import org.opends.server.core.*;
import org.opends.server.protocols.internal.InternalClientConnection;
import org.opends.server.protocols.internal.InternalSearchListener;
import org.opends.server.protocols.internal.InternalSearchOperation;
import org.opends.server.protocols.internal.Requests;
import org.opends.server.protocols.internal.SearchRequest;
import org.opends.server.protocols.ldap.LDAPAttribute;
import org.opends.server.protocols.ldap.LDAPControl;
import org.opends.server.protocols.ldap.LDAPFilter;
import org.opends.server.protocols.ldap.LDAPModification;
import org.opends.server.replication.common.CSN;
import org.opends.server.replication.common.ServerState;
import org.opends.server.replication.common.ServerStatus;
import org.opends.server.replication.common.StatusMachineEvent;
import org.opends.server.replication.protocol.*;
import org.opends.server.replication.service.DSRSShutdownSync;
import org.opends.server.replication.service.ReplicationBroker;
import org.opends.server.replication.service.ReplicationDomain;
import org.opends.server.tasks.PurgeConflictsHistoricalTask;
import org.opends.server.tasks.TaskUtils;
import org.opends.server.types.*;
import org.opends.server.types.operation.*;
import org.opends.server.util.LDIFReader;
import org.opends.server.util.TimeThread;
import org.opends.server.workflowelement.localbackend.LocalBackendModifyOperation;
 
/**
 *  This class implements the bulk part of the Directory Server side
 *  of the replication code.
 *  It contains the root method for publishing a change,
 *  processing a change received from the replicationServer service,
 *  handle conflict resolution,
 *  handle protocol messages from the replicationServer.
 * <p>
 * FIXME Move this class to org.opends.server.replication.service
 * or the equivalent package once this code is moved to a maven module.
 */
public final class LDAPReplicationDomain extends ReplicationDomain
       implements ConfigurationChangeListener<ReplicationDomainCfg>,
                  AlertGenerator
{
 
  /**
   * Set of attributes that will return all the user attributes and the
   * replication related operational attributes when used in a search operation.
   */
  private static final Set<String> USER_AND_REPL_OPERATIONAL_ATTRS =
      new HashSet<String>(Arrays.asList(
          HISTORICAL_ATTRIBUTE_NAME, ENTRYUUID_ATTRIBUTE_NAME, "*"));
 
  /**
   * This class is used in the session establishment phase
   * when no Replication Server with all the local changes has been found
   * and we therefore need to recover them.
   * A search is then performed on the database using this
   * internalSearchListener.
   */
  private class ScanSearchListener implements InternalSearchListener
  {
    private final CSN startCSN;
    private final CSN endCSN;
 
    public ScanSearchListener(CSN startCSN, CSN endCSN)
    {
      this.startCSN = startCSN;
      this.endCSN = endCSN;
    }
 
    @Override
    public void handleInternalSearchEntry(
        InternalSearchOperation searchOperation, SearchResultEntry searchEntry)
        throws DirectoryException
    {
      // Build the list of Operations that happened on this entry after startCSN
      // and before endCSN and add them to the replayOperations list
      Iterable<FakeOperation> updates =
        EntryHistorical.generateFakeOperations(searchEntry);
 
      for (FakeOperation op : updates)
      {
        CSN csn = op.getCSN();
        if (csn.isNewerThan(startCSN) && csn.isOlderThan(endCSN))
        {
          synchronized (replayOperations)
          {
            replayOperations.put(csn, op);
          }
        }
      }
    }
 
    @Override
    public void handleInternalSearchReference(
        InternalSearchOperation searchOperation,
        SearchResultReference searchReference) throws DirectoryException
    {
       // Nothing to do.
    }
  }
 
  /**
   * The fully-qualified name of this class.
   */
  private static final String CLASS_NAME = LDAPReplicationDomain.class
      .getName();
 
  /**
   * The attribute used to mark conflicting entries.
   * The value of this attribute should be the dn that this entry was
   * supposed to have when it was marked as conflicting.
   */
  public static final String DS_SYNC_CONFLICT = "ds-sync-conflict";
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  private final DSRSShutdownSync dsrsShutdownSync;
  /**
   * The update to replay message queue where the listener thread is going to
   * push incoming update messages.
   */
  private final BlockingQueue<UpdateToReplay> updateToReplayQueue;
  /** The number of naming conflicts successfully resolved. */
  private final AtomicInteger numResolvedNamingConflicts = new AtomicInteger();
  /** The number of modify conflicts successfully resolved. */
  private final AtomicInteger numResolvedModifyConflicts = new AtomicInteger();
  /** The number of unresolved naming conflicts. */
  private final AtomicInteger numUnresolvedNamingConflicts =
      new AtomicInteger();
  /** The number of updates replayed successfully by the replication. */
  private final AtomicInteger numReplayedPostOpCalled = new AtomicInteger();
 
  private final PersistentServerState state;
  private volatile boolean generationIdSavedStatus = false;
 
  /**
   * This object is used to store the list of update currently being
   * done on the local database.
   * Is is useful to make sure that the local operations are sent in a
   * correct order to the replication server and that the ServerState
   * is not updated too early.
   */
  private final PendingChanges pendingChanges;
  private final AtomicReference<RSUpdater> rsUpdater =
      new AtomicReference<RSUpdater>(null);
 
  /**
   * It contain the updates that were done on other servers, transmitted by the
   * replication server and that are currently replayed.
   * <p>
   * It is useful to make sure that dependencies between operations are
   * correctly fulfilled and to make sure that the ServerState is not updated
   * too early.
   */
  private final RemotePendingChanges remotePendingChanges;
  private boolean solveConflictFlag = true;
 
  private final InternalClientConnection conn = getRootConnection();
  private final AtomicBoolean shutdown = new AtomicBoolean();
  private volatile boolean disabled = false;
  private volatile boolean stateSavingDisabled = false;
 
  /**
   * This list is used to temporary store operations that needs to be replayed
   * at session establishment time.
   */
  private final SortedMap<CSN, FakeOperation> replayOperations =
    new TreeMap<CSN, FakeOperation>();
 
  private ExternalChangelogDomain eclDomain;
 
  /**
   * A boolean indicating if the thread used to save the persistentServerState
   * is terminated.
   */
  private volatile boolean done = true;
 
  private final ServerStateFlush flushThread;
 
  /**
   * The attribute name used to store the generation id in the backend.
   */
  private static final String REPLICATION_GENERATION_ID =
    "ds-sync-generation-id";
  /**
   * The attribute name used to store the fractional include configuration in
   * the backend.
   */
  static final String REPLICATION_FRACTIONAL_INCLUDE =
    "ds-sync-fractional-include";
  /**
   * The attribute name used to store the fractional exclude configuration in
   * the backend.
   */
  static final String REPLICATION_FRACTIONAL_EXCLUDE =
    "ds-sync-fractional-exclude";
 
  /**
   * Fractional replication variables.
   */
 
  /** Holds the fractional configuration for this domain, if any. */
  private final FractionalConfig fractionalConfig;
 
  /**
   * The list of attributes that cannot be used in fractional replication
   * configuration.
   */
  private static final String[] FRACTIONAL_PROHIBITED_ATTRIBUTES = new String[]
  {
    "objectClass",
    "2.5.4.0" // objectClass OID
  };
 
  /**
   * When true, this flag is used to force the domain status to be put in bad
   * data set just after the connection to the replication server.
   * This must be used when fractional replication is enabled with a
   * configuration different from the previous one (or at the very first
   * fractional usage time) : after connection, a ChangeStatusMsg is sent
   * requesting the bad data set status. Then none of the update messages
   * received from the replication server are taken into account until the
   * backend is synchronized with brand new data set compliant with the new
   * fractional configuration (i.e with compliant fractional configuration in
   * domain root entry).
   */
  private boolean forceBadDataSet = false;
 
  /**
   * The message id to be used when an import is stopped with error by
   * the fractional replication ldif import plugin.
   */
  private int importErrorMessageId = -1;
  /**
   * LocalizableMessage type for ERR_FULL_UPDATE_IMPORT_FRACTIONAL_BAD_REMOTE.
   */
  static final int IMPORT_ERROR_MESSAGE_BAD_REMOTE = 1;
  /**
   * LocalizableMessage type for ERR_FULL_UPDATE_IMPORT_FRACTIONAL_REMOTE_IS_FRACTIONAL.
   */
  static final int IMPORT_ERROR_MESSAGE_REMOTE_IS_FRACTIONAL = 2;
 
  /*
   * Definitions for the return codes of the
   * fractionalFilterOperation(PreOperationModifyOperation
   *  modifyOperation, boolean performFiltering) method
   */
  /**
   * The operation contains attributes subject to fractional filtering according
   * to the fractional configuration.
   */
  private static final int FRACTIONAL_HAS_FRACTIONAL_FILTERED_ATTRIBUTES = 1;
  /**
   * The operation contains no attributes subject to fractional filtering
   * according to the fractional configuration.
   */
  private static final int FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES = 2;
  /** The operation should become a no-op. */
  private static final int FRACTIONAL_BECOME_NO_OP = 3;
 
  /**
   * The last CSN purged in this domain. Allows to have a continuous purging
   * process from one purge processing (task run) to the next one. Values 0 when
   * the server starts.
   */
  private CSN lastCSNPurgedFromHist = new CSN(0,0,0);
 
  /**
   * The thread that periodically saves the ServerState of this
   * LDAPReplicationDomain in the database.
   */
  private class ServerStateFlush extends DirectoryThread
  {
    protected ServerStateFlush()
    {
      super("Replica DS(" + getServerId() + ") state checkpointer for domain \"" + getBaseDN() + "\"");
    }
 
    /** {@inheritDoc} */
    @Override
    public void run()
    {
      done = false;
 
      while (!isShutdownInitiated())
      {
        try
        {
          synchronized (this)
          {
            this.wait(1000);
            if (!disabled && !stateSavingDisabled)
            {
              // save the ServerState
              state.save();
            }
          }
        }
        catch (InterruptedException e)
        {
          // Thread interrupted: check for shutdown.
          Thread.currentThread().interrupt();
        }
      }
      state.save();
 
      done = true;
    }
  }
 
  /**
   * The thread that is responsible to update the RS to which this domain is
   * connected in case it is late and there is no RS which is up to date.
   */
  private class RSUpdater extends DirectoryThread
  {
    private final CSN startCSN;
 
    protected RSUpdater(CSN replServerMaxCSN)
    {
      super("Replica DS(" + getServerId() + ") missing change publisher for domain \"" + getBaseDN() + "\"");
      this.startCSN = replServerMaxCSN;
    }
 
    /** {@inheritDoc} */
    @Override
    public void run()
    {
      // Replication server is missing some of our changes:
      // let's send them to him.
      logger.trace(DEBUG_GOING_TO_SEARCH_FOR_CHANGES);
 
      /*
       * Get all the changes that have not been seen by this
       * replication server and publish them.
       */
      try
      {
        if (buildAndPublishMissingChanges(startCSN, broker))
        {
          logger.trace(DEBUG_CHANGES_SENT);
          synchronized(replayOperations)
          {
            replayOperations.clear();
          }
        }
        else
        {
          /*
           * An error happened trying to search for the updates
           * This server will start accepting again new updates but
           * some inconsistencies will stay between servers.
           * Log an error for the repair tool
           * that will need to re-synchronize the servers.
           */
          logger.error(ERR_CANNOT_RECOVER_CHANGES, getBaseDN());
        }
      }
      catch (Exception e)
      {
        /*
         * An error happened trying to search for the updates
         * This server will start accepting again new updates but
         * some inconsistencies will stay between servers.
         * Log an error for the repair tool
         * that will need to re-synchronize the servers.
         */
        logger.error(ERR_CANNOT_RECOVER_CHANGES, getBaseDN());
      }
      finally
      {
        broker.setRecoveryRequired(false);
        // RSUpdater thread has finished its work, let's remove it from memory
        // so another RSUpdater thread can be started if needed.
        rsUpdater.compareAndSet(this, null);
      }
    }
  }
 
  /**
   * Creates a new ReplicationDomain using configuration from configEntry.
   *
   * @param configuration    The configuration of this ReplicationDomain.
   * @param updateToReplayQueue The queue for update messages to replay.
   * @param dsrsShutdownSync Synchronization object for shutdown of combined DS/RS instances.
   * @throws ConfigException In case of invalid configuration.
   */
  LDAPReplicationDomain(ReplicationDomainCfg configuration,
      BlockingQueue<UpdateToReplay> updateToReplayQueue,
      DSRSShutdownSync dsrsShutdownSync) throws ConfigException
  {
    super(configuration, -1);
 
    this.updateToReplayQueue = updateToReplayQueue;
    this.dsrsShutdownSync = dsrsShutdownSync;
 
    // Get assured configuration
    readAssuredConfig(configuration, false);
 
    // Get fractional configuration
    fractionalConfig = new FractionalConfig(getBaseDN());
    readFractionalConfig(configuration, false);
    storeECLConfiguration(configuration);
    solveConflictFlag = isSolveConflict(configuration);
 
    Backend<?> backend = getBackend();
    if (backend == null)
    {
      throw new ConfigException(ERR_SEARCHING_DOMAIN_BACKEND.get(getBaseDN()));
    }
 
    try
    {
      generationId = loadGenerationId();
    }
    catch (DirectoryException e)
    {
      logger.error(ERR_LOADING_GENERATION_ID, getBaseDN(), stackTraceToSingleLineString(e));
    }
 
    /*
     * Create a new Persistent Server State that will be used to store
     * the last CSN seen from all LDAP servers in the topology.
     */
    state = new PersistentServerState(getBaseDN(), getServerId(),
        getServerState());
    flushThread = new ServerStateFlush();
 
    /*
     * CSNGenerator is used to create new unique CSNs for each operation done on
     * this replication domain.
     *
     * The generator time is adjusted to the time of the last CSN received from
     * remote other servers.
     */
    pendingChanges = new PendingChanges(getGenerator(), this);
    remotePendingChanges = new RemotePendingChanges(getServerState());
 
    // listen for changes on the configuration
    configuration.addChangeListener(this);
 
    // register as an AlertGenerator
    DirectoryServer.registerAlertGenerator(this);
 
    startPublishService();
  }
 
  /**
   * Modify conflicts are solved for all suffixes but the schema suffix because
   * we don't want to store extra information in the schema ldif files. This has
   * no negative impact because the changes on schema should not produce
   * conflicts.
   */
  private boolean isSolveConflict(ReplicationDomainCfg cfg)
  {
    return !getBaseDN().equals(DirectoryServer.getSchemaDN())
        && cfg.isSolveConflicts();
  }
 
  /**
   * Sets the error message id to be used when online import is stopped with
   * error by the fractional replication ldif import plugin.
   * @param importErrorMessageId The message to use.
   */
  void setImportErrorMessageId(int importErrorMessageId)
  {
    this.importErrorMessageId = importErrorMessageId;
  }
 
  /**
   * This flag is used by the fractional replication ldif import plugin to stop
   * the (online) import process if a fractional configuration inconsistency is
   * detected by it.
   *
   * @return true if the online import currently in progress should continue,
   *         false otherwise.
   */
  private boolean isFollowImport()
  {
    return importErrorMessageId == -1;
  }
 
  /**
   * Gets and stores the fractional replication configuration parameters.
   * @param configuration The configuration object
   * @param allowReconnection Tells if one must reconnect if significant changes
   *        occurred
   */
  private void readFractionalConfig(ReplicationDomainCfg configuration,
    boolean allowReconnection)
  {
    // Read the configuration entry
    FractionalConfig newFractionalConfig;
    try
    {
      newFractionalConfig = FractionalConfig.toFractionalConfig(configuration);
    }
    catch(ConfigException e)
    {
      // Should not happen as normally already called without problem in
      // isConfigurationChangeAcceptable or isConfigurationAcceptable
      // if we come up to this method
      logger.info(NOTE_ERR_FRACTIONAL, getBaseDN(), stackTraceToSingleLineString(e));
      return;
    }
 
    /**
     * Is there any change in fractional configuration ?
     */
 
    // Compute current configuration
    boolean needReconnection;
     try
    {
      needReconnection = !FractionalConfig.
        isFractionalConfigEquivalent(fractionalConfig, newFractionalConfig);
    }
    catch  (ConfigException e)
    {
      // Should not happen
      logger.info(NOTE_ERR_FRACTIONAL, getBaseDN(), stackTraceToSingleLineString(e));
      return;
    }
 
    // Disable service if configuration changed
    final boolean needRestart = needReconnection && allowReconnection;
    if (needRestart)
    {
      disableService();
    }
    // Set new configuration
    int newFractionalMode = newFractionalConfig.fractionalConfigToInt();
    fractionalConfig.setFractional(newFractionalMode !=
      FractionalConfig.NOT_FRACTIONAL);
    if (fractionalConfig.isFractional())
    {
      // Set new fractional configuration values
      fractionalConfig.setFractionalExclusive(
          newFractionalMode == FractionalConfig.EXCLUSIVE_FRACTIONAL);
      fractionalConfig.setFractionalSpecificClassesAttributes(
        newFractionalConfig.getFractionalSpecificClassesAttributes());
      fractionalConfig.setFractionalAllClassesAttributes(
        newFractionalConfig.fractionalAllClassesAttributes);
    } else
    {
      // Reset default values
      fractionalConfig.setFractionalExclusive(true);
      fractionalConfig.setFractionalSpecificClassesAttributes(
        new HashMap<String, Set<String>>());
      fractionalConfig.setFractionalAllClassesAttributes(new HashSet<String>());
    }
 
    // Reconnect if required
    if (needRestart)
    {
      enableService();
    }
  }
 
  /**
   * Return true if the fractional configuration stored in the domain root
   * entry of the backend is equivalent to the fractional configuration stored
   * in the local variables.
   */
  private boolean isBackendFractionalConfigConsistent()
  {
    // Read config stored in domain root entry
    if (logger.isTraceEnabled())
    {
      logger.trace("Attempt to read the potential fractional config in domain root entry " + getBaseDN());
    }
 
    // Search the domain root entry that is used to save the generation id
    SearchRequest request = newSearchRequest(getBaseDN(), SearchScope.BASE_OBJECT)
        .addAttribute(REPLICATION_GENERATION_ID, REPLICATION_FRACTIONAL_EXCLUDE, REPLICATION_FRACTIONAL_INCLUDE);
    InternalSearchOperation search = conn.processSearch(request);
 
    if (search.getResultCode() != ResultCode.SUCCESS
        && search.getResultCode() != ResultCode.NO_SUCH_OBJECT)
    {
      String errorMsg = search.getResultCode().getName() + " " + search.getErrorMessage();
      logger.error(ERR_SEARCHING_GENERATION_ID, errorMsg, getBaseDN());
      return false;
    }
 
    SearchResultEntry resultEntry = findReplicationSearchResultEntry(search);
    if (resultEntry == null)
    {
      /*
       * The backend is probably empty: if there is some fractional
       * configuration in memory, we do not let the domain being connected,
       * otherwise, it's ok
       */
      return !fractionalConfig.isFractional();
    }
 
    // Now extract fractional configuration if any
    Iterator<String> exclIt =
        getAttributeValueIterator(resultEntry, REPLICATION_FRACTIONAL_EXCLUDE);
    Iterator<String> inclIt =
        getAttributeValueIterator(resultEntry, REPLICATION_FRACTIONAL_INCLUDE);
 
    // Compare backend and local fractional configuration
    return isFractionalConfigConsistent(fractionalConfig, exclIt, inclIt);
  }
 
  private SearchResultEntry findReplicationSearchResultEntry(
      InternalSearchOperation searchOperation)
  {
    final SearchResultEntry resultEntry = getFirstResult(searchOperation);
    if (resultEntry != null)
    {
      AttributeType synchronizationGenIDType =
          DirectoryServer.getAttributeType(REPLICATION_GENERATION_ID);
      List<Attribute> attrs =
          resultEntry.getAttribute(synchronizationGenIDType);
      if (attrs != null)
      {
        Attribute attr = attrs.get(0);
        if (attr.size() == 1)
        {
          return resultEntry;
        }
        if (attr.size() > 1)
        {
          String errorMsg = "#Values=" + attr.size() + " Must be exactly 1 in entry " + resultEntry.toLDIFString();
          logger.error(ERR_LOADING_GENERATION_ID, getBaseDN(), errorMsg);
        }
      }
    }
    return null;
  }
 
  private Iterator<String> getAttributeValueIterator(
      SearchResultEntry resultEntry, String attrName)
  {
    AttributeType attrType = DirectoryServer.getAttributeType(attrName);
    List<Attribute> exclAttrs = resultEntry.getAttribute(attrType);
    if (exclAttrs != null)
    {
      Attribute exclAttr = exclAttrs.get(0);
      if (exclAttr != null)
      {
        return new AttributeValueStringIterator(exclAttr.iterator());
      }
    }
    return null;
  }
 
  /**
   * Return true if the fractional configuration passed as fractional
   * configuration attribute values is equivalent to the fractional
   * configuration stored in the local variables.
   * @param fractionalConfig The local fractional configuration
   * @param exclIt Fractional exclude mode configuration attribute values to
   * analyze.
   * @param inclIt Fractional include mode configuration attribute values to
   * analyze.
   * @return True if the fractional configuration passed as fractional
   * configuration attribute values is equivalent to the fractional
   * configuration stored in the local variables.
   */
  static boolean isFractionalConfigConsistent(
      FractionalConfig fractionalConfig, Iterator<String> exclIt,
      Iterator<String> inclIt)
  {
    /*
     * Parse fractional configuration stored in passed fractional configuration
     * attributes values
     */
 
    Map<String, Set<String>> storedFractionalSpecificClassesAttributes =
        new HashMap<String, Set<String>>();
    Set<String> storedFractionalAllClassesAttributes = new HashSet<String>();
 
    int storedFractionalMode;
    try
    {
      storedFractionalMode = FractionalConfig.parseFractionalConfig(exclIt,
        inclIt, storedFractionalSpecificClassesAttributes,
        storedFractionalAllClassesAttributes);
    } catch (ConfigException e)
    {
      // Should not happen as configuration in domain root entry is flushed
      // from valid configuration in local variables
      logger.info(NOTE_ERR_FRACTIONAL, fractionalConfig.getBaseDn(), stackTraceToSingleLineString(e));
      return false;
    }
 
    FractionalConfig storedFractionalConfig = new FractionalConfig(
      fractionalConfig.getBaseDn());
    storedFractionalConfig.setFractional(storedFractionalMode !=
      FractionalConfig.NOT_FRACTIONAL);
    // Set stored fractional configuration values
    if (storedFractionalConfig.isFractional())
    {
      storedFractionalConfig.setFractionalExclusive(
          storedFractionalMode == FractionalConfig.EXCLUSIVE_FRACTIONAL);
    }
    storedFractionalConfig.setFractionalSpecificClassesAttributes(
      storedFractionalSpecificClassesAttributes);
    storedFractionalConfig.setFractionalAllClassesAttributes(
      storedFractionalAllClassesAttributes);
 
    /*
     * Compare configuration stored in passed fractional configuration
     * attributes with local variable one
     */
    try
    {
      return FractionalConfig.
        isFractionalConfigEquivalent(fractionalConfig, storedFractionalConfig);
    } catch (ConfigException e)
    {
      // Should not happen as configuration in domain root entry is flushed
      // from valid configuration in local variables so both should have already
      // been checked
      logger.info(NOTE_ERR_FRACTIONAL, fractionalConfig.getBaseDn(), stackTraceToSingleLineString(e));
      return false;
    }
  }
 
  /**
   * Utility class to have get a string iterator from an AtributeValue iterator.
   * Assuming the attribute values are strings.
   */
  static class AttributeValueStringIterator implements Iterator<String>
  {
    private final Iterator<ByteString> attrValIt;
 
    /**
     * Creates a new AttributeValueStringIterator object.
     * @param attrValIt The underlying attribute iterator to use, assuming
     * internal values are strings.
     */
    AttributeValueStringIterator(Iterator<ByteString> attrValIt)
    {
      this.attrValIt = attrValIt;
    }
 
    /** {@inheritDoc} */
    @Override
    public boolean hasNext()
    {
      return attrValIt.hasNext();
    }
 
    /** {@inheritDoc} */
    @Override
    public String next()
    {
      return attrValIt.next().toString();
    }
 
    /** {@inheritDoc} */
    // Should not be needed anyway
    @Override
    public void remove()
    {
      attrValIt.remove();
    }
  }
 
  /**
   * Compare 2 attribute collections and returns true if they are equivalent.
   *
   * @param attributes1
   *          First attribute collection to compare.
   * @param attributes2
   *          Second attribute collection to compare.
   * @return True if both attribute collection are equivalent.
   * @throws ConfigException
   *           If some attributes could not be retrieved from the schema.
   */
  private static boolean areAttributesEquivalent(
      Collection<String> attributes1, Collection<String> attributes2)
      throws ConfigException
  {
    // Compare all classes attributes
    if (attributes1.size() != attributes2.size())
    {
      return false;
    }
 
    // Check consistency of all classes attributes
    Schema schema = DirectoryServer.getSchema();
    /*
     * For each attribute in attributes1, check there is the matching
     * one in attributes2.
     */
    for (String attrName1 : attributes1)
    {
      // Get attribute from attributes1
      AttributeType attributeType1 = schema.getAttributeType(attrName1);
      if (attributeType1 == null)
      {
        throw new ConfigException(
          NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_ATTRIBUTE_TYPE.get(attrName1));
      }
      // Look for matching one in attributes2
      boolean foundAttribute = false;
      for (String attrName2 : attributes2)
      {
        AttributeType attributeType2 = schema.getAttributeType(attrName2);
        if (attributeType2 == null)
        {
          throw new ConfigException(
            NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_ATTRIBUTE_TYPE.get(attrName2));
        }
        if (attributeType1.equals(attributeType2))
        {
          foundAttribute = true;
          break;
        }
      }
      // Found matching attribute ?
      if (!foundAttribute)
      {
        return false;
      }
    }
 
    return true;
  }
 
  /**
   * Check that the passed fractional configuration is acceptable
   * regarding configuration syntax, schema constraints...
   * Throws an exception if the configuration is not acceptable.
   * @param configuration The configuration to analyze.
   * @throws org.opends.server.config.ConfigException if the configuration is
   * not acceptable.
   */
  private static void isFractionalConfigAcceptable(
    ReplicationDomainCfg configuration) throws ConfigException
  {
    /*
     * Parse fractional configuration
     */
 
    // Read the configuration entry
    FractionalConfig newFractionalConfig = FractionalConfig.toFractionalConfig(
        configuration);
 
    if (!newFractionalConfig.isFractional())
    {
      // Nothing to check
      return;
    }
 
    // Prepare variables to be filled with config
    Map<String, Set<String>> newFractionalSpecificClassesAttributes =
      newFractionalConfig.getFractionalSpecificClassesAttributes();
    Set<String> newFractionalAllClassesAttributes =
      newFractionalConfig.getFractionalAllClassesAttributes();
 
    /*
     * Check attributes consistency : we only allow to filter MAY (optional)
     * attributes of a class : to be compliant with the schema, no MUST
     * (mandatory) attribute can be filtered by fractional replication.
     */
 
    // Check consistency of specific classes attributes
    Schema schema = DirectoryServer.getSchema();
    int fractionalMode = newFractionalConfig.fractionalConfigToInt();
    for (String className : newFractionalSpecificClassesAttributes.keySet())
    {
      // Does the class exist ?
      ObjectClass fractionalClass = schema.getObjectClass(
        className.toLowerCase());
      if (fractionalClass == null)
      {
        throw new ConfigException(
          NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_OBJECT_CLASS.get(className));
      }
 
      boolean isExtensibleObjectClass =
          "extensibleObject".equalsIgnoreCase(className);
 
      Set<String> attributes =
        newFractionalSpecificClassesAttributes.get(className);
 
      for (String attrName : attributes)
      {
        // Not a prohibited attribute ?
        if (isFractionalProhibitedAttr(attrName))
        {
          throw new ConfigException(
            NOTE_ERR_FRACTIONAL_CONFIG_PROHIBITED_ATTRIBUTE.get(attrName));
        }
 
        // Does the attribute exist ?
        AttributeType attributeType = schema.getAttributeType(attrName);
        if (attributeType != null)
        {
          // No more checking for the extensibleObject class
          if (!isExtensibleObjectClass
              && fractionalMode == FractionalConfig.EXCLUSIVE_FRACTIONAL
              // Exclusive mode : the attribute must be optional
              && !fractionalClass.isOptional(attributeType))
          {
            throw new ConfigException(
                NOTE_ERR_FRACTIONAL_CONFIG_NOT_OPTIONAL_ATTRIBUTE.get(attrName,
                    className));
          }
        }
        else
        {
          throw new ConfigException(
            NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_ATTRIBUTE_TYPE.get(attrName));
        }
      }
    }
 
 
    // Check consistency of all classes attributes
    for (String attrName : newFractionalAllClassesAttributes)
    {
      // Not a prohibited attribute ?
      if (isFractionalProhibitedAttr(attrName))
      {
        throw new ConfigException(
          NOTE_ERR_FRACTIONAL_CONFIG_PROHIBITED_ATTRIBUTE.get(attrName));
      }
 
      // Does the attribute exist ?
      if (schema.getAttributeType(attrName) == null)
      {
        throw new ConfigException(
          NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_ATTRIBUTE_TYPE.get(attrName));
      }
    }
  }
 
  /**
   * Test if the passed attribute is not allowed to be used in configuration of
   * fractional replication.
   * @param attr Attribute to test.
   * @return true if the attribute is prohibited.
   */
  private static boolean isFractionalProhibitedAttr(String attr)
  {
    for (String forbiddenAttr : FRACTIONAL_PROHIBITED_ATTRIBUTES)
    {
      if (forbiddenAttr.equalsIgnoreCase(attr))
      {
        return true;
      }
    }
    return false;
  }
 
  /**
   * If fractional replication is enabled, this analyzes the operation and
   * suppresses the forbidden attributes in it so that they are not added in
   * the local backend.
   *
   * @param addOperation The operation to modify based on fractional
   * replication configuration
   * @param performFiltering Tells if the effective attribute filtering should
   * be performed or if the call is just to analyze if there are some
   * attributes filtered by fractional configuration
   * @return true if the operation contains some attributes subject to filtering
   * by the fractional configuration
   */
  private boolean fractionalFilterOperation(
    PreOperationAddOperation addOperation, boolean performFiltering)
  {
    return fractionalRemoveAttributesFromEntry(fractionalConfig,
      addOperation.getEntryDN().rdn(), addOperation.getObjectClasses(),
      addOperation.getUserAttributes(), performFiltering);
  }
 
  /**
   * If fractional replication is enabled, this analyzes the operation and
   * suppresses the forbidden attributes in it so that they are not added in
   * the local backend.
   *
   * @param modifyDNOperation The operation to modify based on fractional
   * replication configuration
   * @param performFiltering Tells if the effective modifications should
   * be performed or if the call is just to analyze if there are some
   * inconsistency with fractional configuration
   * @return true if the operation is inconsistent with fractional
   * configuration
   */
  private boolean fractionalFilterOperation(
    PreOperationModifyDNOperation modifyDNOperation, boolean performFiltering)
  {
    // Quick exit if not called for analyze and
    if (performFiltering && modifyDNOperation.deleteOldRDN())
    {
      // The core will remove any occurrence of attribute that was part of the
      // old RDN, nothing more to do.
      return true; // Will not be used as analyze was not requested
    }
 
    // Create a list of filtered attributes for this entry
    Entry concernedEntry = modifyDNOperation.getOriginalEntry();
    Set<String> fractionalConcernedAttributes =
      createFractionalConcernedAttrList(fractionalConfig,
      concernedEntry.getObjectClasses().keySet());
 
    boolean fractionalExclusive = fractionalConfig.isFractionalExclusive();
    if (fractionalExclusive && fractionalConcernedAttributes.isEmpty())
    {
      // No attributes to filter
      return false;
    }
 
    /*
     * Analyze the old and new rdn to see if they are some attributes to be
     * removed: if the oldRDN contains some forbidden attributes (for instance
     * it is possible if the entry was created with an add operation and the
     * RDN used contains a forbidden attribute: in this case the attribute value
     * has been kept to be consistent with the dn of the entry.) that are no
     * more part of the new RDN, we must remove any attribute of this type by
     * putting a modification to delete the attribute.
     */
 
    boolean inconsistentOperation = false;
    RDN rdn = modifyDNOperation.getEntryDN().rdn();
    RDN newRdn = modifyDNOperation.getNewRDN();
 
    // Go through each attribute of the old RDN
    for (int i=0 ; i<rdn.getNumValues() ; i++)
    {
      AttributeType attributeType = rdn.getAttributeType(i);
      // Is it present in the fractional attributes established list ?
      boolean foundAttribute =
          exists(fractionalConcernedAttributes, attributeType);
      if (canRemoveAttribute(fractionalExclusive, foundAttribute)
          && !newRdn.hasAttributeType(attributeType)
          && !modifyDNOperation.deleteOldRDN())
      {
        /*
         * A forbidden attribute is in the old RDN and no more in the new RDN,
         * and it has not been requested to remove attributes from old RDN:
         * let's remove the attribute from the entry to stay consistent with
         * fractional configuration
         */
        Modification modification = new Modification(ModificationType.DELETE,
          Attributes.empty(attributeType));
        modifyDNOperation.addModification(modification);
        inconsistentOperation = true;
      }
    }
 
    return inconsistentOperation;
  }
 
  private boolean exists(Set<String> attrNames, AttributeType attrTypeToFind)
  {
    for (String attrName : attrNames)
    {
      if (DirectoryServer.getAttributeType(attrName).equals(attrTypeToFind))
      {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Remove attributes from an entry, according to the passed fractional
   * configuration. The entry is represented by the 2 passed parameters.
   * The attributes to be removed are removed using the remove method on the
   * passed iterator for the attributes in the entry.
   * @param fractionalConfig The fractional configuration to use
   * @param entryRdn The rdn of the entry to add
   * @param classes The object classes representing the entry to modify
   * @param attributesMap The map of attributes/values to be potentially removed
   * from the entry.
   * @param performFiltering Tells if the effective attribute filtering should
   * be performed or if the call is just an analyze to see if there are some
   * attributes filtered by fractional configuration
   * @return true if the operation contains some attributes subject to filtering
   * by the fractional configuration
   */
   static boolean fractionalRemoveAttributesFromEntry(
    FractionalConfig fractionalConfig, RDN entryRdn,
    Map<ObjectClass,String> classes, Map<AttributeType,
    List<Attribute>> attributesMap, boolean performFiltering)
  {
    boolean hasSomeAttributesToFilter = false;
    /*
     * Prepare a list of attributes to be included/excluded according to the
     * fractional replication configuration
     */
 
    Set<String> fractionalConcernedAttributes =
      createFractionalConcernedAttrList(fractionalConfig, classes.keySet());
    boolean fractionalExclusive = fractionalConfig.isFractionalExclusive();
    if (fractionalExclusive && fractionalConcernedAttributes.isEmpty())
    {
      return false; // No attributes to filter
    }
 
    // Prepare list of object classes of the added entry
    Set<ObjectClass> entryClasses = classes.keySet();
 
    /*
     * Go through the user attributes and remove those that match filtered one
     * - exclude mode : remove only attributes that are in
     * fractionalConcernedAttributes
     * - include mode : remove any attribute that is not in
     * fractionalConcernedAttributes
     */
    List<List<Attribute>> newRdnAttrLists = new ArrayList<List<Attribute>>();
    List<AttributeType> rdnAttrTypes = new ArrayList<AttributeType>();
    final Set<AttributeType> attrTypes = attributesMap.keySet();
    for (Iterator<AttributeType> iter = attrTypes.iterator(); iter.hasNext();)
    {
      AttributeType attributeType = iter.next();
 
      // Only optional attributes may be removed
      if (isMandatoryAttribute(entryClasses, attributeType)
      // Do not remove an attribute if it is a prohibited one
          || isFractionalProhibited(attributeType)
          || !canRemoveAttribute(attributeType, fractionalExclusive,
              fractionalConcernedAttributes))
      {
        continue;
      }
 
      if (!performFiltering)
      {
        // The call was just to check : at least one attribute to filter
        // found, return immediately the answer;
        return true;
      }
 
      // Do not remove an attribute/value that is part of the RDN of the
      // entry as it is forbidden
      if (entryRdn.hasAttributeType(attributeType))
      {
        /*
        We must remove all values of the attributes map for this
        attribute type but the one that has the value which is in the RDN
        of the entry. In fact the (underlying )attribute list does not
        support remove so we have to create a new list, keeping only the
        attribute value which is the same as in the RDN
        */
        ByteString rdnAttributeValue =
          entryRdn.getAttributeValue(attributeType);
        List<Attribute> attrList = attributesMap.get(attributeType);
        ByteString sameAttrValue = null;
        // Locate the attribute value identical to the one in the RDN
        for (Attribute attr : attrList)
        {
          if (attr.contains(rdnAttributeValue))
          {
            for (ByteString attrValue : attr) {
              if (rdnAttributeValue.equals(attrValue)) {
                // Keep the value we want
                sameAttrValue = attrValue;
              } else {
                hasSomeAttributesToFilter = true;
              }
            }
          }
          else
          {
            hasSomeAttributesToFilter = true;
          }
        }
        //    Recreate the attribute list with only the RDN attribute value
        if (sameAttrValue != null)
          // Paranoia check: should never be the case as we should always
          // find the attribute/value pair matching the pair in the RDN
        {
          // Construct and store new attribute list
          newRdnAttrLists.add(
              newList(Attributes.create(attributeType, sameAttrValue)));
          /*
          Store matching attribute type
          The mapping will be done using object from rdnAttrTypes as key
          and object from newRdnAttrLists (at same index) as value in
          the user attribute map to be modified
          */
          rdnAttrTypes.add(attributeType);
        }
      }
      else
      {
        // Found an attribute to remove, remove it from the list.
        iter.remove();
        hasSomeAttributesToFilter = true;
      }
    }
    // Now overwrite the attribute values for the attribute types present in the
    // RDN, if there are some filtered attributes in the RDN
    for (int index = 0 ; index < rdnAttrTypes.size() ; index++)
    {
      attributesMap.put(rdnAttrTypes.get(index), newRdnAttrLists.get(index));
    }
    return hasSomeAttributesToFilter;
  }
 
  private static <T> ArrayList<T> newList(T elem)
  {
    final ArrayList<T> list = new ArrayList<T>(1);
    list.add(elem);
    return list;
  }
 
  private static <T> Set<T> newSet(T elem)
  {
    final Set<T> list = new LinkedHashSet<T>(1);
    list.add(elem);
    return list;
  }
 
   private static boolean isMandatoryAttribute(Set<ObjectClass> entryClasses,
       AttributeType attributeType)
   {
     for (ObjectClass objectClass : entryClasses)
     {
       if (objectClass.isRequired(attributeType))
       {
         return true;
       }
     }
     return false;
   }
 
   private static boolean isFractionalProhibited(AttributeType attrType)
   {
     String attributeName = attrType.getPrimaryName();
     return (attributeName != null && isFractionalProhibitedAttr(attributeName))
         || isFractionalProhibitedAttr(attrType.getOID());
   }
 
  private static boolean canRemoveAttribute(AttributeType attributeType,
      boolean fractionalExclusive, Set<String> fractionalConcernedAttributes)
  {
    String attributeName = attributeType.getPrimaryName();
    String attributeOid = attributeType.getOID();
 
    // Is the current attribute part of the established list ?
    boolean foundAttribute =
        contains(fractionalConcernedAttributes, attributeName, attributeOid);
    // Now remove the attribute or modification if:
    // - exclusive mode and attribute is in configuration
    // - inclusive mode and attribute is not in configuration
    return canRemoveAttribute(fractionalExclusive, foundAttribute);
  }
 
  private static boolean canRemoveAttribute(boolean fractionalExclusive,
      boolean foundAttribute)
  {
    return (foundAttribute && fractionalExclusive)
        || (!foundAttribute && !fractionalExclusive);
  }
 
  private static boolean contains(Set<String> attrNames, String attrName,
      String attrOID)
  {
    return attrNames.contains(attrOID)
        || (attrName != null && attrNames.contains(attrName.toLowerCase()));
  }
 
  /**
   * Prepares a list of attributes of interest for the fractional feature.
   * @param fractionalConfig The fractional configuration to use
   * @param entryObjectClasses The object classes of an entry on which an
   * operation is going to be performed.
   * @return The list of attributes of the entry to be excluded/included
   * when the operation will be performed.
   */
  private static Set<String> createFractionalConcernedAttrList(
    FractionalConfig fractionalConfig, Set<ObjectClass> entryObjectClasses)
  {
    /*
     * Is the concerned entry of a type concerned by fractional replication
     * configuration ? If yes, add the matching attribute names to a set of
     * attributes to take into account for filtering
     * (inclusive or exclusive mode).
     * Using a Set to avoid duplicate attributes (from 2 inheriting classes for
     * instance)
     */
    Set<String> fractionalConcernedAttributes = new HashSet<String>();
 
    // Get object classes the entry matches
    Set<String> fractionalAllClassesAttributes =
      fractionalConfig.getFractionalAllClassesAttributes();
    Map<String, Set<String>> fractionalSpecificClassesAttributes =
      fractionalConfig.getFractionalSpecificClassesAttributes();
 
    Set<String> fractionalClasses =
        fractionalSpecificClassesAttributes.keySet();
    for (ObjectClass entryObjectClass : entryObjectClasses)
    {
      for(String fractionalClass : fractionalClasses)
      {
        if (entryObjectClass.hasNameOrOID(fractionalClass.toLowerCase()))
        {
          fractionalConcernedAttributes.addAll(
              fractionalSpecificClassesAttributes.get(fractionalClass));
        }
      }
    }
 
    // Add to the set any attribute which is class independent
    fractionalConcernedAttributes.addAll(fractionalAllClassesAttributes);
 
    return fractionalConcernedAttributes;
  }
 
  /**
   * If fractional replication is enabled, this analyzes the operation and
   * suppresses the forbidden attributes in it so that they are not added/
   * deleted/modified in the local backend.
   *
   * @param modifyOperation The operation to modify based on fractional
   * replication configuration
   * @param performFiltering Tells if the effective attribute filtering should
   * be performed or if the call is just to analyze if there are some
   * attributes filtered by fractional configuration
   * @return FRACTIONAL_HAS_FRACTIONAL_FILTERED_ATTRIBUTES,
   * FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES or FRACTIONAL_BECOME_NO_OP
   */
  private int fractionalFilterOperation(PreOperationModifyOperation
    modifyOperation, boolean performFiltering)
  {
    /*
     * Prepare a list of attributes to be included/excluded according to the
     * fractional replication configuration
     */
 
    Entry modifiedEntry = modifyOperation.getCurrentEntry();
    Set<String> fractionalConcernedAttributes =
      createFractionalConcernedAttrList(fractionalConfig,
      modifiedEntry.getObjectClasses().keySet());
    boolean fractionalExclusive = fractionalConfig.isFractionalExclusive();
    if (fractionalExclusive && fractionalConcernedAttributes.isEmpty())
    {
      // No attributes to filter
      return FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES;
    }
 
    // Prepare list of object classes of the modified entry
    DN entryToModifyDn = modifyOperation.getEntryDN();
    Entry entryToModify;
    try
    {
      entryToModify = DirectoryServer.getEntry(entryToModifyDn);
    }
    catch(DirectoryException e)
    {
      logger.info(NOTE_ERR_FRACTIONAL, getBaseDN(), stackTraceToSingleLineString(e));
      return FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES;
    }
    Set<ObjectClass> entryClasses = entryToModify.getObjectClasses().keySet();
 
    /*
     * Now go through the attribute modifications and filter the mods according
     * to the fractional configuration (using the just established concerned
     * attributes list):
     * - delete attributes: remove them if regarding a filtered attribute
     * - add attributes: remove them if regarding a filtered attribute
     * - modify attributes: remove them if regarding a filtered attribute
     */
 
    int result = FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES;
    List<Modification> mods = modifyOperation.getModifications();
    Iterator<Modification> modsIt = mods.iterator();
    while (modsIt.hasNext())
    {
      Modification mod = modsIt.next();
      Attribute attr = mod.getAttribute();
      AttributeType attrType = attr.getAttributeType();
      // Fractional replication ignores operational attributes
      if (attrType.isOperational()
          || isMandatoryAttribute(entryClasses, attrType)
          || isFractionalProhibited(attrType)
          || !canRemoveAttribute(attrType, fractionalExclusive,
              fractionalConcernedAttributes))
      {
        continue;
      }
 
      if (!performFiltering)
      {
        // The call was just to check : at least one attribute to filter
        // found, return immediately the answer;
        return FRACTIONAL_HAS_FRACTIONAL_FILTERED_ATTRIBUTES;
      }
 
      // Found a modification to remove, remove it from the list.
      modsIt.remove();
      result = FRACTIONAL_HAS_FRACTIONAL_FILTERED_ATTRIBUTES;
      if (mods.isEmpty())
      {
        // This operation must become a no-op as no more modification in it
        return FRACTIONAL_BECOME_NO_OP;
      }
    }
 
    return result;
  }
 
  /**
   * This is overwritten to allow stopping the (online) import process by the
   * fractional ldif import plugin when it detects that the (imported) remote
   * data set is not consistent with the local fractional configuration.
   * {@inheritDoc}
   */
  @Override
  protected byte[] receiveEntryBytes()
  {
    if (isFollowImport())
    {
      // Ok, next entry is allowed to be received
      return super.receiveEntryBytes();
    }
 
    // Fractional ldif import plugin detected inconsistency between local and
    // remote server fractional configuration and is stopping the import
    // process:
    // This is an error termination during the import
    // The error is stored and the import is ended by returning null
    final ImportExportContext ieCtx = getImportExportContext();
    LocalizableMessage msg = null;
    switch (importErrorMessageId)
    {
    case IMPORT_ERROR_MESSAGE_BAD_REMOTE:
      msg = NOTE_ERR_FULL_UPDATE_IMPORT_FRACTIONAL_BAD_REMOTE.get(getBaseDN(), ieCtx.getImportSource());
      break;
    case IMPORT_ERROR_MESSAGE_REMOTE_IS_FRACTIONAL:
      msg = NOTE_ERR_FULL_UPDATE_IMPORT_FRACTIONAL_REMOTE_IS_FRACTIONAL.get(getBaseDN(), ieCtx.getImportSource());
      break;
    }
    ieCtx.setException(new DirectoryException(UNWILLING_TO_PERFORM, msg));
    return null;
  }
 
  /**
   * This is overwritten to allow stopping the (online) export process if the
   * local domain is fractional and the destination is all other servers:
   * This make no sense to have only fractional servers in a replicated
   * topology. This prevents from administrator manipulation error that would
   * lead to whole topology data corruption.
   * {@inheritDoc}
   */
  @Override
  protected void initializeRemote(int target, int requestorID,
    Task initTask, int initWindow) throws DirectoryException
  {
    if (target == RoutableMsg.ALL_SERVERS && fractionalConfig.isFractional())
    {
      LocalizableMessage msg = NOTE_ERR_FRACTIONAL_FORBIDDEN_FULL_UPDATE_FRACTIONAL.get(getBaseDN(), getServerId());
      throw new DirectoryException(ResultCode.UNWILLING_TO_PERFORM, msg);
    }
 
    // FIXME should the next call use the initWindow parameter rather than the
    // instance variable?
    super.initializeRemote(target, requestorID, initTask, getInitWindow());
  }
 
  /**
   * Implement the  handleConflictResolution phase of the deleteOperation.
   *
   * @param deleteOperation The deleteOperation.
   * @return A SynchronizationProviderResult indicating if the operation
   *         can continue.
   */
  SynchronizationProviderResult handleConflictResolution(
         PreOperationDeleteOperation deleteOperation)
  {
    if (!deleteOperation.isSynchronizationOperation() && !brokerIsConnected())
    {
      LocalizableMessage msg = ERR_REPLICATION_COULD_NOT_CONNECT.get(getBaseDN());
      return new SynchronizationProviderResult.StopProcessing(
          ResultCode.UNWILLING_TO_PERFORM, msg);
    }
 
    DeleteContext ctx =
      (DeleteContext) deleteOperation.getAttachment(SYNCHROCONTEXT);
    Entry deletedEntry = deleteOperation.getEntryToDelete();
 
    if (ctx != null)
    {
      /*
       * This is a replication operation
       * Check that the modified entry has the same entryuuid
       * as it was in the original message.
       */
      String operationEntryUUID = ctx.getEntryUUID();
      String deletedEntryUUID = getEntryUUID(deletedEntry);
      if (!operationEntryUUID.equals(deletedEntryUUID))
      {
        /*
         * The changes entry is not the same entry as the one on
         * the original change was performed.
         * Probably the original entry was renamed and replaced with
         * another entry.
         * We must not let the change proceed, return a negative
         * result and set the result code to NO_SUCH_OBJECT.
         * When the operation will return, the thread that started the operation
         * will try to find the correct entry and restart a new operation.
         */
        return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_SUCH_OBJECT, null);
      }
    }
    else
    {
      // There is no replication context attached to the operation
      // so this is not a replication operation.
      CSN csn = generateCSN(deleteOperation);
      String modifiedEntryUUID = getEntryUUID(deletedEntry);
      ctx = new DeleteContext(csn, modifiedEntryUUID);
      deleteOperation.setAttachment(SYNCHROCONTEXT, ctx);
 
      synchronized (replayOperations)
      {
        int size = replayOperations.size();
        if (size >= 10000)
        {
          replayOperations.remove(replayOperations.firstKey());
        }
        FakeOperation op = new FakeDelOperation(
            deleteOperation.getEntryDN(), csn, modifiedEntryUUID);
        replayOperations.put(csn, op);
      }
    }
 
    return new SynchronizationProviderResult.ContinueProcessing();
  }
 
  /**
   * Implement the  handleConflictResolution phase of the addOperation.
   *
   * @param addOperation The AddOperation.
   * @return A SynchronizationProviderResult indicating if the operation
   *         can continue.
   */
  SynchronizationProviderResult handleConflictResolution(
      PreOperationAddOperation addOperation)
  {
    if (!addOperation.isSynchronizationOperation() && !brokerIsConnected())
    {
      LocalizableMessage msg = ERR_REPLICATION_COULD_NOT_CONNECT.get(getBaseDN());
      return new SynchronizationProviderResult.StopProcessing(
          ResultCode.UNWILLING_TO_PERFORM, msg);
    }
 
    if (fractionalConfig.isFractional())
    {
      if (addOperation.isSynchronizationOperation())
      {
        /*
         * Filter attributes here for fractional replication. If fractional
         * replication is enabled, we analyze the operation to suppress the
         * forbidden attributes in it so that they are not added in the local
         * backend. This must be called before any other plugin is called, to
         * keep coherency across plugin calls.
         */
        fractionalFilterOperation(addOperation, true);
      }
      else
      {
        /*
         * Direct access from an LDAP client : if some attributes are to be
         * removed according to the fractional configuration, simply forbid
         * the operation
         */
        if (fractionalFilterOperation(addOperation, false))
        {
          LocalizableMessage msg = NOTE_ERR_FRACTIONAL_FORBIDDEN_OPERATION.get(getBaseDN(), addOperation);
          return new SynchronizationProviderResult.StopProcessing(
            ResultCode.UNWILLING_TO_PERFORM, msg);
        }
      }
    }
 
    if (addOperation.isSynchronizationOperation())
    {
      AddContext ctx = (AddContext) addOperation.getAttachment(SYNCHROCONTEXT);
      /*
       * If an entry with the same entry uniqueID already exist then
       * this operation has already been replayed in the past.
       */
      String uuid = ctx.getEntryUUID();
      if (findEntryDN(uuid) != null)
      {
        return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_OPERATION, null);
      }
 
      /* The parent entry may have been renamed here since the change was done
       * on the first server, and another entry have taken the former dn
       * of the parent entry
       */
 
      String parentEntryUUID = ctx.getParentEntryUUID();
      // root entry have no parent, there is no need to check for it.
      if (parentEntryUUID != null)
      {
        // There is a potential of perfs improvement here
        // if we could avoid the following parent entry retrieval
        DN parentDnFromCtx = findEntryDN(ctx.getParentEntryUUID());
        if (parentDnFromCtx == null)
        {
          // The parent does not exist with the specified unique id
          // stop the operation with NO_SUCH_OBJECT and let the
          // conflict resolution or the dependency resolution solve this.
          return new SynchronizationProviderResult.StopProcessing(
              ResultCode.NO_SUCH_OBJECT, null);
        }
 
        DN entryDN = addOperation.getEntryDN();
        DN parentDnFromEntryDn = entryDN.getParentDNInSuffix();
        if (parentDnFromEntryDn != null
            && !parentDnFromCtx.equals(parentDnFromEntryDn))
        {
          // parentEntry has been renamed
          // replication name conflict resolution is expected to fix that
          // later in the flow
          return new SynchronizationProviderResult.StopProcessing(
              ResultCode.NO_SUCH_OBJECT, null);
        }
      }
    }
    return new SynchronizationProviderResult.ContinueProcessing();
  }
 
  /**
   * Check that the broker associated to this ReplicationDomain has found
   * a Replication Server and that this LDAP server is therefore able to
   * process operations.
   * If not, set the ResultCode, the response message,
   * interrupt the operation, and return false
   *
   * @return  true when it OK to process the Operation, false otherwise.
   *          When false is returned the resultCode and the response message
   *          is also set in the Operation.
   */
  private boolean brokerIsConnected()
  {
    final IsolationPolicy isolationPolicy = config.getIsolationPolicy();
    if (isolationPolicy.equals(IsolationPolicy.ACCEPT_ALL_UPDATES))
    {
      // this policy imply that we always accept updates.
      return true;
    }
    if (isolationPolicy.equals(IsolationPolicy.REJECT_ALL_UPDATES))
    {
      // this isolation policy specifies that the updates are denied
      // when the broker had problems during the connection phase
      // Updates are still accepted if the broker is currently connecting..
      return !hasConnectionError();
    }
    // we should never get there as the only possible policies are
    // ACCEPT_ALL_UPDATES and REJECT_ALL_UPDATES
    return true;
  }
 
 
  /**
   * Implement the  handleConflictResolution phase of the ModifyDNOperation.
   *
   * @param modifyDNOperation The ModifyDNOperation.
   * @return A SynchronizationProviderResult indicating if the operation
   *         can continue.
   */
  SynchronizationProviderResult handleConflictResolution(
      PreOperationModifyDNOperation modifyDNOperation)
  {
    if (!modifyDNOperation.isSynchronizationOperation() && !brokerIsConnected())
    {
      LocalizableMessage msg = ERR_REPLICATION_COULD_NOT_CONNECT.get(getBaseDN());
      return new SynchronizationProviderResult.StopProcessing(
          ResultCode.UNWILLING_TO_PERFORM, msg);
    }
 
    if (fractionalConfig.isFractional())
    {
      if (modifyDNOperation.isSynchronizationOperation())
      {
        /*
         * Filter operation here for fractional replication. If fractional
         * replication is enabled, we analyze the operation and modify it if
         * necessary to stay consistent with what is defined in fractional
         * configuration.
         */
        fractionalFilterOperation(modifyDNOperation, true);
      }
      else
      {
        /*
         * Direct access from an LDAP client : something is inconsistent with
         * the fractional configuration, forbid the operation.
         */
        if (fractionalFilterOperation(modifyDNOperation, false))
        {
          LocalizableMessage msg = NOTE_ERR_FRACTIONAL_FORBIDDEN_OPERATION.get(getBaseDN(), modifyDNOperation);
          return new SynchronizationProviderResult.StopProcessing(
            ResultCode.UNWILLING_TO_PERFORM, msg);
        }
      }
    }
 
    ModifyDnContext ctx =
      (ModifyDnContext) modifyDNOperation.getAttachment(SYNCHROCONTEXT);
    if (ctx != null)
    {
      /*
       * This is a replication operation
       * Check that the modified entry has the same entryuuid
       * as was in the original message.
       */
      final String modifiedEntryUUID =
          getEntryUUID(modifyDNOperation.getOriginalEntry());
      if (!modifiedEntryUUID.equals(ctx.getEntryUUID()))
      {
        /*
         * The modified entry is not the same entry as the one on
         * the original change was performed.
         * Probably the original entry was renamed and replaced with
         * another entry.
         * We must not let the change proceed, return a negative
         * result and set the result code to NO_SUCH_OBJECT.
         * When the operation will return, the thread that started the operation
         * will try to find the correct entry and restart a new operation.
         */
        return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_SUCH_OBJECT, null);
      }
 
      if (modifyDNOperation.getNewSuperior() != null)
      {
        /*
         * Also check that the current id of the
         * parent is the same as when the operation was performed.
         */
        String newParentId = findEntryUUID(modifyDNOperation.getNewSuperior());
        if (newParentId != null && ctx.getNewSuperiorEntryUUID() != null
            && !newParentId.equals(ctx.getNewSuperiorEntryUUID()))
        {
        return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_SUCH_OBJECT, null);
        }
      }
 
      /*
       * If the object has been renamed more recently than this
       * operation, cancel the operation.
       */
      EntryHistorical hist = EntryHistorical.newInstanceFromEntry(
          modifyDNOperation.getOriginalEntry());
      if (hist.addedOrRenamedAfter(ctx.getCSN()))
      {
        return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_OPERATION, null);
      }
    }
    else
    {
      // There is no replication context attached to the operation
      // so this is not a replication operation.
      CSN csn = generateCSN(modifyDNOperation);
      String newParentId = null;
      if (modifyDNOperation.getNewSuperior() != null)
      {
        newParentId = findEntryUUID(modifyDNOperation.getNewSuperior());
      }
 
      Entry modifiedEntry = modifyDNOperation.getOriginalEntry();
      String modifiedEntryUUID = getEntryUUID(modifiedEntry);
      ctx = new ModifyDnContext(csn, modifiedEntryUUID, newParentId);
      modifyDNOperation.setAttachment(SYNCHROCONTEXT, ctx);
    }
    return new SynchronizationProviderResult.ContinueProcessing();
  }
 
  /**
   * Handle the conflict resolution.
   * Called by the core server after locking the entry and before
   * starting the actual modification.
   * @param modifyOperation the operation
   * @return code indicating is operation must proceed
   */
  SynchronizationProviderResult handleConflictResolution(
         PreOperationModifyOperation modifyOperation)
  {
    if (!modifyOperation.isSynchronizationOperation() && !brokerIsConnected())
    {
      LocalizableMessage msg = ERR_REPLICATION_COULD_NOT_CONNECT.get(getBaseDN());
      return new SynchronizationProviderResult.StopProcessing(
          ResultCode.UNWILLING_TO_PERFORM, msg);
    }
 
    if (fractionalConfig.isFractional())
    {
      if  (modifyOperation.isSynchronizationOperation())
      {
        /*
         * Filter attributes here for fractional replication. If fractional
         * replication is enabled, we analyze the operation and modify it so
         * that no forbidden attribute is added/modified/deleted in the local
         * backend. This must be called before any other plugin is called, to
         * keep coherency across plugin calls.
         */
        if (fractionalFilterOperation(modifyOperation, true) ==
          FRACTIONAL_BECOME_NO_OP)
        {
          // Every modifications filtered in this operation: the operation
          // becomes a no-op
          return new SynchronizationProviderResult.StopProcessing(
            ResultCode.NO_OPERATION, null);
        }
      }
      else
      {
        /*
         * Direct access from an LDAP client : if some attributes are to be
         * removed according to the fractional configuration, simply forbid
         * the operation
         */
        switch(fractionalFilterOperation(modifyOperation, false))
        {
          case FRACTIONAL_HAS_NO_FRACTIONAL_FILTERED_ATTRIBUTES:
            // Ok, let the operation happen
            break;
          case FRACTIONAL_HAS_FRACTIONAL_FILTERED_ATTRIBUTES:
            // Some attributes not compliant with fractional configuration :
            // forbid the operation
            LocalizableMessage msg = NOTE_ERR_FRACTIONAL_FORBIDDEN_OPERATION.get(getBaseDN(), modifyOperation);
            return new SynchronizationProviderResult.StopProcessing(
              ResultCode.UNWILLING_TO_PERFORM, msg);
        }
      }
    }
 
    ModifyContext ctx =
      (ModifyContext) modifyOperation.getAttachment(SYNCHROCONTEXT);
 
    Entry modifiedEntry = modifyOperation.getModifiedEntry();
    if (ctx == null)
    {
      // No replication ctx attached => not a replicated operation
      // - create a ctx with : CSN, entryUUID
      // - attach the context to the op
 
      CSN csn = generateCSN(modifyOperation);
      ctx = new ModifyContext(csn, getEntryUUID(modifiedEntry));
 
      modifyOperation.setAttachment(SYNCHROCONTEXT, ctx);
    }
    else
    {
      // Replication ctx attached => this is a replicated operation being
      // replayed here, it is necessary to
      // - check if the entry has been renamed
      // - check for conflicts
      String modifiedEntryUUID = ctx.getEntryUUID();
      String currentEntryUUID = getEntryUUID(modifiedEntry);
      if (currentEntryUUID != null
          && !currentEntryUUID.equals(modifiedEntryUUID))
      {
        /*
         * The current modified entry is not the same entry as the one on
         * the original modification was performed.
         * Probably the original entry was renamed and replaced with
         * another entry.
         * We must not let the modification proceed, return a negative
         * result and set the result code to NO_SUCH_OBJECT.
         * When the operation will return, the thread that started the
         * operation will try to find the correct entry and restart a new
         * operation.
         */
         return new SynchronizationProviderResult.StopProcessing(
              ResultCode.NO_SUCH_OBJECT, null);
      }
 
      // Solve the conflicts between modify operations
      EntryHistorical historicalInformation =
        EntryHistorical.newInstanceFromEntry(modifiedEntry);
      modifyOperation.setAttachment(EntryHistorical.HISTORICAL,
                                    historicalInformation);
 
      if (historicalInformation.replayOperation(modifyOperation, modifiedEntry))
      {
        numResolvedModifyConflicts.incrementAndGet();
      }
    }
    return new SynchronizationProviderResult.ContinueProcessing();
  }
 
  /**
   * The preOperation phase for the add Operation.
   * Its job is to generate the replication context associated to the
   * operation. It is necessary to do it in this phase because contrary to
   * the other operations, the entry UUID is not set when the handleConflict
   * phase is called.
   *
   * @param addOperation The Add Operation.
   */
  void doPreOperation(PreOperationAddOperation addOperation)
  {
    final CSN csn = generateCSN(addOperation);
    final String entryUUID = getEntryUUID(addOperation);
    final AddContext ctx = new AddContext(csn, entryUUID,
        findEntryUUID(addOperation.getEntryDN().getParentDNInSuffix()));
    addOperation.setAttachment(SYNCHROCONTEXT, ctx);
  }
 
  /** {@inheritDoc} */
  @Override
  public void publishReplicaOfflineMsg()
  {
    pendingChanges.putReplicaOfflineMsg();
    dsrsShutdownSync.replicaOfflineMsgSent(getBaseDN());
  }
 
  /**
   * Check if an operation must be synchronized.
   * Also update the list of pending changes and the server RUV
   * @param op the operation
   */
  void synchronize(PostOperationOperation op)
  {
    ResultCode result = op.getResultCode();
    // Note that a failed non-replication operation might not have a change
    // number.
    CSN curCSN = OperationContext.getCSN(op);
    if (curCSN != null && config.isLogChangenumber())
    {
      op.addAdditionalLogItem(AdditionalLogItem.unquotedKeyValue(getClass(),
          "replicationCSN", curCSN));
    }
 
    if (result == ResultCode.SUCCESS)
    {
      if (op.isSynchronizationOperation())
      { // Replaying a sync operation
        numReplayedPostOpCalled.incrementAndGet();
        try
        {
          remotePendingChanges.commit(curCSN);
        }
        catch (NoSuchElementException e)
        {
          logger.error(ERR_OPERATION_NOT_FOUND_IN_PENDING, op, curCSN);
          return;
        }
      }
      else
      {
        // Generate a replication message for a successful non-replication
        // operation.
        LDAPUpdateMsg msg = LDAPUpdateMsg.generateMsg(op);
 
        if (msg == null)
        {
          /*
          * This is an operation type that we do not know about
          * It should never happen.
          */
          pendingChanges.remove(curCSN);
          logger.error(ERR_UNKNOWN_TYPE, op.getOperationType());
          return;
        }
 
        addEntryAttributesForCL(msg,op);
 
        // If assured replication is configured, this will prepare blocking
        // mechanism. If assured replication is disabled, this returns
        // immediately
        prepareWaitForAckIfAssuredEnabled(msg);
        try
        {
          msg.encode();
          pendingChanges.commitAndPushCommittedChanges(curCSN, msg);
        }
        catch (NoSuchElementException e)
        {
          logger.error(ERR_OPERATION_NOT_FOUND_IN_PENDING, op, curCSN);
          return;
        }
        // If assured replication is enabled, this will wait for the matching
        // ack or time out. If assured replication is disabled, this returns
        // immediately
        try
        {
          waitForAckIfAssuredEnabled(msg);
        } catch (TimeoutException ex)
        {
          // This exception may only be raised if assured replication is enabled
          logger.info(NOTE_DS_ACK_TIMEOUT, getBaseDN(), getAssuredTimeout(), msg);
        }
      }
 
      // If the operation is a DELETE on the base entry of the suffix
      // that is replicated, the generation is now lost because the
      // DB is empty. We need to save it again the next time we add an entry.
      if (op.getOperationType().equals(OperationType.DELETE)
          && ((PostOperationDeleteOperation) op)
                .getEntryDN().equals(getBaseDN()))
      {
        generationIdSavedStatus = false;
      }
 
      if (!generationIdSavedStatus)
      {
        saveGenerationId(generationId);
      }
    }
    else if (!op.isSynchronizationOperation() && curCSN != null)
    {
      // Remove an unsuccessful non-replication operation from the pending
      // changes list.
      pendingChanges.remove(curCSN);
      pendingChanges.pushCommittedChanges();
    }
 
    checkForClearedConflict(op);
  }
 
  /**
   * Check if the operation that just happened has cleared a conflict :
   * Clearing a conflict happens if the operation has free a DN that
   * for which an other entry was in conflict.
   * Steps:
   * - get the DN freed by a DELETE or MODRDN op
   * - search for entries put in the conflict space (dn=entryUUID'+'....)
   *   because the expected DN was not available (ds-sync-conflict=expected DN)
   * - retain the entry with the oldest conflict
   * - rename this entry with the freedDN as it was expected originally
   */
   private void checkForClearedConflict(PostOperationOperation op)
   {
     OperationType type = op.getOperationType();
     if (op.getResultCode() != ResultCode.SUCCESS)
     {
       // those operations cannot have cleared a conflict
       return;
     }
 
     DN freedDN;
     if (type == OperationType.DELETE)
     {
       freedDN = ((PostOperationDeleteOperation) op).getEntryDN();
     }
     else if (type == OperationType.MODIFY_DN)
     {
       freedDN = ((PostOperationModifyDNOperation) op).getEntryDN();
     }
     else
     {
       return;
     }
 
    SearchFilter filter;
    try
    {
      filter = LDAPFilter.createEqualityFilter(DS_SYNC_CONFLICT,
          ByteString.valueOf(freedDN.toString())).toSearchFilter();
    }
    catch (DirectoryException e)
    {
      // can not happen?
      logger.traceException(e);
      return;
    }
 
    SearchRequest request = newSearchRequest(getBaseDN(), SearchScope.WHOLE_SUBTREE, filter)
        .addAttribute(USER_AND_REPL_OPERATIONAL_ATTRS);
    InternalSearchOperation searchOp =  conn.processSearch(request);
 
     Entry entryToRename = null;
     CSN entryToRenameCSN = null;
     for (SearchResultEntry entry : searchOp.getSearchEntries())
     {
       EntryHistorical history = EntryHistorical.newInstanceFromEntry(entry);
       if (entryToRename == null)
       {
         entryToRename = entry;
         entryToRenameCSN = history.getDNDate();
       }
       else if (!history.addedOrRenamedAfter(entryToRenameCSN))
       {
         // this conflict is older than the previous, keep it.
         entryToRename = entry;
         entryToRenameCSN = history.getDNDate();
       }
     }
 
     if (entryToRename != null)
     {
       DN entryDN = entryToRename.getName();
       ModifyDNOperation newOp = renameEntry(
           entryDN, freedDN.rdn(), freedDN.parent(), false);
 
       ResultCode res = newOp.getResultCode();
       if (res != ResultCode.SUCCESS)
       {
        logger.error(ERR_COULD_NOT_SOLVE_CONFLICT, entryDN, res);
       }
     }
   }
 
  /**
   * Rename an Entry Using a synchronization, non-replicated operation.
   * This method should be used instead of the InternalConnection methods
   * when the operation that need to be run must be local only and therefore
   * not replicated to the RS.
   *
   * @param targetDN     The DN of the entry to rename.
   * @param newRDN       The new RDN to be used.
   * @param parentDN     The parentDN to be used.
   * @param markConflict A boolean indicating is this entry should be marked
   *                     as a conflicting entry. In such case the
   *                     DS_SYNC_CONFLICT attribute will be added to the entry
   *                     with the value of its original DN.
   *                     If false, the DS_SYNC_CONFLICT attribute will be
   *                     cleared.
   *
   * @return The operation that was run to rename the entry.
   */
  private ModifyDNOperation renameEntry(DN targetDN, RDN newRDN, DN parentDN,
      boolean markConflict)
  {
    ModifyDNOperation newOp = new ModifyDNOperationBasis(
        conn, nextOperationID(), nextMessageID(), new ArrayList<Control>(0),
        targetDN, newRDN, false, parentDN);
 
    AttributeType attrType =
        DirectoryServer.getAttributeType(DS_SYNC_CONFLICT, true);
    if (markConflict)
    {
      Attribute attr =
          Attributes.create(attrType, targetDN.toString());
      newOp.addModification(new Modification(ModificationType.REPLACE, attr));
    }
    else
    {
      Attribute attr = Attributes.empty(attrType);
      newOp.addModification(new Modification(ModificationType.DELETE, attr));
    }
 
    runAsSynchronizedOperation(newOp);
    return newOp;
  }
 
  private void runAsSynchronizedOperation(Operation op)
  {
    op.setInternalOperation(true);
    op.setSynchronizationOperation(true);
    op.setDontSynchronize(true);
    op.run();
  }
 
  /**
   * Delete this ReplicationDomain.
   */
  void delete()
  {
    shutdown();
    removeECLDomainCfg();
  }
 
  /**
   * Shutdown this ReplicationDomain.
   */
  public void shutdown()
  {
    if (shutdown.compareAndSet(false, true))
    {
      final RSUpdater rsUpdater = this.rsUpdater.get();
      if (rsUpdater != null)
      {
        rsUpdater.initiateShutdown();
      }
 
      // stop the thread in charge of flushing the ServerState.
      if (flushThread != null)
      {
        flushThread.initiateShutdown();
        synchronized (flushThread)
        {
          flushThread.notify();
        }
      }
 
      DirectoryServer.deregisterAlertGenerator(this);
 
      // stop the ReplicationDomain
      disableService();
    }
 
    // wait for completion of the ServerStateFlush thread.
    try
    {
      while (!done)
      {
        Thread.sleep(50);
      }
    } catch (InterruptedException e)
    {
      Thread.currentThread().interrupt();
    }
  }
 
  /**
   * Create and replay a synchronized Operation from an UpdateMsg.
   *
   * @param msg
   *          The UpdateMsg to be replayed.
   * @param shutdown
   *          whether the server initiated shutdown
   */
  void replay(LDAPUpdateMsg msg, AtomicBoolean shutdown)
  {
    // Try replay the operation, then flush (replaying) any pending operation
    // whose dependency has been replayed until no more left.
    do
    {
      Operation op = null; // the last operation on which replay was attempted
      boolean dependency = false;
      String replayErrorMsg = null;
      CSN csn = null;
      try
      {
        // The next operation for which to attempt replay.
        // This local variable allow to keep error messages in the "op" local
        // variable until the next loop iteration starts.
        // "op" is already initialized to the next Operation because of the
        // error handling paths.
        Operation nextOp = op = msg.createOperation(conn);
        dependency = remotePendingChanges.checkDependencies(op, msg);
 
        boolean replayDone = false;
        int retryCount = 10;
        while (!dependency && !replayDone && (retryCount-- > 0))
        {
          if (shutdown.get())
          {
            // shutdown initiated, let's leave
            return;
          }
          // Try replay the operation
          op = nextOp;
          op.setInternalOperation(true);
          op.setSynchronizationOperation(true);
 
          // Always add the ManageDSAIT control so that updates to referrals
          // are processed locally.
          op.addRequestControl(new LDAPControl(OID_MANAGE_DSAIT_CONTROL));
 
          csn = OperationContext.getCSN(op);
          op.run();
 
          ResultCode result = op.getResultCode();
 
          if (result != ResultCode.SUCCESS)
          {
            if (result == ResultCode.NO_OPERATION)
            {
              // Pre-operation conflict resolution detected that the operation
              // was a no-op. For example, an add which has already been
              // replayed, or a modify DN operation on an entry which has been
              // renamed by a more recent modify DN.
              replayDone = true;
            }
            else if (result == ResultCode.BUSY)
            {
              /*
               * We probably could not get a lock (OPENDJ-885). Give the server
               * another chance to process this operation immediately.
               */
              Thread.yield();
              continue;
            }
            else if (result == ResultCode.UNAVAILABLE)
            {
              /*
               * It can happen when a rebuild is performed or the backend is
               * offline (OPENDJ-49). Give the server another chance to process
               * this operation after some time.
               */
              Thread.sleep(50);
              continue;
            }
            else if (op instanceof ModifyOperation)
            {
              ModifyOperation castOp = (ModifyOperation) op;
              dependency = remotePendingChanges.checkDependencies(castOp);
              ModifyMsg modifyMsg = (ModifyMsg) msg;
              replayDone = solveNamingConflict(castOp, modifyMsg);
            }
            else if (op instanceof DeleteOperation)
            {
              DeleteOperation castOp = (DeleteOperation) op;
              dependency = remotePendingChanges.checkDependencies(castOp);
              replayDone = solveNamingConflict(castOp, msg);
            }
            else if (op instanceof AddOperation)
            {
              AddOperation castOp = (AddOperation) op;
              AddMsg addMsg = (AddMsg) msg;
              dependency = remotePendingChanges.checkDependencies(castOp);
              replayDone = solveNamingConflict(castOp, addMsg);
            }
            else if (op instanceof ModifyDNOperation)
            {
              ModifyDNOperation castOp = (ModifyDNOperation) op;
              replayDone = solveNamingConflict(castOp, msg);
            }
            else
            {
              replayDone = true; // unknown type of operation ?!
            }
 
            if (replayDone)
            {
              // the update became a dummy update and the result
              // of the conflict resolution phase is to do nothing.
              // however we still need to push this change to the serverState
              updateError(csn);
            }
            else
            {
              /*
               * Create a new operation reflecting the new state of the
               * UpdateMsg after conflict resolution modified it.
               *  Note: When msg is a DeleteMsg, the DeleteOperation is properly
               *  created with subtreeDelete request control when needed.
               */
              nextOp = msg.createOperation(conn);
            }
          }
          else
          {
            replayDone = true;
          }
        }
 
        if (!replayDone && !dependency)
        {
          // Continue with the next change but the servers could now become
          // inconsistent.
          // Let the repair tool know about this.
          final LocalizableMessage message = ERR_LOOP_REPLAYING_OPERATION.get(
              op, op.getErrorMessage());
          logger.error(message);
          numUnresolvedNamingConflicts.incrementAndGet();
          replayErrorMsg = message.toString();
          updateError(csn);
        }
      } catch (DecodeException e)
      {
        replayErrorMsg = logDecodingOperationError(msg, e);
      } catch (LDAPException e)
      {
        replayErrorMsg = logDecodingOperationError(msg, e);
      } catch (DataFormatException e)
      {
        replayErrorMsg = logDecodingOperationError(msg, e);
      } catch (Exception e)
      {
        if (csn != null)
        {
          /*
           * An Exception happened during the replay process.
           * Continue with the next change but the servers will now start
           * to be inconsistent.
           * Let the repair tool know about this.
           */
          LocalizableMessage message =
              ERR_EXCEPTION_REPLAYING_OPERATION.get(
                  stackTraceToSingleLineString(e), op);
          logger.error(message);
          replayErrorMsg = message.toString();
          updateError(csn);
        } else
        {
          replayErrorMsg = logDecodingOperationError(msg, e);
        }
      } finally
      {
        if (!dependency)
        {
          processUpdateDone(msg, replayErrorMsg);
        }
      }
 
      // Now replay any pending update that had a dependency and whose
      // dependency has been replayed, do that until no more updates of that
      // type left...
      msg = remotePendingChanges.getNextUpdate();
    } while (msg != null);
  }
 
  private String logDecodingOperationError(LDAPUpdateMsg msg, Exception e)
  {
    LocalizableMessage message =
        ERR_EXCEPTION_DECODING_OPERATION.get(msg + " " + stackTraceToSingleLineString(e));
    logger.error(message);
    return message.toString();
  }
 
  /**
   * This method is called when an error happens while replaying
   * an operation.
   * It is necessary because the postOperation does not always get
   * called when error or Exceptions happen during the operation replay.
   *
   * @param csn the CSN of the operation with error.
   */
  private void updateError(CSN csn)
  {
    try
    {
      remotePendingChanges.commit(csn);
    }
    catch (NoSuchElementException e)
    {
      // A failure occurred after the change had been removed from the pending
      // changes table.
      if (logger.isTraceEnabled())
      {
        logger.trace(
            "LDAPReplicationDomain.updateError: Unable to find remote "
                + "pending change for CSN %s", csn);
      }
    }
  }
 
  /**
   * Generate a new CSN and insert it in the pending list.
   *
   * @param operation
   *          The operation for which the CSN must be generated.
   * @return The new CSN.
   */
  private CSN generateCSN(PluginOperation operation)
  {
    return pendingChanges.putLocalOperation(operation);
  }
 
 
  /**
   * Find the Unique Id of the entry with the provided DN by doing a
   * search of the entry and extracting its entryUUID from its attributes.
   *
   * @param dn The dn of the entry for which the unique Id is searched.
   *
   * @return The unique Id of the entry with the provided DN.
   */
  static String findEntryUUID(DN dn)
  {
    if (dn == null)
    {
      return null;
    }
    final SearchRequest request = newSearchRequest(dn, SearchScope.BASE_OBJECT)
        .addAttribute(ENTRYUUID_ATTRIBUTE_NAME);
    final InternalSearchOperation search = getRootConnection().processSearch(request);
    final SearchResultEntry resultEntry = getFirstResult(search);
    if (resultEntry != null)
    {
      return getEntryUUID(resultEntry);
    }
    return null;
  }
 
  private static SearchResultEntry getFirstResult(InternalSearchOperation search)
  {
    if (search.getResultCode() == ResultCode.SUCCESS)
    {
      final LinkedList<SearchResultEntry> results = search.getSearchEntries();
      if (!results.isEmpty())
      {
        return results.getFirst();
      }
    }
    return null;
  }
 
  /**
   * find the current DN of an entry from its entry UUID.
   *
   * @param uuid the Entry Unique ID.
   * @return The current DN of the entry or null if there is no entry with
   *         the specified UUID.
   */
  private DN findEntryDN(String uuid)
  {
    try
    {
      final SearchRequest request = newSearchRequest(getBaseDN(), SearchScope.WHOLE_SUBTREE, "entryuuid=" + uuid);
      InternalSearchOperation search = conn.processSearch(request);
      final SearchResultEntry resultEntry = getFirstResult(search);
      if (resultEntry != null)
      {
        return resultEntry.getName();
      }
    }
    catch (DirectoryException e)
    {
      // never happens because the filter is always valid.
    }
    return null;
  }
 
  /**
   * Solve a conflict detected when replaying a modify operation.
   *
   * @param op The operation that triggered the conflict detection.
   * @param msg The operation that triggered the conflict detection.
   * @return true if the process is completed, false if it must continue..
   */
  private boolean solveNamingConflict(ModifyOperation op, ModifyMsg msg)
  {
    ResultCode result = op.getResultCode();
    ModifyContext ctx = (ModifyContext) op.getAttachment(SYNCHROCONTEXT);
    String entryUUID = ctx.getEntryUUID();
 
    if (result == ResultCode.NO_SUCH_OBJECT)
    {
      /*
       * The operation is a modification but
       * the entry has been renamed on a different master in the same time.
       * search if the entry has been renamed, and return the new dn
       * of the entry.
       */
      DN newDN = findEntryDN(entryUUID);
      if (newDN != null)
      {
        // There is an entry with the same unique id as this modify operation
        // replay the modify using the current dn of this entry.
        msg.setDN(newDN);
        numResolvedNamingConflicts.incrementAndGet();
        return false;
      }
      else
      {
        // This entry does not exist anymore.
        // It has probably been deleted, stop the processing of this operation
        numResolvedNamingConflicts.incrementAndGet();
        return true;
      }
    }
    else if (result == ResultCode.NOT_ALLOWED_ON_RDN)
    {
      DN currentDN = findEntryDN(entryUUID);
      RDN currentRDN;
      if (currentDN != null)
      {
        currentRDN = currentDN.rdn();
      }
      else
      {
        // The entry does not exist anymore.
        numResolvedNamingConflicts.incrementAndGet();
        return true;
      }
 
      // The modify operation is trying to delete the value that is
      // currently used in the RDN. We need to alter the modify so that it does
      // not remove the current RDN value(s).
 
      List<Modification> mods = op.getModifications();
      for (Modification mod : mods)
      {
        AttributeType modAttrType = mod.getAttribute().getAttributeType();
        if ((mod.getModificationType() == ModificationType.DELETE
              || mod.getModificationType() == ModificationType.REPLACE)
            && currentRDN.hasAttributeType(modAttrType))
        {
          // the attribute can't be deleted because it is used in the RDN,
          // turn this operation is a replace with the current RDN value(s);
          mod.setModificationType(ModificationType.REPLACE);
          Attribute newAttribute = mod.getAttribute();
          AttributeBuilder attrBuilder = new AttributeBuilder(newAttribute);
          attrBuilder.add(currentRDN.getAttributeValue(modAttrType));
          mod.setAttribute(attrBuilder.toAttribute());
        }
      }
      msg.setMods(mods);
      numResolvedNamingConflicts.incrementAndGet();
      return false;
    }
    else
    {
      // The other type of errors can not be caused by naming conflicts.
      // Log a message for the repair tool.
      logger.error(ERR_ERROR_REPLAYING_OPERATION,
          op, ctx.getCSN(), result, op.getErrorMessage());
      return true;
    }
  }
 
 /**
  * Solve a conflict detected when replaying a delete operation.
  *
  * @param op The operation that triggered the conflict detection.
  * @param msg The operation that triggered the conflict detection.
  * @return true if the process is completed, false if it must continue..
  */
 private boolean solveNamingConflict(DeleteOperation op, LDAPUpdateMsg msg)
 {
   ResultCode result = op.getResultCode();
   DeleteContext ctx = (DeleteContext) op.getAttachment(SYNCHROCONTEXT);
   String entryUUID = ctx.getEntryUUID();
 
   if (result == ResultCode.NO_SUCH_OBJECT)
   {
     /*
      * Find if the entry is still in the database.
      */
     DN currentDN = findEntryDN(entryUUID);
     if (currentDN == null)
     {
       /*
        * The entry has already been deleted, either because this delete
        * has already been replayed or because another concurrent delete
        * has already done the job.
        * In any case, there is nothing more to do.
        */
       numResolvedNamingConflicts.incrementAndGet();
       return true;
     }
     else
     {
       // This entry has been renamed, replay the delete using its new DN.
       msg.setDN(currentDN);
       numResolvedNamingConflicts.incrementAndGet();
       return false;
     }
   }
   else if (result == ResultCode.NOT_ALLOWED_ON_NONLEAF)
   {
     /*
      * This may happen when we replay a DELETE done on a master
      * but children of this entry have been added on another master.
      *
      * Rename all the children by adding entryuuid in dn and delete this entry.
      *
      * The action taken here must be consistent with the actions
      * done in the solveNamingConflict(AddOperation) method
      * when we are adding an entry whose parent entry has already been deleted.
      */
     if (findAndRenameChild(op.getEntryDN(), op))
     {
       numUnresolvedNamingConflicts.incrementAndGet();
     }
 
     return false;
   }
   else
   {
     // The other type of errors can not be caused by naming conflicts.
     // Log a message for the repair tool.
     logger.error(ERR_ERROR_REPLAYING_OPERATION,
         op, ctx.getCSN(), result, op.getErrorMessage());
     return true;
   }
 }
 
/**
 * Solve a conflict detected when replaying a Modify DN operation.
 *
 * @param op The operation that triggered the conflict detection.
 * @param msg The operation that triggered the conflict detection.
 * @return true if the process is completed, false if it must continue.
 * @throws Exception When the operation is not valid.
 */
private boolean solveNamingConflict(ModifyDNOperation op, LDAPUpdateMsg msg)
    throws Exception
{
  ResultCode result = op.getResultCode();
  ModifyDnContext ctx = (ModifyDnContext) op.getAttachment(SYNCHROCONTEXT);
  String entryUUID = ctx.getEntryUUID();
  String newSuperiorID = ctx.getNewSuperiorEntryUUID();
 
  /*
   * four possible cases :
   * - the modified entry has been renamed
   * - the new parent has been renamed
   * - the operation is replayed for the second time.
   * - the entry has been deleted
   * action :
   *  - change the target dn and the new parent dn and
   *        restart the operation,
   *  - don't do anything if the operation is replayed.
   */
 
  // get the current DN of this entry in the database.
  DN currentDN = findEntryDN(entryUUID);
 
  // Construct the new DN to use for the entry.
  DN entryDN = op.getEntryDN();
  DN newSuperior;
  RDN newRDN = op.getNewRDN();
 
  if (newSuperiorID != null)
  {
    newSuperior = findEntryDN(newSuperiorID);
  }
  else
  {
    newSuperior = entryDN.parent();
  }
 
  //If we could not find the new parent entry, we missed this entry
  // earlier or it has disappeared from the database
  // Log this information for the repair tool and mark the entry
  // as conflicting.
  // stop the processing.
  if (newSuperior == null)
  {
    markConflictEntry(op, currentDN, currentDN.parent().child(newRDN));
    numUnresolvedNamingConflicts.incrementAndGet();
    return true;
  }
 
  DN newDN = newSuperior.child(newRDN);
 
  if (currentDN == null)
  {
    // The entry targeted by the Modify DN is not in the database
    // anymore.
    // This is a conflict between a delete and this modify DN.
    // The entry has been deleted, we can safely assume
    // that the operation is completed.
    numResolvedNamingConflicts.incrementAndGet();
    return true;
  }
 
  // if the newDN and the current DN match then the operation
  // is a no-op (this was probably a second replay)
  // don't do anything.
  if (newDN.equals(currentDN))
  {
    numResolvedNamingConflicts.incrementAndGet();
    return true;
  }
 
  if (result == ResultCode.NO_SUCH_OBJECT
      || result == ResultCode.UNWILLING_TO_PERFORM
      || result == ResultCode.OBJECTCLASS_VIOLATION)
  {
    /*
     * The entry or it's new parent has not been found
     * reconstruct the operation with the DN we just built
     */
    ModifyDNMsg modifyDnMsg = (ModifyDNMsg) msg;
    modifyDnMsg.setDN(currentDN);
    modifyDnMsg.setNewSuperior(newSuperior.toString());
    numResolvedNamingConflicts.incrementAndGet();
    return false;
  }
  else if (result == ResultCode.ENTRY_ALREADY_EXISTS)
  {
    /*
     * This may happen when two modifyDn operation
     * are done on different servers but with the same target DN
     * add the conflict object class to the entry
     * and rename it using its entryuuid.
     */
    ModifyDNMsg modifyDnMsg = (ModifyDNMsg) msg;
    markConflictEntry(op, op.getEntryDN(), newDN);
    modifyDnMsg.setNewRDN(generateConflictRDN(entryUUID,
                          modifyDnMsg.getNewRDN()));
    modifyDnMsg.setNewSuperior(newSuperior.toString());
    numUnresolvedNamingConflicts.incrementAndGet();
    return false;
  }
  else
  {
    // The other type of errors can not be caused by naming conflicts.
    // Log a message for the repair tool.
    logger.error(ERR_ERROR_REPLAYING_OPERATION,
        op, ctx.getCSN(), result, op.getErrorMessage());
    return true;
  }
}
 
 
  /**
   * Solve a conflict detected when replaying a ADD operation.
   *
   * @param op The operation that triggered the conflict detection.
   * @param msg The message that triggered the conflict detection.
   * @return true if the process is completed, false if it must continue.
   * @throws Exception When the operation is not valid.
   */
  private boolean solveNamingConflict(AddOperation op, AddMsg msg)
      throws Exception
  {
    ResultCode result = op.getResultCode();
    AddContext ctx = (AddContext) op.getAttachment(SYNCHROCONTEXT);
    String entryUUID = ctx.getEntryUUID();
    String parentUniqueId = ctx.getParentEntryUUID();
 
    if (result == ResultCode.NO_SUCH_OBJECT)
    {
      /*
       * This can happen if the parent has been renamed or deleted
       * find the parent dn and calculate a new dn for the entry
       */
      if (parentUniqueId == null)
      {
        /*
         * This entry is the base dn of the backend.
         * It is quite surprising that the operation result be NO_SUCH_OBJECT.
         * There is nothing more we can do except log a
         * message for the repair tool to look at this problem.
         * TODO : Log the message
         */
        return true;
      }
      DN parentDn = findEntryDN(parentUniqueId);
      if (parentDn == null)
      {
        /*
         * The parent has been deleted
         * rename the entry as a conflicting entry.
         * The action taken here must be consistent with the actions
         * done when in the solveNamingConflict(DeleteOperation) method
         * when we are deleting an entry that have some child entries.
         */
        addConflict(msg);
 
        String conflictRDN =
            generateConflictRDN(entryUUID, op.getEntryDN().rdn().toString());
        msg.setDN(DN.valueOf(conflictRDN + "," + getBaseDN()));
        // reset the parent entryUUID so that the check done is the
        // handleConflict phase does not fail.
        msg.setParentEntryUUID(null);
        numUnresolvedNamingConflicts.incrementAndGet();
      }
      else
      {
        msg.setDN(DN.valueOf(msg.getDN().rdn() + "," + parentDn));
        numResolvedNamingConflicts.incrementAndGet();
      }
      return false;
    }
    else if (result == ResultCode.ENTRY_ALREADY_EXISTS)
    {
      /*
       * This can happen if
       *  - two adds are done on different servers but with the
       *    same target DN.
       *  - the same ADD is being replayed for the second time on this server.
       * if the entryUUID already exist, assume this is a replay and
       *        don't do anything
       * if the entry unique id do not exist, generate conflict.
       */
      if (findEntryDN(entryUUID) != null)
      {
        // entry already exist : this is a replay
        return true;
      }
      else
      {
        addConflict(msg);
        String conflictRDN =
            generateConflictRDN(entryUUID, msg.getDN().toString());
        msg.setDN(DN.valueOf(conflictRDN));
        numUnresolvedNamingConflicts.incrementAndGet();
        return false;
      }
    }
    else
    {
      // The other type of errors can not be caused by naming conflicts.
      // log a message for the repair tool.
      logger.error(ERR_ERROR_REPLAYING_OPERATION,
          op, ctx.getCSN(), result, op.getErrorMessage());
      return true;
    }
  }
 
  /**
   * Find all the entries below the provided DN and rename them
   * so that they stay below the baseDN of this replicationDomain and
   * use the conflicting name and attribute.
   *
   * @param entryDN    The DN of the entry whose child must be renamed.
   * @param conflictOp The Operation that generated the conflict.
   */
  private boolean findAndRenameChild(DN entryDN, Operation conflictOp)
  {
    /*
     * TODO JNR Ludo thinks that: "Ideally, the operation should verify that the
     * entryUUID has not changed or try to use the entryUUID rather than the
     * DN.". entryUUID can be obtained from the caller of the current method.
     */
    boolean conflict = false;
 
    // Find and rename child entries.
    final SearchRequest request = newSearchRequest(entryDN, SearchScope.SINGLE_LEVEL)
        .addAttribute(ENTRYUUID_ATTRIBUTE_NAME, HISTORICAL_ATTRIBUTE_NAME);
    InternalSearchOperation op = conn.processSearch(request);
    if (op.getResultCode() == ResultCode.SUCCESS)
    {
      for (SearchResultEntry entry : op.getSearchEntries())
      {
        /*
         * Check the ADD and ModRDN date of the child entry
         * (All of them, not only the one that are newer than the DEL op)
         * and keep the entry as a conflicting entry.
         */
        conflict = true;
        renameConflictEntry(conflictOp, entry.getName(), getEntryUUID(entry));
      }
    }
    else
    {
      // log error and information for the REPAIR tool.
      logger.error(ERR_CANNOT_RENAME_CONFLICT_ENTRY, entryDN, conflictOp, op.getResultCode());
    }
 
    return conflict;
  }
 
 
  /**
   * Rename an entry that was conflicting so that it stays below the
   * baseDN of the replicationDomain.
   *
   * @param conflictOp The Operation that caused the conflict.
   * @param dn         The DN of the entry to be renamed.
   * @param entryUUID        The uniqueID of the entry to be renamed.
   */
  private void renameConflictEntry(Operation conflictOp, DN dn,
      String entryUUID)
  {
    LocalizableMessage alertMessage = NOTE_UNRESOLVED_CONFLICT.get(dn);
    DirectoryServer.sendAlertNotification(this,
        ALERT_TYPE_REPLICATION_UNRESOLVED_CONFLICT, alertMessage);
 
    RDN newRDN = generateDeleteConflictDn(entryUUID, dn);
    ModifyDNOperation newOp = renameEntry(dn, newRDN, getBaseDN(), true);
 
    if (newOp.getResultCode() != ResultCode.SUCCESS)
    {
      // log information for the repair tool.
      logger.error(ERR_CANNOT_RENAME_CONFLICT_ENTRY,
          dn, conflictOp, newOp.getResultCode());
    }
  }
 
 
  /**
   * Generate a modification to add the conflict attribute to an entry
   * whose Dn is now conflicting with another entry.
   *
   * @param op        The operation causing the conflict.
   * @param currentDN The current DN of the operation to mark as conflicting.
   * @param conflictDN     The newDn on which the conflict happened.
   */
  private void markConflictEntry(Operation op, DN currentDN, DN conflictDN)
  {
    // create new internal modify operation and run it.
    AttributeType attrType = DirectoryServer.getAttributeType(DS_SYNC_CONFLICT,
        true);
    Attribute attr = Attributes.create(attrType, conflictDN.toString());
    List<Modification> mods =
        newList(new Modification(ModificationType.REPLACE, attr));
 
    ModifyOperation newOp = new ModifyOperationBasis(
          conn, nextOperationID(), nextMessageID(), new ArrayList<Control>(0),
          currentDN, mods);
    runAsSynchronizedOperation(newOp);
 
    if (newOp.getResultCode() != ResultCode.SUCCESS)
    {
      // Log information for the repair tool.
      logger.error(ERR_CANNOT_ADD_CONFLICT_ATTRIBUTE, op, newOp.getResultCode());
    }
 
    // Generate an alert to let the administration know that some
    // conflict could not be solved.
    LocalizableMessage alertMessage = NOTE_UNRESOLVED_CONFLICT.get(conflictDN);
    DirectoryServer.sendAlertNotification(this,
        ALERT_TYPE_REPLICATION_UNRESOLVED_CONFLICT, alertMessage);
  }
 
  /**
   * Add the conflict attribute to an entry that could
   * not be added because it is conflicting with another entry.
   *
   * @param msg            The conflicting Add Operation.
   *
   * @throws DecodeException When an encoding error happened manipulating the
   *                       msg.
   */
  private void addConflict(AddMsg msg) throws DecodeException
  {
    String normalizedDN = msg.getDN().toString();
 
    // Generate an alert to let the administrator know that some
    // conflict could not be solved.
    LocalizableMessage alertMessage = NOTE_UNRESOLVED_CONFLICT.get(normalizedDN);
    DirectoryServer.sendAlertNotification(this,
        ALERT_TYPE_REPLICATION_UNRESOLVED_CONFLICT, alertMessage);
 
    // Add the conflict attribute
    msg.addAttribute(DS_SYNC_CONFLICT, normalizedDN);
  }
 
  /**
   * Generate the Dn to use for a conflicting entry.
   *
   * @param entryUUID The unique identifier of the entry involved in the
   * conflict.
   * @param rdn Original rdn.
   * @return The generated RDN for a conflicting entry.
   */
  private String generateConflictRDN(String entryUUID, String rdn)
  {
    return "entryuuid=" + entryUUID + "+" + rdn;
  }
 
  /**
   * Generate the RDN to use for a conflicting entry whose father was deleted.
   *
   * @param entryUUID The unique identifier of the entry involved in the
   *                 conflict.
   * @param dn       The original DN of the entry.
   *
   * @return The generated RDN for a conflicting entry.
   */
  private RDN generateDeleteConflictDn(String entryUUID, DN dn)
  {
    String newRDN =  "entryuuid=" + entryUUID + "+" + dn.rdn();
    try
    {
      return RDN.decode(newRDN);
    } catch (DirectoryException e)
    {
      // cannot happen
      return null;
    }
  }
 
  /**
   * Check if the domain solve conflicts.
   *
   * @return a boolean indicating if the domain should solve conflicts.
   */
  boolean solveConflict()
  {
    return solveConflictFlag;
  }
 
  /**
   * Disable the replication on this domain.
   * The session to the replication server will be stopped.
   * The domain will not be destroyed but call to the pre-operation
   * methods will result in failure.
   * The listener thread will be destroyed.
   * The monitor informations will still be accessible.
   */
  public void disable()
  {
    state.save();
    state.clearInMemory();
    disabled = true;
    disableService(); // This will cut the session and wake up the listener
  }
 
  /**
   * Do what necessary when the data have changed : load state, load
   * generation Id.
   * If there is no such information check if there is a
   * ReplicaUpdateVector entry and translate it into a state
   * and generationId.
   * @exception DirectoryException Thrown when an error occurs.
   */
  private void loadDataState() throws DirectoryException
  {
    state.clearInMemory();
    state.loadState();
    getGenerator().adjust(state.getMaxCSN(getServerId()));
 
    // Retrieves the generation ID associated with the data imported
    generationId = loadGenerationId();
  }
 
  /**
   * Enable back the domain after a previous disable.
   * The domain will connect back to a replication Server and
   * will recreate threads to listen for messages from the Synchronization
   * server.
   * The generationId will be retrieved or computed if necessary.
   * The ServerState will also be read again from the local database.
   */
  public void enable()
  {
    try
    {
      loadDataState();
    }
    catch (Exception e)
    {
      /* TODO should mark that replicationServer service is
       * not available, log an error and retry upon timeout
       * should we stop the modifications ?
       */
      logger.error(ERR_LOADING_GENERATION_ID, getBaseDN(), stackTraceToSingleLineString(e));
      return;
    }
 
    enableService();
 
    disabled = false;
  }
 
  /**
   * Compute the data generationId associated with the current data present
   * in the backend for this domain.
   * @return The computed generationId.
   * @throws DirectoryException When an error occurs.
   */
  private long computeGenerationId() throws DirectoryException
  {
    final long genId = exportBackend(null, true);
    if (logger.isTraceEnabled())
    {
      logger.trace("Computed generationId: generationId=" + genId);
    }
    return genId;
  }
 
  /**
   * Run a modify operation to update the entry whose DN is given as
   * a parameter with the generationID information.
   *
   * @param entryDN       The DN of the entry to be updated.
   * @param generationId  The value of the generationID to be saved.
   *
   * @return A ResultCode indicating if the operation was successful.
   */
  private ResultCode runSaveGenerationId(DN entryDN, long generationId)
  {
    // The generationId is stored in the root entry of the domain.
    final ByteString asn1BaseDn = ByteString.valueOf(entryDN.toString());
    final ArrayList<ByteString> values =
        newList(ByteString.valueOf(Long.toString(generationId)));
 
    LDAPAttribute attr = new LDAPAttribute(REPLICATION_GENERATION_ID, values);
    List<RawModification> mods = new ArrayList<RawModification>(1);
    mods.add(new LDAPModification(ModificationType.REPLACE, attr));
 
    ModifyOperation op = new ModifyOperationBasis(
          conn, nextOperationID(), nextMessageID(), new ArrayList<Control>(0),
          asn1BaseDn, mods);
    runAsSynchronizedOperation(op);
    return op.getResultCode();
  }
 
  /**
   * Stores the value of the generationId.
   * @param generationId The value of the generationId.
   * @return a ResultCode indicating if the method was successful.
   */
  private ResultCode saveGenerationId(long generationId)
  {
    ResultCode result = runSaveGenerationId(getBaseDN(), generationId);
    if (result != ResultCode.SUCCESS)
    {
      generationIdSavedStatus = false;
      if (result == ResultCode.NO_SUCH_OBJECT)
      {
        // If the base entry does not exist, save the generation
        // ID in the config entry
        result = runSaveGenerationId(config.dn(), generationId);
      }
 
      if (result != ResultCode.SUCCESS)
      {
        logger.error(ERR_UPDATING_GENERATION_ID, result.getName(), getBaseDN());
      }
    }
    else
    {
      generationIdSavedStatus = true;
    }
    return result;
  }
 
 
  /**
   * Load the GenerationId from the root entry of the domain
   * from the REPLICATION_GENERATION_ID attribute in database
   * to memory, or compute it if not found.
   *
   * @return generationId The retrieved value of generationId
   * @throws DirectoryException When an error occurs.
   */
  private long loadGenerationId() throws DirectoryException
  {
    if (logger.isTraceEnabled())
    {
      logger.trace("Attempt to read generation ID from DB " + getBaseDN());
    }
 
    /*
     * Search the database entry that is used to periodically
     * save the generation id
     */
    final SearchRequest request = newSearchRequest(getBaseDN(), SearchScope.BASE_OBJECT)
        .addAttribute(REPLICATION_GENERATION_ID);
    InternalSearchOperation search = conn.processSearch(request);
    if (search.getResultCode() == ResultCode.NO_SUCH_OBJECT)
    {
      // if the base entry does not exist look for the generationID
      // in the config entry.
      request.setName(config.dn());
      search = conn.processSearch(request);
    }
 
    boolean found = false;
    long aGenerationId = -1;
    if (search.getResultCode() != ResultCode.SUCCESS)
    {
      if (search.getResultCode() != ResultCode.NO_SUCH_OBJECT)
      {
        String errorMsg = search.getResultCode().getName() + " " + search.getErrorMessage();
        logger.error(ERR_SEARCHING_GENERATION_ID, errorMsg, getBaseDN());
      }
    }
    else
    {
      List<SearchResultEntry> result = search.getSearchEntries();
      SearchResultEntry resultEntry = result.get(0);
      if (resultEntry != null)
      {
        AttributeType synchronizationGenIDType =
          DirectoryServer.getAttributeType(REPLICATION_GENERATION_ID);
        List<Attribute> attrs =
          resultEntry.getAttribute(synchronizationGenIDType);
        if (attrs != null)
        {
          Attribute attr = attrs.get(0);
          if (attr.size()>1)
          {
            String errorMsg = "#Values=" + attr.size() + " Must be exactly 1 in entry " + resultEntry.toLDIFString();
            logger.error(ERR_LOADING_GENERATION_ID, getBaseDN(), errorMsg);
          }
          else if (attr.size() == 1)
          {
            found = true;
            try
            {
              aGenerationId = Long.decode(attr.iterator().next().toString());
            }
            catch(Exception e)
            {
              logger.error(ERR_LOADING_GENERATION_ID, getBaseDN(), stackTraceToSingleLineString(e));
            }
          }
        }
      }
    }
 
    if (!found)
    {
      aGenerationId = computeGenerationId();
      saveGenerationId(aGenerationId);
 
      if (logger.isTraceEnabled())
      {
        logger.trace("Generation ID created for domain baseDN=" + getBaseDN() + " generationId=" + aGenerationId);
      }
    }
    else
    {
      generationIdSavedStatus = true;
      if (logger.isTraceEnabled())
      {
        logger.trace("Generation ID successfully read from domain baseDN=" + getBaseDN()
            + " generationId=" + aGenerationId);
      }
    }
    return aGenerationId;
  }
 
  /**
   * Do whatever is needed when a backup is started.
   * We need to make sure that the serverState is correctly save.
   */
  void backupStart()
  {
    state.save();
  }
 
  /** Do whatever is needed when a backup is finished. */
  void backupEnd()
  {
    // Nothing is needed at the moment
  }
 
  /*
   * Total Update >>
   */
 
  /**
   * This method trigger an export of the replicated data.
   *
   * @param output               The OutputStream where the export should
   *                             be produced.
   * @throws DirectoryException  When needed.
   */
  @Override
  protected void exportBackend(OutputStream output) throws DirectoryException
  {
    exportBackend(output, false);
  }
 
  /**
   * Export the entries from the backend and/or compute the generation ID.
   * The ieContext must have been set before calling.
   *
   * @param output              The OutputStream where the export should
   *                            be produced.
   * @param checksumOutput      A boolean indicating if this export is
   *                            invoked to perform a checksum only
   *
   * @return The computed       GenerationID.
   *
   * @throws DirectoryException when an error occurred
   */
  private long exportBackend(OutputStream output, boolean checksumOutput)
      throws DirectoryException
  {
    Backend<?> backend = getBackend();
 
    //  Acquire a shared lock for the backend.
    try
    {
      String lockFile = LockFileManager.getBackendLockFileName(backend);
      StringBuilder failureReason = new StringBuilder();
      if (! LockFileManager.acquireSharedLock(lockFile, failureReason))
      {
        LocalizableMessage message =
            ERR_LDIFEXPORT_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason);
        logger.error(message);
        throw new DirectoryException(ResultCode.OTHER, message);
      }
    }
    catch (Exception e)
    {
      LocalizableMessage message =
          ERR_LDIFEXPORT_CANNOT_LOCK_BACKEND.get(backend.getBackendID(),
              stackTraceToSingleLineString(e));
      logger.error(message);
      throw new DirectoryException(ResultCode.OTHER, message);
    }
 
    long numberOfEntries = backend.numSubordinates(getBaseDN(), true) + 1;
    long entryCount = Math.min(numberOfEntries, 1000);
    OutputStream os;
    ReplLDIFOutputStream ros = null;
    if (checksumOutput)
    {
      ros = new ReplLDIFOutputStream(entryCount);
      os = ros;
      try
      {
        os.write(Long.toString(numberOfEntries).getBytes());
      }
      catch(Exception e)
      {
        // Should never happen
      }
    }
    else
    {
      os = output;
    }
 
    // baseDN branch is the only one included in the export
    LDIFExportConfig exportConfig = new LDIFExportConfig(os);
    exportConfig.setIncludeBranches(newList(getBaseDN()));
 
    // For the checksum computing mode, only consider the 'stable' attributes
    if (checksumOutput)
    {
      String includeAttributeStrings[] =
        {"objectclass", "sn", "cn", "entryuuid"};
      Set<AttributeType> includeAttributes = new HashSet<AttributeType>();
      for (String attrName : includeAttributeStrings)
      {
        AttributeType attrType  = DirectoryServer.getAttributeType(attrName);
        if (attrType == null)
        {
          attrType = DirectoryServer.getDefaultAttributeType(attrName);
        }
        includeAttributes.add(attrType);
      }
      exportConfig.setIncludeAttributes(includeAttributes);
    }
 
    //  Launch the export.
    long genID = 0;
    try
    {
      backend.exportLDIF(exportConfig);
    }
    catch (DirectoryException de)
    {
      if (ros == null || ros.getNumExportedEntries() < entryCount)
      {
        LocalizableMessage message = ERR_LDIFEXPORT_ERROR_DURING_EXPORT.get(de.getMessageObject());
        logger.error(message);
        throw new DirectoryException(ResultCode.OTHER, message);
      }
    }
    catch (Exception e)
    {
      LocalizableMessage message = ERR_LDIFEXPORT_ERROR_DURING_EXPORT.get(stackTraceToSingleLineString(e));
      logger.error(message);
      throw new DirectoryException(ResultCode.OTHER, message);
    }
    finally
    {
      // Clean up after the export by closing the export config.
      // Will also flush the export and export the remaining entries.
      exportConfig.close();
 
      if (checksumOutput)
      {
        genID = ros.getChecksumValue();
      }
 
      //  Release the shared lock on the backend.
      try
      {
        String lockFile = LockFileManager.getBackendLockFileName(backend);
        StringBuilder failureReason = new StringBuilder();
        if (! LockFileManager.releaseLock(lockFile, failureReason))
        {
          LocalizableMessage message =
              WARN_LDIFEXPORT_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), failureReason);
          logger.warn(message);
          throw new DirectoryException(ResultCode.OTHER, message);
        }
      }
      catch (Exception e)
      {
        LocalizableMessage message =
            WARN_LDIFEXPORT_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(),
                stackTraceToSingleLineString(e));
        logger.warn(message);
        throw new DirectoryException(ResultCode.OTHER, message);
      }
    }
    return genID;
  }
 
  /**
   * Process backend before import.
   *
   * @param backend
   *          The backend.
   * @throws DirectoryException
   *           If the backend could not be disabled or locked exclusively.
   */
  private void preBackendImport(Backend<?> backend) throws DirectoryException
  {
    // Stop saving state
    stateSavingDisabled = true;
 
    // FIXME setBackendEnabled should be part of TaskUtils ?
    TaskUtils.disableBackend(backend.getBackendID());
 
    // Acquire an exclusive lock for the backend.
    String lockFile = LockFileManager.getBackendLockFileName(backend);
    StringBuilder failureReason = new StringBuilder();
    if (! LockFileManager.acquireExclusiveLock(lockFile, failureReason))
    {
      LocalizableMessage message = ERR_INIT_CANNOT_LOCK_BACKEND.get(backend.getBackendID(), failureReason);
      logger.error(message);
      throw new DirectoryException(ResultCode.OTHER, message);
    }
  }
 
  /**
   * This method triggers an import of the replicated data.
   *
   * @param input                The InputStream from which the data are read.
   * @throws DirectoryException  When needed.
   */
  @Override
  protected void importBackend(InputStream input) throws DirectoryException
  {
    Backend<?> backend = getBackend();
 
    LDIFImportConfig importConfig = null;
    ImportExportContext ieCtx = getImportExportContext();
    try
    {
      if (!backend.supports(BackendOperation.LDIF_IMPORT))
      {
        ieCtx.setExceptionIfNoneSet(new DirectoryException(OTHER,
            ERR_INIT_IMPORT_NOT_SUPPORTED.get(backend.getBackendID())));
        return;
      }
 
      importConfig = new LDIFImportConfig(input);
      importConfig.setIncludeBranches(newSet(getBaseDN()));
      importConfig.setAppendToExistingData(false);
      importConfig.setSkipDNValidation(true);
      // We should not validate schema for replication
      importConfig.setValidateSchema(false);
      // Allow fractional replication ldif import plugin to be called
      importConfig.setInvokeImportPlugins(true);
      // Reset the follow import flag and message before starting the import
      importErrorMessageId = -1;
 
      // TODO How to deal with rejected entries during the import
      File rejectsFile =
          getFileForPath("logs" + File.separator + "replInitRejectedEntries");
      importConfig.writeRejectedEntries(rejectsFile.getAbsolutePath(),
          ExistingFileBehavior.OVERWRITE);
 
      // Process import
      preBackendImport(backend);
      backend.importLDIF(importConfig);
 
      stateSavingDisabled = false;
    }
    catch(Exception e)
    {
      ieCtx.setExceptionIfNoneSet(new DirectoryException(ResultCode.OTHER,
          ERR_INIT_IMPORT_FAILURE.get(stackTraceToSingleLineString(e))));
    }
    finally
    {
      try
      {
        // Cleanup
        if (importConfig != null)
        {
          importConfig.close();
          closeBackendImport(backend); // Re-enable backend
          backend = getBackend();
        }
 
        loadDataState();
 
        if (ieCtx.getException() != null)
        {
          // When an error occurred during an import, most of times
          // the generationId coming in the root entry of the imported data,
          // is not valid anymore (partial data in the backend).
          generationId = computeGenerationId();
          saveGenerationId(generationId);
        }
      }
      catch (DirectoryException fe)
      {
        // If we already catch an Exception it's quite possible
        // that the loadDataState() and setGenerationId() fail
        // so we don't bother about the new Exception.
        // However if there was no Exception before we want
        // to return this Exception to the task creator.
        ieCtx.setExceptionIfNoneSet(new DirectoryException(
            ResultCode.OTHER,
            ERR_INIT_IMPORT_FAILURE.get(stackTraceToSingleLineString(fe))));
      }
    }
 
    if (ieCtx.getException() != null)
    {
      throw ieCtx.getException();
    }
  }
 
  /**
   * Make post import operations.
   * @param backend The backend implied in the import.
   * @exception DirectoryException Thrown when an error occurs.
   */
  private void closeBackendImport(Backend<?> backend) throws DirectoryException
  {
    String lockFile = LockFileManager.getBackendLockFileName(backend);
    StringBuilder failureReason = new StringBuilder();
 
    // Release lock
    if (!LockFileManager.releaseLock(lockFile, failureReason))
    {
      LocalizableMessage message =
          WARN_LDIFIMPORT_CANNOT_UNLOCK_BACKEND.get(backend.getBackendID(), failureReason);
      logger.warn(message);
      throw new DirectoryException(ResultCode.OTHER, message);
    }
 
    TaskUtils.enableBackend(backend.getBackendID());
  }
 
  /**
   * Retrieves a replication domain based on the baseDN.
   *
   * @param baseDN The baseDN of the domain to retrieve
   * @return The domain retrieved
   * @throws DirectoryException When an error occurred or no domain
   * match the provided baseDN.
   */
  public static LDAPReplicationDomain retrievesReplicationDomain(DN baseDN)
      throws DirectoryException
  {
    LDAPReplicationDomain replicationDomain = null;
 
    // Retrieves the domain
    for (SynchronizationProvider<?> provider :
      DirectoryServer.getSynchronizationProviders())
    {
      if (!(provider instanceof MultimasterReplication))
      {
        LocalizableMessage message = ERR_INVALID_PROVIDER.get();
        throw new DirectoryException(ResultCode.OTHER, message);
      }
 
      // From the domainDN retrieves the replication domain
      LDAPReplicationDomain domain =
        MultimasterReplication.findDomain(baseDN, null);
      if (domain == null)
      {
        break;
      }
      if (replicationDomain != null)
      {
        // Should never happen
        LocalizableMessage message = ERR_MULTIPLE_MATCHING_DOMAIN.get();
        throw new DirectoryException(ResultCode.OTHER, message);
      }
      replicationDomain = domain;
    }
 
    if (replicationDomain == null)
    {
      throw new DirectoryException(ResultCode.OTHER, ERR_NO_MATCHING_DOMAIN.get(baseDN));
    }
    return replicationDomain;
  }
 
  /**
   * Returns the backend associated to this domain.
   * @return The associated backend.
   */
  private Backend<?> getBackend()
  {
    return DirectoryServer.getBackend(getBaseDN());
  }
 
  /*
   * <<Total Update
   */
 
 
  /**
   * Push the schema modifications contained in the given parameter as a
   * modification that would happen on a local server. The modifications are not
   * applied to the local schema backend and historical information is not
   * updated; but a CSN is generated and the ServerState associated to the
   * schema domain is updated.
   *
   * @param modifications
   *          The schema modifications to push
   */
  void synchronizeSchemaModifications(List<Modification> modifications)
  {
    ModifyOperation op = new ModifyOperationBasis(
        conn, nextOperationID(), nextMessageID(), null,
        DirectoryServer.getSchemaDN(), modifications);
 
    final Entry schema;
    try
    {
      schema = DirectoryServer.getEntry(DirectoryServer.getSchemaDN());
    }
    catch (DirectoryException e)
    {
      logger.traceException(e);
      logger.error(ERR_BACKEND_SEARCH_ENTRY.get(DirectoryServer.getSchemaDN().toString(),
              stackTraceToSingleLineString(e)));
      return;
    }
 
    LocalBackendModifyOperation localOp = new LocalBackendModifyOperation(op);
    CSN csn = generateCSN(localOp);
    OperationContext ctx = new ModifyContext(csn, getEntryUUID(schema));
    localOp.setAttachment(SYNCHROCONTEXT, ctx);
    localOp.setResultCode(ResultCode.SUCCESS);
    synchronize(localOp);
  }
 
  /**
   * Check if the provided configuration is acceptable for add.
   *
   * @param configuration The configuration to check.
   * @param unacceptableReasons When the configuration is not acceptable, this
   *                            table is use to return the reasons why this
   *                            configuration is not acceptable.
   *
   * @return true if the configuration is acceptable, false other wise.
   */
  static boolean isConfigurationAcceptable(ReplicationDomainCfg configuration,
      List<LocalizableMessage> unacceptableReasons)
  {
    // Check that there is not already a domain with the same DN
    final DN dn = configuration.getBaseDN();
    LDAPReplicationDomain domain = MultimasterReplication.findDomain(dn, null);
    if (domain != null && domain.getBaseDN().equals(dn))
    {
      unacceptableReasons.add(ERR_SYNC_INVALID_DN.get());
      return false;
    }
 
    // Check that the base DN is configured as a base-dn of the directory server
    if (DirectoryServer.getBackend(dn) == null)
    {
      unacceptableReasons.add(ERR_UNKNOWN_DN.get(dn));
      return false;
    }
 
    // Check fractional configuration
    try
    {
      isFractionalConfigAcceptable(configuration);
    } catch (ConfigException e)
    {
      unacceptableReasons.add(e.getMessageObject());
      return false;
    }
 
    return true;
  }
 
  /** {@inheritDoc} */
  @Override
  public ConfigChangeResult applyConfigurationChange(
         ReplicationDomainCfg configuration)
  {
    this.config = configuration;
    changeConfig(configuration);
 
    // Read assured + fractional configuration and each time reconnect if needed
    readAssuredConfig(configuration, true);
    readFractionalConfig(configuration, true);
 
    solveConflictFlag = isSolveConflict(configuration);
 
    final ConfigChangeResult ccr = new ConfigChangeResult();
    try
    {
      storeECLConfiguration(configuration);
    }
    catch(Exception e)
    {
      ccr.setResultCode(ResultCode.OTHER);
    }
    return ccr;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean isConfigurationChangeAcceptable(
         ReplicationDomainCfg configuration, List<LocalizableMessage> unacceptableReasons)
  {
    // Check that a import/export is not in progress
    if (ieRunning())
    {
      unacceptableReasons.add(
          NOTE_ERR_CANNOT_CHANGE_CONFIG_DURING_TOTAL_UPDATE.get());
      return false;
    }
 
    // Check fractional configuration
    try
    {
      isFractionalConfigAcceptable(configuration);
      return true;
    }
    catch (ConfigException e)
    {
      unacceptableReasons.add(e.getMessageObject());
      return false;
    }
  }
 
  /** {@inheritDoc} */
  @Override
  public Map<String, String> getAlerts()
  {
    Map<String, String> alerts = new LinkedHashMap<String, String>();
 
    alerts.put(ALERT_TYPE_REPLICATION_UNRESOLVED_CONFLICT,
               ALERT_DESCRIPTION_REPLICATION_UNRESOLVED_CONFLICT);
    return alerts;
  }
 
  /** {@inheritDoc} */
  @Override
  public String getClassName()
  {
    return CLASS_NAME;
 
  }
 
  /** {@inheritDoc} */
  @Override
  public DN getComponentEntryDN()
  {
    return config.dn();
  }
 
  /**
   * Starts the Replication Domain.
   */
  public void start()
  {
    // Create the ServerStateFlush thread
    flushThread.start();
 
    startListenService();
  }
 
 
  /**
   * Remove from this domain configuration, the configuration of the
   * external change log.
   */
  private void removeECLDomainCfg()
  {
    try
    {
      DN eclConfigEntryDN = DN.valueOf("cn=external changeLog," + config.dn());
      if (DirectoryServer.getConfigHandler().entryExists(eclConfigEntryDN))
      {
        DirectoryServer.getConfigHandler().deleteEntry(eclConfigEntryDN, null);
      }
    }
    catch(Exception e)
    {
      logger.traceException(e);
      logger.error(ERR_CHECK_CREATE_REPL_BACKEND_FAILED, stackTraceToSingleLineString(e));
    }
  }
 
  /**
   * Store the provided ECL configuration for the domain.
   * @param  domCfg       The provided configuration.
   * @throws ConfigException When an error occurred.
   */
  private void storeECLConfiguration(ReplicationDomainCfg domCfg)
      throws ConfigException
  {
    ExternalChangelogDomainCfg eclDomCfg = null;
    // create the ecl config if it does not exist
    // There may not be any config entry related to this domain in some
    // unit test cases
    try
    {
      DN configDn = config.dn();
      if (DirectoryServer.getConfigHandler().entryExists(configDn))
      {
        try
        { eclDomCfg = domCfg.getExternalChangelogDomain();
        } catch(Exception e) { /* do nothing */ }
        // domain with no config entry only when running unit tests
        if (eclDomCfg == null)
        {
          // no ECL config provided hence create a default one
          // create the default one
          DN eclConfigEntryDN = DN.valueOf("cn=external changelog," + configDn);
          if (!DirectoryServer.getConfigHandler().entryExists(eclConfigEntryDN))
          {
            // no entry exist yet for the ECL config for this domain
            // create it
            String ldif = makeLdif(
                "dn: cn=external changelog," + configDn,
                "objectClass: top",
                "objectClass: ds-cfg-external-changelog-domain",
                "cn: external changelog",
                "ds-cfg-enabled: " + !getBackend().isPrivateBackend());
            LDIFImportConfig ldifImportConfig = new LDIFImportConfig(
                new StringReader(ldif));
            // No need to validate schema in replication
            ldifImportConfig.setValidateSchema(false);
            LDIFReader reader = new LDIFReader(ldifImportConfig);
            Entry eclEntry = reader.readEntry();
            DirectoryServer.getConfigHandler().addEntry(eclEntry, null);
            ldifImportConfig.close();
          }
        }
      }
      eclDomCfg = domCfg.getExternalChangelogDomain();
      if (eclDomain != null)
      {
        eclDomain.applyConfigurationChange(eclDomCfg);
      }
      else
      {
        // Create the ECL domain object
        eclDomain = new ExternalChangelogDomain(this, eclDomCfg);
      }
    }
    catch (Exception e)
    {
      throw new ConfigException(NOTE_ERR_UNABLE_TO_ENABLE_ECL.get(
          "Replication Domain on " + getBaseDN(), stackTraceToSingleLineString(e)), e);
    }
  }
 
  private static String makeLdif(String... lines)
  {
    final StringBuilder buffer = new StringBuilder();
    for (String line : lines) {
      buffer.append(line).append(EOL);
    }
    // Append an extra line so we can append LDIF Strings.
    buffer.append(EOL);
    return buffer.toString();
  }
 
  /** {@inheritDoc} */
  @Override
  public void sessionInitiated(ServerStatus initStatus, ServerState rsState)
  {
    // Check domain fractional configuration consistency with local
    // configuration variables
    forceBadDataSet = !isBackendFractionalConfigConsistent();
 
    super.sessionInitiated(initStatus, rsState);
 
    // Now for bad data set status if needed
    if (forceBadDataSet)
    {
      signalNewStatus(StatusMachineEvent.TO_BAD_GEN_ID_STATUS_EVENT);
      logger.info(NOTE_FRACTIONAL_BAD_DATA_SET_NEED_RESYNC, getBaseDN());
      return; // Do not send changes to the replication server
    }
 
    try
    {
      /*
       * We must not publish changes to a replicationServer that has
       * not seen all our previous changes because this could cause
       * some other ldap servers to miss those changes.
       * Check that the ReplicationServer has seen all our previous
       * changes.
       */
      CSN replServerMaxCSN = rsState.getCSN(getServerId());
 
      // we don't want to update from here (a DS) an empty RS because
      // normally the RS should have been updated by other RSes except for
      // very last changes lost if the local connection was broken
      // ... hence the RS we are connected to should not be empty
      // ... or if it is empty, it is due to a voluntary reset
      // and we don't want to update it with our changes that could be huge.
      if (replServerMaxCSN != null && replServerMaxCSN.getSeqnum() != 0)
      {
        CSN ourMaxCSN = state.getMaxCSN(getServerId());
        if (ourMaxCSN != null
            && !ourMaxCSN.isOlderThanOrEqualTo(replServerMaxCSN))
        {
          pendingChanges.setRecovering(true);
          broker.setRecoveryRequired(true);
          final RSUpdater rsUpdater = new RSUpdater(replServerMaxCSN);
          if (this.rsUpdater.compareAndSet(null, rsUpdater))
          {
            rsUpdater.start();
          }
        }
      }
    } catch (Exception e)
    {
      logger.error(ERR_PUBLISHING_FAKE_OPS, getBaseDN(), stackTraceToSingleLineString(e));
    }
  }
 
  /**
   * Build the list of changes that have been processed by this server after the
   * CSN given as a parameter and publish them using the given session.
   *
   * @param startCSN
   *          The CSN where we need to start the search
   * @param session
   *          The session to use to publish the changes
   * @return A boolean indicating he success of the operation.
   * @throws Exception
   *           if an Exception happens during the search.
   */
  boolean buildAndPublishMissingChanges(CSN startCSN, ReplicationBroker session)
      throws Exception
  {
    // Trim the changes in replayOperations that are older than the startCSN.
    synchronized (replayOperations)
    {
      Iterator<CSN> it = replayOperations.keySet().iterator();
      while (it.hasNext())
      {
        if (shutdown.get())
        {
          return false;
        }
        if (it.next().isNewerThan(startCSN))
        {
          break;
        }
        it.remove();
      }
    }
 
    CSN lastRetrievedChange;
    InternalSearchOperation op;
    CSN currentStartCSN = startCSN;
    do
    {
      if (shutdown.get())
      {
        return false;
      }
 
      lastRetrievedChange = null;
      // We can't do the search in one go because we need to store the results
      // so that we are sure we send the operations in order and because the
      // list might be large.
      // So we search by interval of 10 seconds and store the results in the
      // replayOperations list so that they are sorted before sending them.
      long missingChangesDelta = currentStartCSN.getTime() + 10000;
      CSN endCSN = new CSN(missingChangesDelta, 0xffffffff, getServerId());
 
      ScanSearchListener listener =
        new ScanSearchListener(currentStartCSN, endCSN);
      op = searchForChangedEntries(getBaseDN(), currentStartCSN, endCSN,
              listener);
 
      // Publish and remove all the changes from the replayOperations list
      // that are older than the endCSN.
      final List<FakeOperation> opsToSend = new LinkedList<FakeOperation>();
      synchronized (replayOperations)
      {
        Iterator<FakeOperation> itOp = replayOperations.values().iterator();
        while (itOp.hasNext())
        {
          if (shutdown.get())
          {
            return false;
          }
          FakeOperation fakeOp = itOp.next();
          if (fakeOp.getCSN().isNewerThan(endCSN) // sanity check
              || !state.cover(fakeOp.getCSN())
              // do not look for replay operations in the future
              || currentStartCSN.isNewerThan(now()))
          {
            break;
          }
 
          lastRetrievedChange = fakeOp.getCSN();
          opsToSend.add(fakeOp);
          itOp.remove();
        }
      }
 
      for (FakeOperation opToSend : opsToSend)
      {
        if (shutdown.get())
        {
          return false;
        }
        session.publishRecovery(opToSend.generateMessage());
      }
 
      if (lastRetrievedChange != null)
      {
        if (logger.isInfoEnabled())
          logger.info(LocalizableMessage.raw("publish loop"
                  + " >=" + currentStartCSN + " <=" + endCSN
                  + " nentries=" + op.getEntriesSent()
                  + " result=" + op.getResultCode()
                  + " lastRetrievedChange=" + lastRetrievedChange));
        currentStartCSN = lastRetrievedChange;
      }
      else
      {
        if (logger.isInfoEnabled())
          logger.info(LocalizableMessage.raw("publish loop"
                  + " >=" + currentStartCSN + " <=" + endCSN
                  + " nentries=" + op.getEntriesSent()
                  + " result=" + op.getResultCode()
                  + " no changes"));
        currentStartCSN = endCSN;
      }
    } while (pendingChanges.recoveryUntil(currentStartCSN)
          && op.getResultCode().equals(ResultCode.SUCCESS));
 
    return op.getResultCode().equals(ResultCode.SUCCESS);
  }
 
  private static CSN now()
  {
    // ensure now() will always come last with isNewerThan() test,
    // even though the timestamp, or the timestamp and seqnum would be the same
    return new CSN(TimeThread.getTime(), Integer.MAX_VALUE, Integer.MAX_VALUE);
  }
 
  /**
   * Search for the changes that happened since fromCSN based on the historical
   * attribute. The only changes that will be send will be the one generated on
   * the serverId provided in fromCSN.
   *
   * @param baseDN
   *          the base DN
   * @param fromCSN
   *          The CSN from which we want the changes
   * @param lastCSN
   *          The max CSN that the search should return
   * @param resultListener
   *          The listener that will process the entries returned
   * @return the internal search operation
   * @throws Exception
   *           when raised.
   */
  private static InternalSearchOperation searchForChangedEntries(DN baseDN,
      CSN fromCSN, CSN lastCSN, InternalSearchListener resultListener)
      throws Exception
  {
    String maxValueForId;
    if (lastCSN == null)
    {
      final Integer serverId = fromCSN.getServerId();
      maxValueForId = "ffffffffffffffff" + String.format("%04x", serverId)
                      + "ffffffff";
    }
    else
    {
      maxValueForId = lastCSN.toString();
    }
 
    String filter =
        "(&(" + HISTORICAL_ATTRIBUTE_NAME + ">=dummy:" + fromCSN + ")" +
          "(" + HISTORICAL_ATTRIBUTE_NAME + "<=dummy:" + maxValueForId + "))";
    SearchRequest request = Requests.newSearchRequest(baseDN, SearchScope.WHOLE_SUBTREE, filter)
        .addAttribute(USER_AND_REPL_OPERATIONAL_ATTRS);
    return getRootConnection().processSearch(request, resultListener);
  }
 
  /**
   * Search for the changes that happened since fromCSN based on the historical
   * attribute. The only changes that will be send will be the one generated on
   * the serverId provided in fromCSN.
   *
   * @param baseDN
   *          the base DN
   * @param fromCSN
   *          The CSN from which we want the changes
   * @param resultListener
   *          that will process the entries returned.
   * @return the internal search operation
   * @throws Exception
   *           when raised.
   */
  static InternalSearchOperation searchForChangedEntries(DN baseDN,
      CSN fromCSN, InternalSearchListener resultListener) throws Exception
  {
    return searchForChangedEntries(baseDN, fromCSN, null, resultListener);
  }
 
 
  /**
   * This method should return the total number of objects in the
   * replicated domain.
   * This count will be used for reporting.
   *
   * @throws DirectoryException when needed.
   *
   * @return The number of objects in the replication domain.
   */
  @Override
  public long countEntries() throws DirectoryException
  {
    Backend<?> backend = getBackend();
    if (!backend.supports(BackendOperation.LDIF_EXPORT))
    {
      LocalizableMessage msg = ERR_INIT_EXPORT_NOT_SUPPORTED.get(backend.getBackendID());
      logger.error(msg);
      throw new DirectoryException(ResultCode.OTHER, msg);
    }
 
    return backend.numSubordinates(getBaseDN(), true) + 1;
  }
 
  /** {@inheritDoc} */
  @Override
  public boolean processUpdate(UpdateMsg updateMsg)
  {
    // Ignore message if fractional configuration is inconsistent and
    // we have been passed into bad data set status
    if (forceBadDataSet)
    {
      return false;
    }
 
    if (updateMsg instanceof LDAPUpdateMsg)
    {
      LDAPUpdateMsg msg = (LDAPUpdateMsg) updateMsg;
 
      // Put the UpdateMsg in the RemotePendingChanges list.
      if (!remotePendingChanges.putRemoteUpdate(msg))
      {
        /*
         * Already received this change so ignore it. This may happen if there
         * are uncommitted changes in the queue and session failover occurs
         * causing a recovery of all changes since the current committed server
         * state. See OPENDJ-1115.
         */
        if (logger.isTraceEnabled())
        {
          logger.trace(
                  "LDAPReplicationDomain.processUpdate: ignoring "
                  + "duplicate change %s", msg.getCSN());
        }
        return true;
      }
 
      // Put update message into the replay queue
      // (block until some place in the queue is available)
      final UpdateToReplay updateToReplay = new UpdateToReplay(msg, this);
      while (!isListenerShuttingDown())
      {
        // loop until we can offer to the queue or shutdown was initiated
        try
        {
          if (updateToReplayQueue.offer(updateToReplay, 1, TimeUnit.SECONDS))
          {
            // successful offer to the queue, let's exit the loop
            break;
          }
        }
        catch (InterruptedException e)
        {
          // Thread interrupted: check for shutdown.
          Thread.currentThread().interrupt();
        }
      }
 
      return false;
    }
 
    // unknown message type, this should not happen, just ignore it.
    return true;
  }
 
  /**
   * Monitoring information for the LDAPReplicationDomain.
   *
   * @return Monitoring attributes specific to the LDAPReplicationDomain.
   */
  @Override
  public Collection<Attribute> getAdditionalMonitoring()
  {
    List<Attribute> attributes = new ArrayList<Attribute>();
 
    // number of updates in the pending list
    addMonitorData(attributes, "pending-updates", pendingChanges.size());
 
    addMonitorData(attributes, "replayed-updates-ok",
        numReplayedPostOpCalled.get());
    addMonitorData(attributes, "resolved-modify-conflicts",
        numResolvedModifyConflicts.get());
    addMonitorData(attributes, "resolved-naming-conflicts",
        numResolvedNamingConflicts.get());
    addMonitorData(attributes, "unresolved-naming-conflicts",
        numUnresolvedNamingConflicts.get());
    addMonitorData(attributes, "remote-pending-changes-size",
        remotePendingChanges.getQueueSize());
 
    return attributes;
  }
 
  /**
   * Verifies that the given string represents a valid source
   * from which this server can be initialized.
   * @param sourceString The string representing the source
   * @return The source as a integer value
   * @throws DirectoryException if the string is not valid
   */
  public int decodeSource(String sourceString) throws DirectoryException
  {
    int source = 0;
    try
    {
      source = Integer.decode(sourceString);
      if (source >= -1 && source != getServerId())
      {
        // TODO Verifies serverID is in the domain
        // We should check here that this is a server implied
        // in the current domain.
        return source;
      }
    }
    catch (Exception e)
    {
      LocalizableMessage message = ERR_INVALID_IMPORT_SOURCE.get(
          getBaseDN(), getServerId(), sourceString, stackTraceToSingleLineString(e));
      throw new DirectoryException(ResultCode.OTHER, message, e);
    }
 
    LocalizableMessage message = ERR_INVALID_IMPORT_SOURCE.get(getBaseDN(), getServerId(), source, "");
    throw new DirectoryException(ResultCode.OTHER, message);
  }
 
  /**
   * Called by synchronize post op plugin in order to add the entry historical
   * attributes to the UpdateMsg.
   * @param msg an replication update message
   * @param op  the operation in progress
   */
  private void addEntryAttributesForCL(UpdateMsg msg,
      PostOperationOperation op)
  {
    if (op instanceof PostOperationDeleteOperation)
    {
      PostOperationDeleteOperation delOp = (PostOperationDeleteOperation) op;
      final Set<String> names = getEclIncludesForDeletes();
      Entry entry = delOp.getEntryToDelete();
      final DeleteMsg deleteMsg = (DeleteMsg) msg;
      deleteMsg.setEclIncludes(getIncludedAttributes(entry, names));
 
      // For delete only, add the Authorized DN since it's required in the
      // ECL entry but is not part of rest of the message.
      DN deleterDN = delOp.getAuthorizationDN();
      if (deleterDN != null)
      {
        deleteMsg.setInitiatorsName(deleterDN.toString());
      }
    }
    else if (op instanceof PostOperationModifyOperation)
    {
      PostOperationModifyOperation modOp = (PostOperationModifyOperation) op;
      Set<String> names = getEclIncludes();
      Entry entry = modOp.getCurrentEntry();
      ((ModifyMsg) msg).setEclIncludes(getIncludedAttributes(entry, names));
    }
    else if (op instanceof PostOperationModifyDNOperation)
    {
      PostOperationModifyDNOperation modDNOp =
        (PostOperationModifyDNOperation) op;
      Set<String> names = getEclIncludes();
      Entry entry = modDNOp.getOriginalEntry();
      ((ModifyDNMsg) msg).setEclIncludes(getIncludedAttributes(entry, names));
    }
    else if (op instanceof PostOperationAddOperation)
    {
      PostOperationAddOperation addOp = (PostOperationAddOperation) op;
      Set<String> names = getEclIncludes();
      Entry entry = addOp.getEntryToAdd();
      ((AddMsg) msg).setEclIncludes(getIncludedAttributes(entry, names));
    }
  }
 
  private Collection<Attribute> getIncludedAttributes(Entry entry,
      Set<String> names)
  {
    if (names.isEmpty())
    {
      // Fast-path.
      return Collections.emptySet();
    }
    else if (names.size() == 1 && names.contains("*"))
    {
      // Potential fast-path for delete operations.
      List<Attribute> attributes = new LinkedList<Attribute>();
      for (List<Attribute> attributeList : entry.getUserAttributes().values())
      {
        attributes.addAll(attributeList);
      }
      Attribute objectClassAttribute = entry.getObjectClassAttribute();
      if (objectClassAttribute != null)
      {
        attributes.add(objectClassAttribute);
      }
      return attributes;
    }
    else
    {
      // Expand @objectclass references in attribute list if needed.
      // We do this now in order to take into account dynamic schema changes.
      final Set<String> expandedNames = getExpandedNames(names);
      final Entry filteredEntry =
          entry.filterEntry(expandedNames, false, false, false);
      return filteredEntry.getAttributes();
    }
  }
 
  private Set<String> getExpandedNames(Set<String> names)
  {
    // Only rebuild the attribute set if necessary.
    if (!needsExpanding(names))
    {
      return names;
    }
 
    final Set<String> expandedNames = new HashSet<String>(names.size());
    for (String name : names)
    {
      if (name.startsWith("@"))
      {
        String ocName = name.substring(1);
        ObjectClass objectClass =
            DirectoryServer.getObjectClass(toLowerCase(ocName));
        if (objectClass != null)
        {
          for (AttributeType at : objectClass.getRequiredAttributeChain())
          {
            expandedNames.add(at.getNameOrOID());
          }
          for (AttributeType at : objectClass.getOptionalAttributeChain())
          {
            expandedNames.add(at.getNameOrOID());
          }
        }
      }
      else
      {
        expandedNames.add(name);
      }
    }
    return expandedNames;
  }
 
  private boolean needsExpanding(Set<String> names)
  {
    for (String name : names)
    {
      if (name.startsWith("@"))
      {
        return true;
      }
    }
    return false;
  }
 
  /**
   * Gets the fractional configuration of this domain.
   * @return The fractional configuration of this domain.
   */
  FractionalConfig getFractionalConfig()
  {
    return fractionalConfig;
  }
 
  /**
   * This bean is a utility class used for holding the parsing
   * result of a fractional configuration. It also contains some facility
   * methods like fractional configuration comparison...
   */
  static class FractionalConfig
  {
    /**
     * Tells if fractional replication is enabled or not (some fractional
     * constraints have been put in place). If this is true then
     * fractionalExclusive explains the configuration mode and either
     * fractionalSpecificClassesAttributes or fractionalAllClassesAttributes or
     * both should be filled with something.
     */
    private boolean fractional = false;
 
    /**
     * - If true, tells that the configured fractional replication is exclusive:
     * Every attributes contained in fractionalSpecificClassesAttributes and
     * fractionalAllClassesAttributes should be ignored when replaying operation
     * in local backend.
     * - If false, tells that the configured fractional replication is
     * inclusive:
     * Only attributes contained in fractionalSpecificClassesAttributes and
     * fractionalAllClassesAttributes should be taken into account in local
     * backend.
     */
    private boolean fractionalExclusive = true;
 
    /**
     * Used in fractional replication: holds attributes of a specific object
     * class.
     * - key = object class (name or OID of the class)
     * - value = the attributes of that class that should be taken into account
     * (inclusive or exclusive fractional replication) (name or OID of the
     * attribute)
     * When an operation coming from the network is to be locally replayed, if
     * the concerned entry has an objectClass attribute equals to 'key':
     * - inclusive mode: only the attributes in 'value' will be added/deleted/
     * modified
     * - exclusive mode: the attributes in 'value' will not be added/deleted/
     * modified
     */
    private Map<String, Set<String>> fractionalSpecificClassesAttributes =
        new HashMap<String, Set<String>>();
 
    /**
     * Used in fractional replication: holds attributes of any object class.
     * When an operation coming from the network is to be locally replayed:
     * - inclusive mode: only attributes of the matching entry not present in
     * fractionalAllClassesAttributes will be added/deleted/modified
     * - exclusive mode: attributes of the matching entry present in
     * fractionalAllClassesAttributes will not be added/deleted/modified
     * The attributes may be in human readable form of OID form.
     */
    private Set<String> fractionalAllClassesAttributes = new HashSet<String>();
 
    /**
     * Base DN the fractional configuration is for.
     */
    private final DN baseDN;
 
    /**
     * Constructs a new fractional configuration object.
     * @param baseDN The base DN the object is for.
     */
    private FractionalConfig(DN baseDN)
    {
      this.baseDN = baseDN;
    }
 
    /**
     * Getter for fractional.
     * @return True if the configuration has fractional enabled
     */
    boolean isFractional()
    {
      return fractional;
    }
 
    /**
     * Set the fractional parameter.
     * @param fractional The fractional parameter
     */
    private void setFractional(boolean fractional)
    {
      this.fractional = fractional;
    }
 
    /**
     * Getter for fractionalExclusive.
     * @return True if the configuration has fractional exclusive enabled
     */
    boolean isFractionalExclusive()
    {
      return fractionalExclusive;
    }
 
    /**
     * Set the fractionalExclusive parameter.
     * @param fractionalExclusive The fractionalExclusive parameter
     */
    private void setFractionalExclusive(boolean fractionalExclusive)
    {
      this.fractionalExclusive = fractionalExclusive;
    }
 
    /**
     * Getter for fractionalSpecificClassesAttributes attribute.
     * @return The fractionalSpecificClassesAttributes attribute.
     */
    Map<String, Set<String>> getFractionalSpecificClassesAttributes()
    {
      return fractionalSpecificClassesAttributes;
    }
 
    /**
     * Set the fractionalSpecificClassesAttributes parameter.
     * @param fractionalSpecificClassesAttributes The
     * fractionalSpecificClassesAttributes parameter to set.
     */
    private void setFractionalSpecificClassesAttributes(
        Map<String, Set<String>> fractionalSpecificClassesAttributes)
    {
      this.fractionalSpecificClassesAttributes =
        fractionalSpecificClassesAttributes;
    }
 
    /**
     * Getter for fractionalSpecificClassesAttributes attribute.
     * @return The fractionalSpecificClassesAttributes attribute.
     */
    Set<String> getFractionalAllClassesAttributes()
    {
      return fractionalAllClassesAttributes;
    }
 
    /**
     * Set the fractionalAllClassesAttributes parameter.
     * @param fractionalAllClassesAttributes The
     * fractionalSpecificClassesAttributes parameter to set.
     */
    private void setFractionalAllClassesAttributes(
        Set<String> fractionalAllClassesAttributes)
    {
      this.fractionalAllClassesAttributes = fractionalAllClassesAttributes;
    }
 
    /**
     * Getter for the base baseDN.
     * @return The baseDN attribute.
     */
    DN getBaseDn()
    {
      return baseDN;
    }
 
    /**
     * Extract the fractional configuration from the passed domain configuration
     * entry.
     * @param configuration The configuration object
     * @return The fractional replication configuration.
     * @throws ConfigException If an error occurred.
     */
    static FractionalConfig toFractionalConfig(
      ReplicationDomainCfg configuration) throws ConfigException
    {
      // Prepare fractional configuration variables to parse
      Iterator<String> exclIt = configuration.getFractionalExclude().iterator();
      Iterator<String> inclIt = configuration.getFractionalInclude().iterator();
 
      // Get potentially new fractional configuration
      Map<String, Set<String>> newFractionalSpecificClassesAttributes =
          new HashMap<String, Set<String>>();
      Set<String> newFractionalAllClassesAttributes = new HashSet<String>();
 
      int newFractionalMode = parseFractionalConfig(exclIt, inclIt,
        newFractionalSpecificClassesAttributes,
        newFractionalAllClassesAttributes);
 
      // Create matching parsed config object
      FractionalConfig result = new FractionalConfig(configuration.getBaseDN());
      switch (newFractionalMode)
      {
        case NOT_FRACTIONAL:
          result.setFractional(false);
          result.setFractionalExclusive(true);
          break;
        case EXCLUSIVE_FRACTIONAL:
        case INCLUSIVE_FRACTIONAL:
          result.setFractional(true);
          result.setFractionalExclusive(
              newFractionalMode == EXCLUSIVE_FRACTIONAL);
          break;
      }
      result.setFractionalSpecificClassesAttributes(
        newFractionalSpecificClassesAttributes);
      result.setFractionalAllClassesAttributes(
        newFractionalAllClassesAttributes);
      return result;
    }
 
    /**
     * Parses a fractional replication configuration, filling the empty passed
     * variables and returning the used fractional mode. The 2 passed variables
     * to fill should be initialized (not null) and empty.
     * @param exclIt The list of fractional exclude configuration values (may be
     *               null)
     * @param inclIt The list of fractional include configuration values (may be
     *               null)
     * @param fractionalSpecificClassesAttributes An empty map to be filled with
     *        what is read from the fractional configuration properties.
     * @param fractionalAllClassesAttributes An empty list to be filled with
     *        what is read from the fractional configuration properties.
     * @return the fractional mode deduced from the passed configuration:
     *         not fractional, exclusive fractional or inclusive fractional
     *         modes
     */
    private static int parseFractionalConfig (
      Iterator<String> exclIt, Iterator<String> inclIt,
      Map<String, Set<String>> fractionalSpecificClassesAttributes,
      Set<String> fractionalAllClassesAttributes) throws ConfigException
    {
      // Determine if fractional-exclude or fractional-include property is used:
      // only one of them is allowed
      int fractionalMode;
      Iterator<String> iterator;
      if (exclIt != null && exclIt.hasNext())
      {
        if (inclIt != null && inclIt.hasNext())
        {
          throw new ConfigException(
            NOTE_ERR_FRACTIONAL_CONFIG_BOTH_MODES.get());
        }
 
        fractionalMode = EXCLUSIVE_FRACTIONAL;
        iterator = exclIt;
      }
      else
      {
        if (inclIt != null && inclIt.hasNext())
        {
          fractionalMode = INCLUSIVE_FRACTIONAL;
          iterator = inclIt;
        }
        else
        {
          return NOT_FRACTIONAL;
        }
      }
 
      while (iterator.hasNext())
      {
        // Parse a value with the form class:attr1,attr2...
        // or *:attr1,attr2...
        String fractCfgStr = iterator.next();
        StringTokenizer st = new StringTokenizer(fractCfgStr, ":");
        int nTokens = st.countTokens();
        if (nTokens < 2)
        {
          throw new ConfigException(NOTE_ERR_FRACTIONAL_CONFIG_WRONG_FORMAT.
            get(fractCfgStr));
        }
        // Get the class name
        String classNameLower = st.nextToken().toLowerCase();
        boolean allClasses = "*".equals(classNameLower);
        // Get the attributes
        String attributes = st.nextToken();
        st = new StringTokenizer(attributes, ",");
        while (st.hasMoreTokens())
        {
          String attrNameLower = st.nextToken().toLowerCase();
          // Store attribute in the appropriate variable
          if (allClasses)
          {
            fractionalAllClassesAttributes.add(attrNameLower);
          }
          else
          {
            Set<String> attrList =
                fractionalSpecificClassesAttributes.get(classNameLower);
            if (attrList == null)
            {
              attrList = new LinkedHashSet<String>();
              fractionalSpecificClassesAttributes.put(classNameLower, attrList);
            }
            attrList.add(attrNameLower);
          }
        }
      }
      return fractionalMode;
    }
 
    /** Return type of the parseFractionalConfig method. */
    private static final int NOT_FRACTIONAL = 0;
    private static final int EXCLUSIVE_FRACTIONAL = 1;
    private static final int INCLUSIVE_FRACTIONAL = 2;
 
    /**
     * Get an integer representation of the domain fractional configuration.
     * @return An integer representation of the domain fractional configuration.
     */
    private int fractionalConfigToInt()
    {
      if (!fractional)
      {
        return NOT_FRACTIONAL;
      }
      else if (fractionalExclusive)
      {
        return EXCLUSIVE_FRACTIONAL;
      }
      return INCLUSIVE_FRACTIONAL;
    }
 
    /**
     * Compare 2 fractional replication configurations and returns true if they
     * are equivalent.
     * @param cfg1 First fractional configuration
     * @param cfg2 Second fractional configuration
     * @return True if both configurations are equivalent.
     * @throws ConfigException If some classes or attributes could not be
     * retrieved from the schema.
     */
    private static boolean isFractionalConfigEquivalent(FractionalConfig cfg1,
        FractionalConfig cfg2) throws ConfigException
    {
      // Compare base DNs just to be consistent
      if (!cfg1.getBaseDn().equals(cfg2.getBaseDn()))
      {
        return false;
      }
 
      // Compare modes
      if (cfg1.isFractional() != cfg2.isFractional()
          || cfg1.isFractionalExclusive() != cfg2.isFractionalExclusive())
      {
        return false;
      }
 
      // Compare all classes attributes
      Set<String> allClassesAttrs1 = cfg1.getFractionalAllClassesAttributes();
      Set<String> allClassesAttrs2 = cfg2.getFractionalAllClassesAttributes();
      if (!areAttributesEquivalent(allClassesAttrs1, allClassesAttrs2))
      {
        return false;
      }
 
      // Compare specific classes attributes
      Map<String, Set<String>> specificClassesAttrs1 =
          cfg1.getFractionalSpecificClassesAttributes();
      Map<String, Set<String>> specificClassesAttrs2 =
          cfg2.getFractionalSpecificClassesAttributes();
      if (specificClassesAttrs1.size() != specificClassesAttrs2.size())
      {
        return false;
      }
 
      /*
       * Check consistency of specific classes attributes
       *
       * For each class in specificClassesAttributes1, check that the attribute
       * list is equivalent to specificClassesAttributes2 attribute list
       */
      Schema schema = DirectoryServer.getSchema();
      for (String className1 : specificClassesAttrs1.keySet())
      {
        // Get class from specificClassesAttributes1
        ObjectClass objectClass1 = schema.getObjectClass(className1);
        if (objectClass1 == null)
        {
          throw new ConfigException(
            NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_OBJECT_CLASS.get(className1));
        }
 
        // Look for matching one in specificClassesAttributes2
        boolean foundClass = false;
        for (String className2 : specificClassesAttrs2.keySet())
        {
          ObjectClass objectClass2 = schema.getObjectClass(className2);
          if (objectClass2 == null)
          {
            throw new ConfigException(
              NOTE_ERR_FRACTIONAL_CONFIG_UNKNOWN_OBJECT_CLASS.get(className2));
          }
          if (objectClass1.equals(objectClass2))
          {
            foundClass = true;
            // Now compare the 2 attribute lists
            Set<String> attributes1 = specificClassesAttrs1.get(className1);
            Set<String> attributes2 = specificClassesAttrs2.get(className2);
            if (!areAttributesEquivalent(attributes1, attributes2))
            {
              return false;
            }
            break;
          }
        }
        // Found matching class ?
        if (!foundClass)
        {
          return false;
        }
      }
 
      return true;
    }
  }
 
  /**
   * Specifies whether this domain is enabled/disabled regarding the ECL.
   * @return enabled/disabled for the ECL.
   */
  boolean isECLEnabled()
  {
    return this.eclDomain.isEnabled();
  }
 
  /**
   * Return the minimum time (in ms) that the domain keeps the historical
   * information necessary to solve conflicts.
   *
   * @return the purge delay.
   */
  long getHistoricalPurgeDelay()
  {
    return config.getConflictsHistoricalPurgeDelay() * 60 * 1000;
  }
 
  /**
   * Check if the operation that just happened has cleared a conflict : Clearing
   * a conflict happens if the operation has freed a DN for which another entry
   * was in conflict.
   * <p>
   * Steps:
   * <ul>
   * <li>get the DN freed by a DELETE or MODRDN op</li>
   * <li>search for entries put in the conflict space (dn=entryUUID'+'....)
   * because the expected DN was not available (ds-sync-conflict=expected DN)
   * </li>
   * <li>retain the entry with the oldest conflict</li>
   * <li>rename this entry with the freedDN as it was expected originally</li>
   * </ul>
   *
   * @param task
   *          the task raising this purge.
   * @param endDate
   *          the date to stop this task whether the job is done or not.
   * @throws DirectoryException
   *           when an exception happens.
   */
  public void purgeConflictsHistorical(PurgeConflictsHistoricalTask task,
      long endDate) throws DirectoryException
  {
     logger.trace("[PURGE] purgeConflictsHistorical "
         + "on domain: " + getBaseDN()
         + "endDate:" + new Date(endDate)
         + "lastCSNPurgedFromHist: "
         + lastCSNPurgedFromHist.toStringUI());
 
    String filter = "(" + HISTORICAL_ATTRIBUTE_NAME + ">=dummy:" + lastCSNPurgedFromHist + ")";
    SearchRequest request = Requests.newSearchRequest(getBaseDN(), SearchScope.WHOLE_SUBTREE, filter)
        .addAttribute(USER_AND_REPL_OPERATIONAL_ATTRS);
    InternalSearchOperation searchOp = conn.processSearch(request);
 
     int count = 0;
     if (task != null)
     {
       task.setProgressStats(lastCSNPurgedFromHist, count);
     }
 
     for (SearchResultEntry entry : searchOp.getSearchEntries())
     {
       long maxTimeToRun = endDate - TimeThread.getTime();
       if (maxTimeToRun < 0)
       {
        throw new DirectoryException(ResultCode.ADMIN_LIMIT_EXCEEDED,
            LocalizableMessage.raw(" end date reached"));
       }
 
       EntryHistorical entryHist = EntryHistorical.newInstanceFromEntry(entry);
       lastCSNPurgedFromHist = entryHist.getOldestCSN();
       entryHist.setPurgeDelay(getHistoricalPurgeDelay());
       Attribute attr = entryHist.encodeAndPurge();
       count += entryHist.getLastPurgedValuesCount();
       List<Modification> mods =
           newList(new Modification(ModificationType.REPLACE, attr));
 
       ModifyOperation newOp = new ModifyOperationBasis(
           conn, nextOperationID(), nextMessageID(), new ArrayList<Control>(0),
           entry.getName(), mods);
       runAsSynchronizedOperation(newOp);
 
       if (newOp.getResultCode() != ResultCode.SUCCESS)
       {
         // Log information for the repair tool.
         logger.error(ERR_CANNOT_ADD_CONFLICT_ATTRIBUTE, newOp, newOp.getResultCode());
       }
       else if (task != null)
       {
         task.setProgressStats(lastCSNPurgedFromHist, count);
       }
     }
  }
 
}