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

Jean-Noël Rouvignac
25.26.2016 9a300db9864e8da7187930315a9784369ace9c74
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
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions Copyright [year] [name of copyright owner]".
 *
 * Portions Copyright 2014 The Apache Software Foundation
 * Copyright 2015-2016 ForgeRock AS.
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.opends.server.backends.pluggable;
 
import static java.nio.channels.FileChannel.*;
import static java.nio.file.StandardOpenOption.*;
import static org.forgerock.util.Utils.*;
import static org.opends.messages.BackendMessages.*;
import static org.opends.server.util.DynamicConstants.*;
import static org.opends.server.util.StaticUtils.*;
import static org.forgerock.opendj.ldap.ResultCode.*;
 
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.SortedSet;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.UUID;
import java.util.WeakHashMap;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
 
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.config.server.ConfigException;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.schema.MatchingRule;
import org.forgerock.opendj.ldap.schema.UnknownSchemaElementException;
import org.forgerock.opendj.ldap.spi.Indexer;
import org.forgerock.opendj.server.config.meta.BackendIndexCfgDefn.IndexType;
import org.forgerock.opendj.server.config.server.BackendIndexCfg;
import org.forgerock.opendj.server.config.server.PluggableBackendCfg;
import org.forgerock.util.Reject;
import org.forgerock.util.Utils;
import org.forgerock.util.promise.PromiseImpl;
import org.opends.server.api.CompressedSchema;
import org.opends.server.backends.RebuildConfig;
import org.opends.server.backends.pluggable.AttributeIndex.MatchingRuleIndex;
import org.opends.server.backends.pluggable.CursorTransformer.SequentialCursorAdapter;
import org.opends.server.backends.pluggable.DN2ID.TreeVisitor;
import org.opends.server.backends.pluggable.ImportLDIFReader.EntryInformation;
import org.opends.server.backends.pluggable.OnDiskMergeImporter.BufferPool.MemoryBuffer;
import org.opends.server.backends.pluggable.spi.Cursor;
import org.opends.server.backends.pluggable.spi.Importer;
import org.opends.server.backends.pluggable.spi.ReadOperation;
import org.opends.server.backends.pluggable.spi.ReadableTransaction;
import org.opends.server.backends.pluggable.spi.SequentialCursor;
import org.opends.server.backends.pluggable.spi.StorageRuntimeException;
import org.opends.server.backends.pluggable.spi.TreeName;
import org.opends.server.backends.pluggable.spi.UpdateFunction;
import org.opends.server.backends.pluggable.spi.WriteOperation;
import org.opends.server.backends.pluggable.spi.WriteableTransaction;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ServerContext;
import org.opends.server.schema.SchemaConstants;
import org.opends.server.types.DirectoryException;
import org.opends.server.types.Entry;
import org.opends.server.types.InitializationException;
import org.opends.server.types.LDIFImportConfig;
import org.opends.server.types.LDIFImportResult;
 
import com.forgerock.opendj.util.OperatingSystem;
import com.forgerock.opendj.util.PackedLong;
import com.forgerock.opendj.util.Predicate;
 
import net.jcip.annotations.NotThreadSafe;
 
/**
 * Imports LDIF data contained in files into the database. Because of the B-Tree structure used in backend, import is
 * faster when records are inserted in ascending order. This prevents node locking/re-writing due to B-Tree inner nodes
 * split. This is why import is performed in two phases: the first phase encode and sort all records while the second
 * phase copy the sorted records into the database. Entries are read from an LDIF file by the {@link ImportLDIFReader}.
 * Then, each entry are optionally validated and finally imported into a {@link Chunk} by the {@link EntryContainer}
 * using a {@link PhaseOneWriteableTransaction}. Once all entries have been processed,
 * {@link PhaseOneWriteableTransaction#getChunks()} get all the chunks which will be copied into the database
 * concurrently using tasks created by the {@link ImporterTaskFactory}.
 */
final class OnDiskMergeImporter
{
  private static final String DEFAULT_TMP_DIR = "import-tmp";
 
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /**
   * Shim that allows properly constructing an {@link OnDiskMergeImporter} without polluting {@link ImportStrategy} and
   * {@link RootContainer} with this importer inner workings.
   */
  static class StrategyImpl implements ImportStrategy
  {
    private static final String PHASE1_REBUILDER_THREAD_NAME = "PHASE1-REBUILDER-%d";
 
    private static final String PHASE2_REBUILDER_THREAD_NAME = "PHASE2-REBUILDER-%d";
 
    private static final String PHASE1_IMPORTER_THREAD_NAME = "PHASE1-IMPORTER-%d";
 
    private static final String PHASE2_IMPORTER_THREAD_NAME = "PHASE2-IMPORTER-%d";
 
    private static final String SORTER_THREAD_NAME = "PHASE1-SORTER-%d";
 
    /** Small heap threshold used to give more memory to JVM to attempt OOM errors. */
    private static final int SMALL_HEAP_SIZE = 256 * MB;
 
    private static final Predicate<Tree, Void> IS_VLV = new Predicate<Tree, Void>()
    {
      @Override
      public boolean matches(Tree value, Void p)
      {
        return value.getName().getIndexId().startsWith("vlv.");
      }
    };
 
    private final ServerContext serverContext;
    private final RootContainer rootContainer;
    private final PluggableBackendCfg backendCfg;
 
    StrategyImpl(final ServerContext serverContext, final RootContainer rootContainer,
        final PluggableBackendCfg backendCfg)
    {
      this.serverContext = serverContext;
      this.rootContainer = rootContainer;
      this.backendCfg = backendCfg;
    }
 
    @Override
    public LDIFImportResult importLDIF(LDIFImportConfig importConfig)
        throws InitializationException, ConfigException, InterruptedException, ExecutionException
    {
      logger.info(NOTE_IMPORT_STARTING, DirectoryServer.getVersionString(), BUILD_ID, REVISION);
 
      final long startTime = System.currentTimeMillis();
      final int maxThreadCount = importConfig.getThreadCount() == 0
          ? getDefaultNumberOfThread()
          : importConfig.getThreadCount();
      final int nbBuffersPerThread = 2 * getIndexCount();
      try (final BufferPool bufferPool = newBufferPool(maxThreadCount, nbBuffersPerThread))
      {
        final int threadCount = bufferPool.size() / nbBuffersPerThread;
        logger.info(NOTE_IMPORT_THREAD_COUNT, threadCount);
        final OnDiskMergeImporter importer;
        final ExecutorService sorter =
            Executors.newFixedThreadPool(threadCount, newThreadFactory(null, SORTER_THREAD_NAME, true));
        try (final LDIFReaderSource source =
            new LDIFReaderSource(rootContainer, importConfig, PHASE1_IMPORTER_THREAD_NAME, threadCount))
        {
          final File tempDir = prepareTempDir(backendCfg, importConfig.getTmpDirectory());
          try (final Importer dbStorage = rootContainer.getStorage().startImport())
          {
            final Collection<EntryContainer> entryContainers = rootContainer.getEntryContainers();
            final AbstractTwoPhaseImportStrategy importStrategy =
                new ExternalSortAndImportStrategy(entryContainers, dbStorage, tempDir, bufferPool, sorter);
            importer = new OnDiskMergeImporter(PHASE2_IMPORTER_THREAD_NAME, importStrategy);
            importer.doImport(source);
          }
          finally
          {
            sorter.shutdownNow();
            if (OperatingSystem.isWindows())
            {
              // Try to force the JVM to close mmap()ed file so that they can be deleted.
              // (see http://bugs.java.com/view_bug.do?bug_id=4715154)
              System.gc();
              Runtime.getRuntime().runFinalization();
            }
            recursiveDelete(tempDir);
          }
          logger.info(NOTE_IMPORT_PHASE_STATS,
                      importer.getTotalTimeInMillis() / 1000,
                      importer.getPhaseOneTimeInMillis() / 1000,
                      importer.getPhaseTwoTimeInMillis() / 1000);
 
          final long importTime = System.currentTimeMillis() - startTime;
          float rate = 0;
          if (importTime > 0)
          {
            rate = 1000f * source.getEntriesRead() / importTime;
          }
          logger.info(NOTE_IMPORT_FINAL_STATUS, source.getEntriesRead(), importer.getImportedCount(), source
              .getEntriesIgnored(), source.getEntriesRejected(), 0, importTime / 1000, rate);
          return new LDIFImportResult(source.getEntriesRead(), source.getEntriesRejected(), source.getEntriesIgnored());
        }
      }
      catch (IOException e)
      {
        throw new ExecutionException(e);
      }
    }
 
    private static int getDefaultNumberOfThread()
    {
      final int nbProcessors = Runtime.getRuntime().availableProcessors();
      return Math.max(2, DirectoryServer.isRunning() ? nbProcessors / 2 : nbProcessors);
    }
 
    private int getIndexCount() throws ConfigException
    {
      int indexCount = 2; // dn2id, dn2uri
      for (String indexName : backendCfg.listBackendIndexes())
      {
        final BackendIndexCfg index = backendCfg.getBackendIndex(indexName);
        final SortedSet<IndexType> types = index.getIndexType();
        if (types.contains(IndexType.EXTENSIBLE))
        {
          indexCount += types.size() - 1 + index.getIndexExtensibleMatchingRule().size();
        }
        else
        {
          indexCount += types.size();
        }
      }
      indexCount += backendCfg.listBackendVLVIndexes().length;
      return indexCount;
    }
 
    @Override
    public void rebuildIndex(final RebuildConfig rebuildConfig)
        throws InitializationException, ExecutionException, ConfigException, InterruptedException
    {
      final EntryContainer entryContainer = rootContainer.getEntryContainer(rebuildConfig.getBaseDN());
      final long totalEntries;
      try
      {
        totalEntries = rootContainer.getStorage().read(new ReadOperation<Long>()
        {
          @Override
          public Long run(ReadableTransaction txn) throws Exception
          {
            return entryContainer.getID2Entry().getRecordCount(txn);
          }
        });
      }
      catch (Exception e)
      {
        throw new ExecutionException(e);
      }
 
      final Set<String> indexesToRebuild = selectIndexesToRebuild(entryContainer, rebuildConfig, totalEntries);
      if (rebuildConfig.isClearDegradedState())
      {
        clearDegradedState(entryContainer, indexesToRebuild);
        logger.info(NOTE_REBUILD_CLEARDEGRADEDSTATE_FINAL_STATUS, rebuildConfig.getRebuildList());
      }
      else
      {
        rebuildIndex(entryContainer, rebuildConfig.getTmpDirectory(), indexesToRebuild, totalEntries);
      }
    }
 
    private void clearDegradedState(final EntryContainer entryContainer, final Set<String> indexIds)
        throws ExecutionException
    {
      try
      {
        rootContainer.getStorage().write(new WriteOperation()
        {
          @Override
          public void run(WriteableTransaction txn)
          {
            visitIndexes(entryContainer, visitOnlyIndexes(indexIdIn(indexIds), setTrust(true, txn)));
          }
        });
      }
      catch (Exception e)
      {
        throw new ExecutionException(e);
      }
    }
 
    private void rebuildIndex(EntryContainer entryContainer, String tmpDirectory, Set<String> indexesToRebuild,
        long totalEntries) throws InitializationException, ConfigException, InterruptedException, ExecutionException
    {
      if (indexesToRebuild.isEmpty())
      {
        logger.info(NOTE_REBUILD_NOTHING_TO_REBUILD);
        return;
      }
      rootContainer.getStorage().close();
      final int nbBuffersPerThread = 2 * indexesToRebuild.size();
      try (final BufferPool bufferPool = newBufferPool(getDefaultNumberOfThread(), nbBuffersPerThread))
      {
        final int threadCount = bufferPool.size() / nbBuffersPerThread;
        final ExecutorService sorter =
            Executors.newFixedThreadPool(threadCount, newThreadFactory(null, SORTER_THREAD_NAME, true));
 
        final OnDiskMergeImporter importer;
        final File tempDir = prepareTempDir(backendCfg, tmpDirectory);
        try (final Importer dbStorage = rootContainer.getStorage().startImport())
        {
          final AbstractTwoPhaseImportStrategy strategy =
              new RebuildIndexStrategy(
                  rootContainer.getEntryContainers(), dbStorage, tempDir, bufferPool, sorter, indexesToRebuild);
 
          importer = new OnDiskMergeImporter(PHASE2_REBUILDER_THREAD_NAME, strategy);
          importer.doImport(new ID2EntrySource(entryContainer, dbStorage, PHASE1_REBUILDER_THREAD_NAME, threadCount,
              totalEntries));
        }
        finally
        {
          sorter.shutdown();
          recursiveDelete(tempDir);
        }
        final long totalTime = importer.getTotalTimeInMillis();
        final float rate = totalTime > 0 ? 1000f * importer.getImportedCount() / totalTime : 0;
        logger.info(NOTE_REBUILD_FINAL_STATUS, importer.getImportedCount(), totalTime / 1000, rate);
      }
    }
 
    /**
     * Try to allocate a {@link BufferPool} with a number of buffer in it being a multiple of {@code nbBuffers} in the
     * range [1, {@code maxThreadCount}] depending of the amount of memory available.
     */
    BufferPool newBufferPool(final int maxThreadCount, final int nbBuffers) throws InitializationException
    {
      final int initialThreadCount = maxThreadCount;
      final Long offheapMemorySize = backendCfg.getImportOffheapMemorySize();
      boolean useOffHeap = (offheapMemorySize != null && offheapMemorySize > 0);
      long memoryAvailable =
          useOffHeap ? offheapMemorySize.longValue() : calculateAvailableHeapMemoryForBuffersAfterGC();
      int threadCount = initialThreadCount;
      for (;;)
      {
        final int nbRequiredBuffers = threadCount * nbBuffers;
        try
        {
          return useOffHeap
              ? newOffHeapBufferPool(nbRequiredBuffers, memoryAvailable)
              : newHeapBufferPool(nbRequiredBuffers, memoryAvailable);
        }
        catch (InitializationException e)
        {
          if (threadCount > 1)
          {
            // Retry using less buffer by reducing the number of importer threads.
            threadCount--;
          }
          else if (useOffHeap)
          {
            // Retry using on-heap buffer
            useOffHeap = false;
            memoryAvailable = calculateAvailableHeapMemoryForBuffersAfterGC();
            threadCount = initialThreadCount;
          }
          else
          {
            throw e;
          }
        }
      }
    }
 
    private BufferPool newOffHeapBufferPool(final int nbBuffers, long offHeapMemoryAvailable)
        throws InitializationException
    {
      // Try off-heap direct buffer
      logger.info(NOTE_IMPORT_LDIF_TOT_MEM_BUF, offHeapMemoryAvailable, nbBuffers);
      int bufferSize = (int) (offHeapMemoryAvailable / nbBuffers);
      while (bufferSize > MIN_BUFFER_SIZE)
      {
        BufferPool pool = null;
        try
        {
          pool = new BufferPool(nbBuffers, bufferSize, true);
          final long usedOffHeapMemory = (((long) bufferSize) * nbBuffers) / MB;
          logger.info(NOTE_IMPORT_LDIF_OFFHEAP_MEM_BUF_INFO, DB_CACHE_SIZE / MB, usedOffHeapMemory, nbBuffers,
              bufferSize / KB);
          return pool;
        }
        catch (OutOfMemoryError e)
        {
          bufferSize /= 2;
          closeSilently(pool);
          pool = null;
        }
      }
      throw new InitializationException(ERR_IMPORT_LDIF_LACK_MEM.get(offHeapMemoryAvailable, nbBuffers
          * MIN_BUFFER_SIZE));
    }
 
    private BufferPool newHeapBufferPool(final int nbBuffers, final long heapMemoryAvailable)
        throws InitializationException
    {
      final long minimumRequiredMemory = nbBuffers * MIN_BUFFER_SIZE + DB_CACHE_SIZE + REQUIRED_FREE_MEMORY;
      if (heapMemoryAvailable < minimumRequiredMemory)
      {
        // Not enough memory.
        throw new InitializationException(ERR_IMPORT_LDIF_LACK_MEM.get(heapMemoryAvailable, minimumRequiredMemory));
      }
      logger.info(NOTE_IMPORT_LDIF_TOT_MEM_BUF, heapMemoryAvailable, nbBuffers);
      final long buffersMemory = heapMemoryAvailable - DB_CACHE_SIZE - REQUIRED_FREE_MEMORY;
      final int bufferSize = Math.min(((int) (buffersMemory / nbBuffers)), MAX_BUFFER_SIZE);
      logger.info(NOTE_IMPORT_LDIF_DB_MEM_BUF_INFO, DB_CACHE_SIZE, bufferSize);
      return new BufferPool(nbBuffers, bufferSize, false);
    }
 
    private final Set<String> selectIndexesToRebuild(final EntryContainer entryContainer,
        final RebuildConfig rebuildConfig, final long totalEntries) throws InitializationException
    {
      final SelectIndexName selector = new SelectIndexName();
      final Set<String> indexesToRebuild;
      switch (rebuildConfig.getRebuildMode())
      {
      case ALL:
        visitIndexes(entryContainer, selector);
        indexesToRebuild = selector.getSelectedIndexNames();
        logger.info(NOTE_REBUILD_ALL_START, totalEntries);
        break;
      case DEGRADED:
        visitIndexes(entryContainer, visitOnlyDegraded(selector));
        indexesToRebuild = selector.getSelectedIndexNames();
        logger.info(NOTE_REBUILD_DEGRADED_START, totalEntries);
        break;
      case USER_DEFINED:
        // User defined format is (attributeType)((.indexType)|(.matchingRule))
        indexesToRebuild = expandIndexNames(entryContainer, rebuildConfig.getRebuildList());
        if (!rebuildConfig.isClearDegradedState())
        {
          logger.info(NOTE_REBUILD_START, Utils.joinAsString(", ", indexesToRebuild), totalEntries);
        }
        break;
      default:
        throw new UnsupportedOperationException("Unsupported rebuild mode " + rebuildConfig.getRebuildMode());
      }
      if (indexesToRebuild.contains(entryContainer.getDN2ID().getName().getIndexId()))
      {
        // Always rebuild id2childrencount with dn2id.
        indexesToRebuild.add(entryContainer.getID2ChildrenCount().getName().getIndexId());
      }
      return indexesToRebuild;
    }
 
    /**
     * Translate (attributeType)((.indexType)|(.matchingRuleNameOrOid)) into attributeType.matchingRuleOid index name.
     *
     * @throws InitializationException
     *           if rebuildList contains an invalid/non-existing attribute/index name.
     */
    final Set<String> expandIndexNames(final EntryContainer entryContainer, final Collection<String> rebuildList)
        throws InitializationException
   {
      final Set<String> indexNames = new HashSet<>();
      for (final String name : rebuildList)
      {
        // Name could be a (attributeType)((.indexType)|(.matchingRule))
        // Add a trailing "." to ensure that resulting parts has always at least two parts.
        final String parts[] = (name + ".*").split("\\.");
 
        // Is name represents all VLV index ?
        final SelectIndexName selector = new SelectIndexName();
        if (parts[0].equalsIgnoreCase("vlv") && isWildcard(parts[1]))
        {
          visitIndexes(entryContainer, visitOnlyIndexes(IS_VLV, selector));
        }
        else
        {
          // Is name a fully qualified index id ? i.e: "dn2id", "sn.caseIgnoreMatch:6"
          visitIndexes(entryContainer, visitOnlyIndexes(indexIdIn(Arrays.asList(name)), selector));
        }
 
        if (selector.getSelectedIndexNames().isEmpty())
        {
          if (isWildcard(parts[1]))
          {
            // Name is "attributeType", "attributeType." or "attributeType.*"
            visitAttributeIndexes(entryContainer.getAttributeIndexes(), attributeTypeIs(parts[0]), selector);
            if (selector.getSelectedIndexNames().isEmpty())
            {
              throw new InitializationException(ERR_ATTRIBUTE_INDEX_NOT_CONFIGURED.get(name));
            }
          }
          else
          {
            final Collection<Predicate<MatchingRuleIndex, AttributeIndex>> attributeIndexFilters = new ArrayList<>();
            if (!isWildcard(parts[0]))
            {
              // Name is attributeType.matchingRule or attributeType.indexType
              attributeIndexFilters.add(attributeTypeIs(parts[0]));
            }
            // Filter on index type or matching rule.
            final IndexType indexType = indexTypeForNameOrNull(parts[1]);
            if (indexType == null)
            {
              // Name contains a matching rule
              try
              {
                attributeIndexFilters.add(matchingRuleIs(serverContext.getSchema().getMatchingRule(parts[1])));
              }
              catch (UnknownSchemaElementException usee)
              {
                throw new InitializationException(usee.getMessageObject(), usee);
              }
 
              if (parts[1].equalsIgnoreCase(SchemaConstants.EMR_DN_NAME))
              {
                indexNames.add(entryContainer.getDN2ID().getName().getIndexId());
                indexNames.add(entryContainer.getDN2URI().getName().getIndexId());
              }
            }
            else
            {
              // Name contains an index type
              attributeIndexFilters.add(indexTypeIs(indexType));
            }
            visitAttributeIndexes(entryContainer.getAttributeIndexes(), matchingAllOf(attributeIndexFilters), selector);
          }
        }
        indexNames.addAll(selector.getSelectedIndexNames());
      }
      return indexNames;
    }
 
    private static boolean isWildcard(final String part)
    {
      return part.isEmpty() || "*".equals(part);
    }
 
    /**
     * Retrieves the index type for the specified name, or {@code null} if there is no such index type.
     */
    private static IndexType indexTypeForNameOrNull(final String indexName)
    {
      for (final IndexType type : IndexType.values())
      {
        if (type.name().equalsIgnoreCase(indexName))
        {
          return type;
        }
      }
      return null;
    }
 
    private static File prepareTempDir(PluggableBackendCfg backendCfg, String tmpDirectory)
        throws InitializationException
    {
      final File tempDir =
          new File(getFileForPath(tmpDirectory != null ? tmpDirectory : DEFAULT_TMP_DIR), backendCfg.getBackendId());
      recursiveDelete(tempDir);
      if (!tempDir.exists() && !tempDir.mkdirs())
      {
        throw new InitializationException(ERR_IMPORT_CREATE_TMPDIR_ERROR.get(tempDir));
      }
      return tempDir;
    }
 
    /**
     * Calculates the amount of available memory which can be used by this import, taking into account whether
     * the import is running offline or online as a task.
     */
    private long calculateAvailableHeapMemoryForBuffersAfterGC()
    {
      final Runtime runTime = Runtime.getRuntime();
      runTime.gc();
      runTime.gc();
 
      // First try calculation based on oldgen size
      final List<MemoryPoolMXBean> mpools = ManagementFactory.getMemoryPoolMXBeans();
      for (final MemoryPoolMXBean mpool : mpools)
      {
        final MemoryUsage usage = mpool.getUsage();
        if (usage != null && mpool.getName().endsWith("Old Gen") && usage.getMax() > 0)
        {
          final long max = usage.getMax();
          return (max > SMALL_HEAP_SIZE ? (max * 90 / 100) : (max * 70 / 100));
        }
      }
      // Fall back to 40% of overall heap size (no need to do gc() again).
      return (runTime.freeMemory() + (runTime.maxMemory() - runTime.totalMemory())) * 40 / 100;
    }
  }
 
  /** Source of LDAP {@link Entry}s to process. */
  private interface Source extends Closeable
  {
    /** Process {@link Entry}s extracted from a {@link Source}. */
    interface EntryProcessor
    {
      void processEntry(EntryContainer container, EntryID entryID, Entry entry) throws Exception;
    }
 
    void processAllEntries(EntryProcessor processor) throws InterruptedException, ExecutionException;
 
    boolean isCancelled();
  }
 
  /** Extract LDAP {@link Entry}s from an LDIF file. */
  private static final class LDIFReaderSource implements Source
  {
    private static final String PHASE1_REPORTER_THREAD_NAME = "PHASE1-REPORTER-%d";
 
    private final Map<DN, EntryContainer> entryContainers;
    private final LDIFImportConfig importConfig;
    private final ImportLDIFReader reader;
    private final ExecutorService executor;
    private final int nbThreads;
 
    LDIFReaderSource(RootContainer rootContainer, LDIFImportConfig importConfig, String threadNameTemplate,
        int nbThreads) throws IOException
    {
      this.importConfig = importConfig;
      this.reader = new ImportLDIFReader(importConfig, rootContainer);
      this.entryContainers = new HashMap<>();
      for (EntryContainer container : rootContainer.getEntryContainers())
      {
        this.entryContainers.put(container.getBaseDN(), container);
      }
      this.nbThreads = nbThreads;
      this.executor = Executors.newFixedThreadPool(nbThreads, newThreadFactory(null, threadNameTemplate, true));
    }
 
    @Override
    public void close()
    {
      closeSilently(reader);
    }
 
    @Override
    public void processAllEntries(final EntryProcessor entryProcessor) throws InterruptedException, ExecutionException
    {
      final ScheduledExecutorService scheduler =
          Executors.newSingleThreadScheduledExecutor(newThreadFactory(null, PHASE1_REPORTER_THREAD_NAME, true));
      scheduler.scheduleAtFixedRate(new PhaseOneProgressReporter(), 10, 10, TimeUnit.SECONDS);
      final CompletionService<Void> completion = new ExecutorCompletionService<>(executor);
      try
      {
        for (int i = 0; i < nbThreads; i++)
        {
          completion.submit(new Callable<Void>()
          {
            @Override
            public Void call() throws Exception
            {
              checkThreadNotInterrupted();
              EntryInformation entryInfo;
              while ((entryInfo = reader.readEntry(entryContainers)) != null && !importConfig.isCancelled())
              {
                final EntryContainer entryContainer = entryInfo.getEntryContainer();
                final Entry entry = entryInfo.getEntry();
                final DN entryDN = entry.getName();
                final DN parentDN = entryContainer.getParentWithinBase(entryDN);
 
                if (parentDN != null)
                {
                  reader.waitIfPending(parentDN);
                }
                try
                {
                  entryProcessor.processEntry(entryContainer, entryInfo.getEntryID(), entry);
                }
                catch (DirectoryException e)
                {
                  reader.rejectEntry(entry, e.getMessageObject());
                }
                catch (Exception e)
                {
                  reader.rejectEntry(entry, ERR_EXECUTION_ERROR.get(e));
                }
                finally
                {
                  reader.removePending(entry.getName());
                }
                checkThreadNotInterrupted();
              }
              return null;
            }
          });
        }
        waitTasksTermination(completion, nbThreads);
      }
      finally
      {
        scheduler.shutdown();
        executor.shutdown();
      }
    }
 
    long getEntriesRead()
    {
      return reader.getEntriesRead();
    }
 
    long getEntriesIgnored()
    {
      return reader.getEntriesIgnored();
    }
 
    long getEntriesRejected()
    {
      return reader.getEntriesRejected();
    }
 
    @Override
    public boolean isCancelled()
    {
      return importConfig.isCancelled();
    }
 
    /** This class reports progress of first phase of import processing at fixed intervals. */
    private final class PhaseOneProgressReporter extends TimerTask
    {
      /** The number of entries that had been read at the time of the previous progress report. */
      private long previousCount;
      /** The time in milliseconds of the previous progress report. */
      private long previousTime;
 
      /** Create a new import progress task. */
      public PhaseOneProgressReporter()
      {
        previousTime = System.currentTimeMillis();
      }
 
      /** The action to be performed by this timer task. */
      @Override
      public void run()
      {
        long entriesRead = reader.getEntriesRead();
        long entriesIgnored = reader.getEntriesIgnored();
        long entriesRejected = reader.getEntriesRejected();
        long deltaCount = entriesRead - previousCount;
 
        long latestTime = System.currentTimeMillis();
        long deltaTime = latestTime - previousTime;
        if (deltaTime == 0)
        {
          return;
        }
        float rate = 1000f * deltaCount / deltaTime;
        logger.info(NOTE_IMPORT_PROGRESS_REPORT, entriesRead, entriesIgnored, entriesRejected, rate);
        previousCount = entriesRead;
        previousTime = latestTime;
      }
    }
  }
 
  /** Extract LDAP {@link Entry}s from an existing database. */
  private static final class ID2EntrySource implements Source
  {
    private static final String PHASE1_REPORTER_THREAD_NAME = "REPORTER-%d";
 
    private final EntryContainer entryContainer;
    private final CompressedSchema schema;
    private final Importer importer;
    private final ExecutorService executor;
    private final long nbTotalEntries;
    private final AtomicLong nbEntriesProcessed = new AtomicLong();
    private volatile boolean interrupted;
 
    ID2EntrySource(EntryContainer entryContainer, Importer importer, String threadNameTemplate, int nbThread,
        long nbTotalEntries)
    {
      this.nbTotalEntries = nbTotalEntries;
      this.entryContainer = entryContainer;
      this.importer = importer;
      this.schema = entryContainer.getRootContainer().getCompressedSchema();
      // by default (unfortunately) the ThreadPoolExecutor will throw an exception when queue is full.
      this.executor =
          new ThreadPoolExecutor(nbThread, nbThread, 0, TimeUnit.SECONDS,
              new ArrayBlockingQueue<Runnable>(nbThread * 2),
              newThreadFactory(null, threadNameTemplate, true),
              new RejectedExecutionHandler()
              {
                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)
                {
                  // this will block if the queue is full
                  try
                  {
                    executor.getQueue().put(r);
                  }
                  catch (InterruptedException e)
                  {
                  }
                }
              });
    }
 
    @Override
    public void close()
    {
      executor.shutdown();
    }
 
    @Override
    public void processAllEntries(final EntryProcessor entryProcessor) throws InterruptedException, ExecutionException
    {
      final ScheduledExecutorService scheduler =
          Executors.newSingleThreadScheduledExecutor(newThreadFactory(null, PHASE1_REPORTER_THREAD_NAME, true));
      scheduler.scheduleAtFixedRate(new PhaseOneProgressReporter(), 10, 10, TimeUnit.SECONDS);
      final PromiseImpl<Void, ExecutionException> promise = PromiseImpl.create();
      final ID2Entry id2Entry = entryContainer.getID2Entry();
      try (final SequentialCursor<ByteString, ByteString> cursor = importer.openCursor(id2Entry.getName()))
      {
        while (cursor.next())
        {
          final ByteString key = cursor.getKey();
          final ByteString value = cursor.getValue();
          executor.submit(new Runnable()
          {
            @Override
            public void run()
            {
              try
              {
                entryProcessor.processEntry(entryContainer,
                    new EntryID(key), id2Entry.entryFromDatabase(value, schema));
                nbEntriesProcessed.incrementAndGet();
              }
              catch (ExecutionException e)
              {
                interrupted = true;
                promise.handleException(e);
              }
              catch (Exception e)
              {
                interrupted = true;
                promise.handleException(new ExecutionException(e));
              }
            }
          });
        }
      }
      finally
      {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
        scheduler.shutdown();
      }
 
      // Forward exception if any
      if (promise.isDone())
      {
        promise.getOrThrow();
      }
    }
 
    @Override
    public boolean isCancelled()
    {
      return interrupted;
    }
 
    /** This class reports progress of first phase of import processing at fixed intervals. */
    private final class PhaseOneProgressReporter extends TimerTask
    {
      /** The number of entries that had been read at the time of the previous progress report. */
      private long previousCount;
      /** The time in milliseconds of the previous progress report. */
      private long previousTime;
 
      /** Create a new import progress task. */
      public PhaseOneProgressReporter()
      {
        previousTime = System.currentTimeMillis();
      }
 
      /** The action to be performed by this timer task. */
      @Override
      public void run()
      {
        long entriesRead = nbEntriesProcessed.get();
        long deltaCount = entriesRead - previousCount;
 
        long latestTime = System.currentTimeMillis();
        long deltaTime = latestTime - previousTime;
        final float progressPercent = nbTotalEntries > 0 ? Math.round((100f * entriesRead) / nbTotalEntries) : 0;
        if (deltaTime == 0)
        {
          return;
        }
        float rate = 1000f * deltaCount / deltaTime;
        logger.info(NOTE_REBUILD_PROGRESS_REPORT, progressPercent, entriesRead, nbTotalEntries, rate);
        previousCount = entriesRead;
        previousTime = latestTime;
      }
    }
  }
 
  /** Max size of phase one buffer. */
  private static final int MAX_BUFFER_SIZE = 4 * MB;
  /** Min size of phase one buffer. */
  private static final int MIN_BUFFER_SIZE = 32 * KB;
  /** DB cache size to use during import. */
  private static final int DB_CACHE_SIZE = 32 * MB;
  /** Required free memory for this importer. */
  private static final int REQUIRED_FREE_MEMORY = 50 * MB;
  /** LDIF reader. */
  /** Map of DNs to Suffix objects. */
  private final AbstractTwoPhaseImportStrategy importStrategy;
 
  private final String phase2ThreadNameTemplate;
  private final AtomicLong importedCount = new AtomicLong();
  private long phaseOneTimeMs;
  private long phaseTwoTimeMs;
 
  private OnDiskMergeImporter(String phase2ThreadNameTemplate, AbstractTwoPhaseImportStrategy importStrategy)
  {
    this.phase2ThreadNameTemplate = phase2ThreadNameTemplate;
    this.importStrategy = importStrategy;
  }
 
  private void doImport(final Source source) throws InterruptedException, ExecutionException
  {
    final long phaseOneStartTime = System.currentTimeMillis();
    final PhaseOneWriteableTransaction transaction = new PhaseOneWriteableTransaction(importStrategy);
    importedCount.set(0);
 
    final ConcurrentMap<EntryContainer, CountDownLatch> importedContainers = new ConcurrentHashMap<>();
 
    // Start phase one
    try
    {
      source.processAllEntries(new Source.EntryProcessor()
      {
        @Override
        public void processEntry(EntryContainer container, EntryID entryID, Entry entry) throws DirectoryException,
            InterruptedException
        {
          CountDownLatch latch = importedContainers.get(container);
          if (latch == null)
          {
            final CountDownLatch newLatch = new CountDownLatch(1);
            if (importedContainers.putIfAbsent(container, newLatch) == null)
            {
              try
              {
                importStrategy.beforePhaseOne(container);
              }
              finally
              {
                newLatch.countDown();
              }
            }
            latch = importedContainers.get(container);
          }
          latch.await();
 
          container.importEntry(transaction, entryID, entry);
          importedCount.incrementAndGet();
        }
      });
    }
    finally
    {
      closeSilently(source);
    }
    phaseOneTimeMs = System.currentTimeMillis() - phaseOneStartTime;
 
    if (source.isCancelled())
    {
      throw new InterruptedException("Import processing canceled.");
    }
 
    importStrategy.afterPhaseOne();
 
    // Start phase two
    final long phaseTwoStartTime = System.currentTimeMillis();
    try (final PhaseTwoProgressReporter progressReporter = new PhaseTwoProgressReporter())
    {
      final List<Callable<Void>> tasks = new ArrayList<>();
      final Set<String> importedBaseDNs = new HashSet<>();
      for (Map.Entry<TreeName, Chunk> treeChunk : transaction.getChunks().entrySet())
      {
        importedBaseDNs.add(treeChunk.getKey().getBaseDN());
        tasks.add(importStrategy.newPhaseTwoTask(treeChunk.getKey(), treeChunk.getValue(), progressReporter));
      }
      invokeParallel(phase2ThreadNameTemplate, tasks);
    }
 
    // Finish import
    for (EntryContainer entryContainer : importedContainers.keySet())
    {
      importStrategy.afterPhaseTwo(entryContainer);
    }
    phaseTwoTimeMs = System.currentTimeMillis() - phaseTwoStartTime;
  }
 
  public long getImportedCount()
  {
    return importedCount.get();
  }
 
  public long getPhaseOneTimeInMillis()
  {
    return phaseOneTimeMs;
  }
 
  public long getPhaseTwoTimeInMillis()
  {
    return phaseTwoTimeMs;
  }
 
  public long getTotalTimeInMillis()
  {
    return phaseOneTimeMs + phaseTwoTimeMs;
  }
 
  /** Create {@link Chunk} depending on the {@link TreeName}. */
  private interface ChunkFactory
  {
    Chunk newChunk(TreeName treeName) throws Exception;
  }
 
  /** Provides default behavior for two phases strategies. */
  private static abstract class AbstractTwoPhaseImportStrategy implements ChunkFactory
  {
    protected final Map<String, EntryContainer> entryContainers;
    protected final Executor sorter;
    protected final Importer importer;
    protected final BufferPool bufferPool;
    protected final File tempDir;
 
    AbstractTwoPhaseImportStrategy(Collection<EntryContainer> entryContainers, Importer importer, File tempDir,
        BufferPool bufferPool, Executor sorter)
    {
      this.entryContainers = new HashMap<>(entryContainers.size());
      for (EntryContainer container : entryContainers)
      {
        this.entryContainers.put(container.getTreePrefix(), container);
      }
      this.importer = importer;
      this.tempDir = tempDir;
      this.bufferPool = bufferPool;
      this.sorter = sorter;
    }
 
    void beforePhaseOne(EntryContainer entryContainer)
    {
      entryContainer.delete(asWriteableTransaction(importer));
      visitIndexes(entryContainer, setTrust(false, importer));
    }
 
    void afterPhaseOne()
    {
      closeSilently(bufferPool);
    }
 
    abstract Callable<Void> newPhaseTwoTask(TreeName treeName, Chunk source, PhaseTwoProgressReporter progressReporter);
 
    void afterPhaseTwo(EntryContainer entryContainer)
    {
      visitIndexes(entryContainer, setTrust(true, importer));
    }
 
    final Chunk newExternalSortChunk(TreeName treeName) throws Exception
    {
      return new ExternalSortChunk(tempDir, treeName.toString(), bufferPool,
          newPhaseOneCollector(entryContainers.get(treeName.getBaseDN()), treeName),
          newPhaseTwoCollector(entryContainers.get(treeName.getBaseDN()), treeName), sorter);
    }
 
    final Callable<Void> newChunkCopierTask(TreeName treeName, final Chunk source,
        PhaseTwoProgressReporter progressReporter)
    {
      return new ChunkCopierTask(progressReporter, source, treeName, importer);
    }
 
    final Callable<Void> newDN2IDImporterTask(TreeName treeName, final Chunk source,
        PhaseTwoProgressReporter progressReporter)
    {
      final EntryContainer entryContainer = entryContainers.get(treeName.getBaseDN());
      final ID2Entry id2entry = entryContainer.getID2Entry();
      final ID2ChildrenCount id2count = entryContainer.getID2ChildrenCount();
 
      return new DN2IDImporterTask(progressReporter, importer, tempDir, bufferPool, id2entry, entryContainer.getDN2ID(),
          source, id2count, newPhaseTwoCollector(entryContainer, id2count.getName()));
    }
 
    final Callable<Void> newVLVIndexImporterTask(VLVIndex vlvIndex, final Chunk source,
        PhaseTwoProgressReporter progressReporter)
    {
      return new VLVIndexImporterTask(progressReporter, source, vlvIndex, importer);
    }
 
    static final Callable<Void> newFlushTask(final Chunk source)
    {
      return new Callable<Void>()
      {
        @Override
        public Void call() throws Exception
        {
          checkThreadNotInterrupted();
          try (final MeteredCursor<ByteString, ByteString> unusued = source.flip())
          {
            // force flush
          }
          return null;
        }
      };
    }
  }
 
  /**
   * During phase one, import all {@link TreeName} (but id2entry) into a dedicated and temporary
   * {@link ExternalSortChunk} which will sort the keys in the ascending order. Phase two will copy the sorted keys into
   * the database using the {@link Importer}. id2entry database is imported directly into the database using
   * {@link ImporterToChunkAdapter}.
   */
  private static final class ExternalSortAndImportStrategy extends AbstractTwoPhaseImportStrategy
  {
    ExternalSortAndImportStrategy(Collection<EntryContainer> entryContainers, Importer importer, File tempDir,
        BufferPool bufferPool, Executor sorter)
    {
      super(entryContainers, importer, tempDir, bufferPool, sorter);
    }
 
    @Override
    public Chunk newChunk(TreeName treeName) throws Exception
    {
      if (isID2Entry(entryContainers.get(treeName.getBaseDN()), treeName))
      {
        return new MostlyOrderedChunk(asChunk(treeName, importer));
      }
      return newExternalSortChunk(treeName);
    }
 
    @Override
    public Callable<Void> newPhaseTwoTask(TreeName treeName, final Chunk source,
        PhaseTwoProgressReporter progressReporter)
    {
      final EntryContainer entryContainer = entryContainers.get(treeName.getBaseDN());
 
      if (isID2Entry(entryContainer, treeName))
      {
        return newFlushTask(source);
      }
      else if (isDN2ID(entryContainer, treeName))
      {
        return newDN2IDImporterTask(treeName, source, progressReporter);
      }
      else if (isVLVIndex(entryContainer, treeName))
      {
        return newVLVIndexImporterTask(getVLVIndex(entryContainer, treeName), source, progressReporter);
      }
      return newChunkCopierTask(treeName, source, progressReporter);
    }
  }
 
  /** Import only a specific indexes list while ignoring everything else. */
  private static final class RebuildIndexStrategy extends AbstractTwoPhaseImportStrategy
  {
    private final Set<String> indexesToRebuild;
 
    RebuildIndexStrategy(Collection<EntryContainer> entryContainers, Importer importer, File tempDir,
        BufferPool bufferPool, Executor sorter, Set<String> indexNames)
    {
      super(entryContainers, importer, tempDir, bufferPool, sorter);
      this.indexesToRebuild = indexNames;
    }
 
    @Override
    void beforePhaseOne(EntryContainer entryContainer)
    {
      visitIndexes(entryContainer, visitOnlyIndexes(indexIdIn(indexesToRebuild), setTrust(false, importer)));
      visitIndexes(entryContainer, visitOnlyIndexes(indexIdIn(indexesToRebuild), deleteDatabase(importer)));
    }
 
    @Override
    void afterPhaseTwo(EntryContainer entryContainer)
    {
      visitIndexes(entryContainer, visitOnlyIndexes(indexIdIn(indexesToRebuild), setTrust(true, importer)));
    }
 
    @Override
    public Chunk newChunk(TreeName treeName) throws Exception
    {
      if (indexesToRebuild.contains(treeName.getIndexId()))
      {
        return newExternalSortChunk(treeName);
      }
      // Ignore
      return nullChunk();
    }
 
    @Override
    public Callable<Void> newPhaseTwoTask(TreeName treeName, Chunk source, PhaseTwoProgressReporter progressReporter)
    {
      final EntryContainer entryContainer = entryContainers.get(treeName.getBaseDN());
 
      if (!indexesToRebuild.contains(treeName.getIndexId()))
      {
        // Do nothing (flush null chunk)
        return newFlushTask(source);
      }
      else if (isDN2ID(entryContainer, treeName))
      {
        return newDN2IDImporterTask(treeName, source, progressReporter);
      }
      else if (isVLVIndex(entryContainer, treeName))
      {
        return newVLVIndexImporterTask(getVLVIndex(entryContainer, treeName), source, progressReporter);
      }
      return newChunkCopierTask(treeName, source, progressReporter);
    }
  }
 
  private static <V> List<V> invokeParallel(String threadNameTemplate, Collection<Callable<V>> tasks)
      throws InterruptedException, ExecutionException
  {
    final ExecutorService executor = Executors.newCachedThreadPool(newThreadFactory(null, threadNameTemplate, true));
    try
    {
      final CompletionService<V> completionService = new ExecutorCompletionService<>(executor);
      for (Callable<V> task : tasks)
      {
        completionService.submit(task);
      }
      return waitTasksTermination(completionService, tasks.size());
    }
    finally
    {
      executor.shutdownNow();
      executor.awaitTermination(5, TimeUnit.SECONDS);
    }
  }
 
  /**
   * A {@link WriteableTransaction} delegates the storage of data to {@link Chunk}s which are created on-demand for each
   * {@link TreeName} through the provided {@link ChunkFactory}. Once there is no more data to import, call
   * {@link #getChunks()} to get the resulting {@link Chunk}s containing the sorted data to import into database.
   * {@link #put(TreeName, ByteSequence, ByteSequence)} is thread-safe. Since there is only one {@link Chunk} created
   * per {@link TreeName}, the {@link Chunk#put(ByteSequence, ByteSequence)} method of returned {@link Chunk} must be
   * thread-safe.
   */
  private static final class PhaseOneWriteableTransaction implements WriteableTransaction
  {
    /** Must be power of 2 because of fast-modulo computing. */
    private static final int LOCKTABLE_SIZE = 64;
    private final ConcurrentMap<TreeName, Chunk> chunks = new ConcurrentHashMap<>();
    private final ChunkFactory chunkFactory;
    private final Object[] lockTable = new Object[LOCKTABLE_SIZE];
 
    PhaseOneWriteableTransaction(ChunkFactory chunkFactory)
    {
      this.chunkFactory = chunkFactory;
      for (int i = 0; i < LOCKTABLE_SIZE; i++)
      {
        lockTable[i] = new Object();
      }
    }
 
    Map<TreeName, Chunk> getChunks()
    {
      return chunks;
    }
 
    /**
     * Store record into a {@link Chunk}. Creating one if none is existing for the given treeName. This method is
     * thread-safe.
     */
    @Override
    public void put(final TreeName treeName, ByteSequence key, ByteSequence value)
    {
      try
      {
        getOrCreateChunk(treeName).put(key, value);
      }
      catch (Exception e)
      {
        throw new StorageRuntimeException(e);
      }
    }
 
    private Chunk getOrCreateChunk(final TreeName treeName) throws Exception
    {
      Chunk alreadyExistingChunk = chunks.get(treeName);
      if (alreadyExistingChunk != null)
      {
        return alreadyExistingChunk;
      }
 
      // Fast modulo computing.
      final int lockIndex = treeName.hashCode() & (LOCKTABLE_SIZE - 1);
      synchronized (lockTable[lockIndex])
      {
        alreadyExistingChunk = chunks.get(treeName);
        if (alreadyExistingChunk != null)
        {
          return alreadyExistingChunk;
        }
        final Chunk newChunk = chunkFactory.newChunk(treeName);
        chunks.put(treeName, newChunk);
        return newChunk;
      }
    }
 
    @Override
    public ByteString read(TreeName treeName, ByteSequence key)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public boolean update(TreeName treeName, ByteSequence key, UpdateFunction f)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public Cursor<ByteString, ByteString> openCursor(TreeName treeName)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public long getRecordCount(TreeName treeName)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public void openTree(TreeName name, boolean createOnDemand)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public void deleteTree(TreeName name)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public boolean delete(TreeName treeName, ByteSequence key)
    {
      throw new UnsupportedOperationException();
    }
  }
 
  /**
   * Chunk implementations are a data storage with an optional limited capacity. Chunk are typically used by first
   * adding data to the storage using {@link #put(ByteSequence, ByteSequence)} later on data can be sequentially
   * accessed using {@link #flip()}.
   */
  interface Chunk
  {
    /**
     * Add data to the storage. Wherever this method is thread-safe or not is implementation dependent.
     *
     * @return true if the data were added to the storage, false if the chunk is full.
     */
    boolean put(ByteSequence key, ByteSequence value);
 
    /**
     * Flip this chunk from write-only to read-only in order to get the previously stored data. This method must be
     * called only once. After flip is called, Chunk instance must not be used anymore.
     *
     * @return a {@link MeteredCursor} to access the data
     */
    MeteredCursor<ByteString, ByteString> flip();
 
    /**
     * Return size of data contained in this chunk. This size is guaranteed to be consistent only if there is no pending
     * {@link #put(ByteSequence, ByteSequence)} operations.
     */
    long size();
  }
 
  /**
   * Store and sort data into multiple chunks. Thanks to the chunk rolling mechanism, this chunk can sort and store an
   * unlimited amount of data. This class uses double-buffering: data are firstly stored in a
   * {@link InMemorySortedChunk} which, once full, will be asynchronously sorted and copied into a
   * {@link FileRegion}. Duplicate keys are reduced by a {@link Collector}.
   * {@link #put(ByteSequence, ByteSequence))} is thread-safe.
   * This class is used in phase-one. There is one {@link ExternalSortChunk} per
   * database tree, shared across all phase-one importer threads, in charge of storing/sorting records.
   */
  static final class ExternalSortChunk implements Chunk
  {
    /** Name reported by the {@link MeteredCursor} after {@link #flip()}. */
    private final String name;
    /** Provides buffer used to store and sort chunk of data. */
    private final BufferPool bufferPool;
    /** File containing the regions used to store the data. */
    private final FileChannel channel;
    /** Pointer to the next available region in the file, typically at end of file. */
    private final AtomicLong filePosition = new AtomicLong();
    /** Collector used to reduces the number of duplicate keys during sort. */
    private final Collector<?, ByteString> phaseOneDeduplicator;
    private final Collector<?, ByteString> phaseTwoDeduplicator;
    /** Keep track of pending sorting tasks. */
    private final CompletionService<Region> sorter;
    /** Keep track of currently opened chunks. */
    private final Set<Chunk> activeChunks = Collections.synchronizedSet(new HashSet<Chunk>());
    /** Keep track of the number of chunks created. */
    private final AtomicInteger nbSortedChunks = new AtomicInteger();
    /** Size approximation of data contained in this chunk. */
    private final AtomicLong size = new AtomicLong();
    /** Active chunk for the current thread. */
    private final ThreadLocal<Chunk> currentChunk = new ThreadLocal<Chunk>()
    {
      @Override
      protected Chunk initialValue()
      {
        return nullChunk();
      }
    };
 
    ExternalSortChunk(File tempDir, String name, BufferPool bufferPool, Collector<?, ByteString> phaseOneDeduplicator,
        Collector<?, ByteString> phaseTwoDeduplicator, Executor sortExecutor) throws IOException
    {
      this.name = name;
      this.bufferPool = bufferPool;
      this.phaseOneDeduplicator = phaseOneDeduplicator;
      this.phaseTwoDeduplicator = phaseTwoDeduplicator;
      final File file = new File(tempDir, name.replaceAll("\\W+", "_") + "_" + UUID.randomUUID().toString());
      this.channel = open(file.toPath(), CREATE_NEW, SPARSE, READ, WRITE);
      this.sorter = new ExecutorCompletionService<>(sortExecutor);
    }
 
    @Override
    public boolean put(final ByteSequence key, final ByteSequence value)
    {
      final Chunk chunk = currentChunk.get();
      if (!chunk.put(key, value))
      {
        sortAndAppendChunkAsync(chunk);
        activeChunks.remove(chunk);
 
        final Chunk newChunk = new InMemorySortedChunk(name, bufferPool);
        activeChunks.add(newChunk);
        currentChunk.set(newChunk);
        newChunk.put(key, value);
      }
      return true;
    }
 
    @Override
    public MeteredCursor<ByteString, ByteString> flip()
    {
      for (Chunk chunk : activeChunks)
      {
        sortAndAppendChunkAsync(chunk);
      }
 
      final List<MeteredCursor<ByteString, ByteString>> cursors = new ArrayList<>();
      try
      {
        final List<Region> regions = waitTasksTermination(sorter, nbSortedChunks.get());
        Collections.sort(regions); // Sort regions by their starting offsets.
        long mmapPosition = 0;
        // Create as big as possible memory are (handling 2Gb limit) and create as many cursors as regions from
        // these area.
        MappedByteBuffer mmap = channel.map(MapMode.READ_ONLY, mmapPosition, Math.min(size.get(), Integer.MAX_VALUE));
        for (Region region : regions)
        {
          if ((region.offset + region.size) > (mmapPosition + Integer.MAX_VALUE))
          {
            // Handle the 2Gb ByteBuffer limit
            mmapPosition = region.offset;
            mmap = channel.map(MapMode.READ_ONLY, mmapPosition, Math.min(size.get() - mmapPosition, Integer.MAX_VALUE));
          }
          final ByteBuffer regionBuffer = mmap.duplicate();
          final int relativeRegionOffset = (int) (region.offset - mmapPosition);
          regionBuffer.position(relativeRegionOffset).limit(regionBuffer.position() + region.size);
          cursors.add(new FileRegion.Cursor(name, regionBuffer.slice()));
        }
      }
      catch (ExecutionException | InterruptedException | IOException e)
      {
        throw new StorageRuntimeException(e);
      }
 
      final CompositeCursor<ByteString, ByteString> cursor = new CompositeCursor<ByteString, ByteString>(name, cursors)
      {
        @Override
        public void close()
        {
          super.close();
          if (OperatingSystem.isWindows())
          {
            // Windows might not be able to delete the file (see http://bugs.java.com/view_bug.do?bug_id=4715154)
            // To prevent these not deleted files to waste space, we empty it.
            try
            {
              channel.truncate(0);
            }
            catch (IOException e)
            {
              // This is best effort, it's safe to ignore the exception here.
            }
          }
          closeSilently(channel);
        }
      };
      return phaseTwoDeduplicator != null
          ? new CollectorCursor<>(cursor, (Collector<?, ByteString>) phaseTwoDeduplicator)
          : cursor;
    }
 
    @Override
    public long size()
    {
      long activeSize = 0;
      for (Chunk chunk : activeChunks)
      {
        activeSize += chunk.size();
      }
      return size.get() + activeSize;
    }
 
    int getNbSortedChunks()
    {
      return nbSortedChunks.get();
    }
 
    private void sortAndAppendChunkAsync(final Chunk chunk)
    {
      size.addAndGet(chunk.size());
 
      final long startOffset = filePosition.getAndAdd(chunk.size());
      nbSortedChunks.incrementAndGet();
 
      sorter.submit(new Callable<Region>()
      {
        @Override
        public Region call() throws Exception
        {
          /*
           * NOTE: The resulting size of the FileRegion might be less than chunk.size() because of key de-duplication
           * performed by the CollectorCursor.
           */
          checkThreadNotInterrupted();
          final int regionSize;
          try (final FileRegion region = new FileRegion(channel, startOffset, chunk.size());
               final SequentialCursor<ByteString, ByteString> source = phaseOneDeduplicator != null
                     ? new CollectorCursor<>(chunk.flip(), phaseOneDeduplicator)
                     : chunk.flip())
          {
            regionSize = region.write(source);
          }
          return new Region(startOffset, regionSize);
        }
      });
    }
 
    /** Define a region inside a file. */
    private static final class Region implements Comparable<Region>
    {
      private final long offset;
      private final int size;
 
      Region(long offset, int size)
      {
        this.offset = offset;
        this.size = size;
      }
 
      @Override
      public int compareTo(Region o)
      {
        return Long.compare(offset, o.offset);
      }
    }
 
    /**
     * Store data inside fixed-size byte arrays. Data stored in this chunk are sorted by key during the flip() so that
     * they can be cursored ascendantly. Byte arrays are supplied through a {@link BufferPool}. To allow sort operation,
     * data must be accessible randomly. To do so, offsets of each key/value records are stored in the buffer. To
     * maximize space occupation, buffer content is split in two parts: one contains records offset, the other contains
     * the records themselves:
     *
     * <pre>
     * ----------> offset writer direction ----------------> |<- free ->| <---- record writer direction ---
     * +-----------------+-----------------+-----------------+----------+----------+----------+----------+
     * | offset record 1 | offset record 2 | offset record n | .........| record n | record 2 | record 1 |
     * +-----------------+-----------------+-----------------+----------+----------+----------+----------+
     * </pre>
     *
     * Each record is the concatenation of a key/value (length are encoded using {@link PackedLong} representation)
     *
     * <pre>
     * +------------+--------------+--------------+----------------+
     * | key length | key bytes... | value length | value bytes... |
     * +------------+--------------+--------------+----------------+
     * </pre>
     */
    static final class InMemorySortedChunk implements Chunk, Comparator<Integer>
    {
      private final String metricName;
      private final BufferPool bufferPool;
      private final MemoryBuffer buffer;
      private long totalBytes;
      private int indexPos;
      private int dataPos;
      private int nbRecords;
 
      InMemorySortedChunk(String name, BufferPool bufferPool)
      {
        this.metricName = name;
        this.bufferPool = bufferPool;
        this.buffer = bufferPool.get();
        this.dataPos = buffer.length();
      }
 
      @Override
      public boolean put(ByteSequence key, ByteSequence value)
      {
        final int keyRecordSize = INT_SIZE + key.length();
        final int recordSize = keyRecordSize + INT_SIZE + value.length();
 
        dataPos -= recordSize;
        int recordDataPos = dataPos;
 
        final int recordIndexPos = indexPos;
        indexPos += INT_SIZE;
 
        if (indexPos > dataPos)
        {
          // Chunk is full
          return false;
        }
 
        nbRecords++;
        totalBytes += recordSize;
 
        // Write record offset
        buffer.writeInt(recordIndexPos, recordDataPos);
 
        buffer.writeInt(recordDataPos, key.length());
        recordDataPos += INT_SIZE;
        buffer.writeInt(recordDataPos, value.length());
        recordDataPos += INT_SIZE;
        buffer.writeByteSequence(recordDataPos, key);
        recordDataPos += key.length();
        buffer.writeByteSequence(recordDataPos, value);
 
        return true;
      }
 
      @Override
      public long size()
      {
        return totalBytes;
      }
 
      @Override
      public MeteredCursor<ByteString, ByteString> flip()
      {
        Collections.sort(new AbstractList<Integer>()
        {
          @Override
          public Integer get(int index)
          {
            return getOffsetAtPosition(index * INT_SIZE);
          }
 
          private Integer getOffsetAtPosition(int pos)
          {
            return buffer.readInt(pos);
          }
 
          @Override
          public Integer set(int index, Integer element)
          {
            final int pos = index * INT_SIZE;
            final Integer valueA = getOffsetAtPosition(pos);
            buffer.writeInt(pos, element);
            return valueA;
          }
 
          @Override
          public int size()
          {
            return nbRecords;
          }
        }, this);
 
        return new InMemorySortedChunkCursor();
      }
 
      @Override
      public int compare(Integer offsetA, Integer offsetB)
      {
        final int iOffsetA = offsetA.intValue();
        final int iOffsetB = offsetB.intValue();
        if (iOffsetA == iOffsetB)
        {
          return 0;
        }
        // Compare Keys
        final int keyLengthA = buffer.readInt(iOffsetA);
        final int keyLengthB = buffer.readInt(iOffsetB);
        final int keyOffsetA = iOffsetA + 2 * INT_SIZE;
        final int keyOffsetB = iOffsetB + 2 * INT_SIZE;
 
        return buffer.compare(keyOffsetA, keyLengthA, keyOffsetB, keyLengthB);
      }
 
      /** Cursor of the in-memory chunk. */
      private final class InMemorySortedChunkCursor implements MeteredCursor<ByteString, ByteString>
      {
        private ByteString key;
        private ByteString value;
        private volatile long bytesRead;
        private int indexOffset;
 
        @Override
        public boolean next()
        {
          if (bytesRead >= totalBytes)
          {
            key = value = null;
            return false;
          }
          int recordOffset = buffer.readInt(indexOffset);
 
          final int keyLength = buffer.readInt(recordOffset);
          recordOffset += 4;
          final int valueLength = buffer.readInt(recordOffset);
          recordOffset += 4;
 
          key = buffer.readByteString(recordOffset, keyLength);
          recordOffset += key.length();
          value = buffer.readByteString(recordOffset, valueLength);
 
          indexOffset += INT_SIZE;
          bytesRead += (2 * INT_SIZE) + keyLength + valueLength;
 
          return true;
        }
 
        @Override
        public boolean isDefined()
        {
          return key != null;
        }
 
        @Override
        public ByteString getKey() throws NoSuchElementException
        {
          throwIfUndefined(this);
          return key;
        }
 
        @Override
        public ByteString getValue() throws NoSuchElementException
        {
          throwIfUndefined(this);
 
          return value;
        }
 
        @Override
        public void delete() throws NoSuchElementException, UnsupportedOperationException
        {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public void close()
        {
          key = value = null;
          bufferPool.release(buffer);
        }
 
        @Override
        public String getMetricName()
        {
          return metricName;
        }
 
        @Override
        public long getNbBytesRead()
        {
          return bytesRead;
        }
 
        @Override
        public long getNbBytesTotal()
        {
          return totalBytes;
        }
      }
    }
 
    /**
     * Store data inside a region contained in a file. A regions is delimited by an offset and a length. The region is
     * memory-mapped and the data are appended in the memory-mapped region until it is full. Region store a
     * concatenation of key/value records: (Key & value sizes are stored using {@link PackedLong} format.)
     *
     * <pre>
     * +------------+--------------+--------------+----------------+
     * | key length | value length | key bytes... | value bytes... |
     * +------------+--------------+--------------+----------------+
     * </pre>
     */
    static final class FileRegion implements Closeable
    {
      private final MappedByteBuffer mmapBuffer;
      private final OutputStream mmapBufferOS = new OutputStream()
      {
        @Override
        public void write(int arg0) throws IOException
        {
          mmapBuffer.put((byte) arg0);
        }
      };
 
      FileRegion(FileChannel channel, long startOffset, long size) throws IOException
      {
        if (size > 0)
        {
          // Make sure that the file is big-enough to encapsulate this memory-mapped region.
          channel.write(ByteBuffer.wrap(new byte[] { 0 }), (startOffset + size) - 1);
        }
        mmapBuffer = channel.map(MapMode.READ_WRITE, startOffset, size);
      }
 
      public int write(SequentialCursor<ByteString, ByteString> source) throws IOException, InterruptedException
      {
        checkThreadNotInterrupted();
        while (source.next())
        {
          final ByteSequence key = source.getKey();
          final ByteSequence value = source.getValue();
          PackedLong.writeCompactUnsigned(mmapBufferOS, key.length());
          PackedLong.writeCompactUnsigned(mmapBufferOS, value.length());
          key.copyTo(mmapBuffer);
          value.copyTo(mmapBuffer);
          checkThreadNotInterrupted();
        }
        return mmapBuffer.position();
      }
 
      @Override
      public void close()
      {
        // Since this mmapBuffer will be GC'd, we have to ensure that the modified data
        // are synced to disk. Indeed, there is no guarantee that these data
        // will otherwise be available for the future File.map(READ).
        mmapBuffer.force();
      }
 
      /** Cursor through the specific memory-mapped file's region. */
      static final class Cursor implements MeteredCursor<ByteString, ByteString>
      {
        private final InputStream asInputStream = new InputStream()
        {
          @Override
          public int read() throws IOException
          {
            return region.get() & 0xFF;
          }
        };
        private final String metricName;
        private ByteBuffer region;
        private ByteString key, value;
 
        Cursor(String metricName, ByteBuffer region)
        {
          this.metricName = metricName;
          this.region = region;
        }
 
        @Override
        public boolean next()
        {
          if (!region.hasRemaining())
          {
            key = value = null;
            return false;
          }
 
          final int keyLength;
          final int valueLength;
          try
          {
            keyLength = (int) PackedLong.readCompactUnsignedLong(asInputStream);
            valueLength = (int) PackedLong.readCompactUnsignedLong(asInputStream);
          }
          catch (IOException e)
          {
            throw new StorageRuntimeException(e);
          }
          final int recordSize = keyLength + valueLength;
 
          final byte[] keyValueData = new byte[recordSize];
          region.get(keyValueData, 0, recordSize);
 
          key = ByteString.wrap(keyValueData, 0, keyLength);
          value = ByteString.wrap(keyValueData, keyLength, valueLength);
 
          return true;
        }
 
        @Override
        public boolean isDefined()
        {
          return key != null;
        }
 
        @Override
        public ByteString getKey() throws NoSuchElementException
        {
          throwIfUndefined(this);
          return key;
        }
 
        @Override
        public ByteString getValue() throws NoSuchElementException
        {
          throwIfUndefined(this);
          return value;
        }
 
        @Override
        public void delete() throws NoSuchElementException, UnsupportedOperationException
        {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public void close()
        {
          key = value = null;
          region = null;
        }
 
        @Override
        public String getMetricName()
        {
          return metricName;
        }
 
        @Override
        public long getNbBytesRead()
        {
          return region.position();
        }
 
        @Override
        public long getNbBytesTotal()
        {
          return region.limit();
        }
      }
    }
 
    /** A cursor de-duplicating data with the same keys from a sorted cursor. */
    static final class CollectorCursor<A, K, V> implements MeteredCursor<K, V>
    {
      private final MeteredCursor<K, ? extends V> delegate;
      private final Collector<A, V> collector;
      private boolean isDefined;
      private K key;
      private V value;
 
      CollectorCursor(MeteredCursor<K, ? extends V> cursor, Collector<A, V> collector)
      {
        this.delegate = cursor;
        this.collector = collector;
        if (!delegate.isDefined())
        {
          delegate.next();
        }
      }
 
      @Override
      public boolean next()
      {
        isDefined = delegate.isDefined();
        if (isDefined)
        {
          key = delegate.getKey();
          accumulateValues();
        }
        return isDefined;
      }
 
      private void accumulateValues()
      {
        throwIfUndefined(this);
        A resultContainer = collector.get();
        do
        {
          resultContainer = collector.accept(resultContainer, delegate.getValue());
        }
        while (delegate.next() && key.equals(delegate.getKey()));
        value = collector.merge(resultContainer);
        // Delegate is one step beyond. When delegate.isDefined() return false, we have to return true once more.
        isDefined = true;
      }
 
      @Override
      public boolean isDefined()
      {
        return isDefined;
      }
 
      @Override
      public K getKey() throws NoSuchElementException
      {
        throwIfUndefined(this);
        return key;
      }
 
      @Override
      public V getValue() throws NoSuchElementException
      {
        throwIfUndefined(this);
        return value;
      }
 
      @Override
      public void delete() throws NoSuchElementException, UnsupportedOperationException
      {
        throw new UnsupportedOperationException();
      }
 
      @Override
      public void close()
      {
        key = null;
        delegate.close();
      }
 
      @Override
      public String getMetricName()
      {
        return delegate.getMetricName();
      }
 
      @Override
      public long getNbBytesRead()
      {
        return delegate.getNbBytesRead();
      }
 
      @Override
      public long getNbBytesTotal()
      {
        return delegate.getNbBytesTotal();
      }
    }
 
    /** Provides a globally sorted cursor from multiple sorted cursors. */
    static class CompositeCursor<K extends Comparable<? super K>, V> implements MeteredCursor<K, V>
    {
      /** Contains the non empty and sorted cursors ordered in regards of their current key. */
      private final NavigableSet<MeteredCursor<K, V>> orderedCursors;
      private final String metricName;
      private final long totalBytes;
      private volatile long bytesRead;
      private K key;
      private V value;
 
      CompositeCursor(String metricName, Collection<MeteredCursor<K, V>> cursors)
      {
        this.metricName = metricName;
        this.orderedCursors = new TreeSet<>(new Comparator<MeteredCursor<K, V>>()
        {
          @Override
          public int compare(MeteredCursor<K, V> o1, MeteredCursor<K, V> o2)
          {
            final int cmp = o1.getKey().compareTo(o2.getKey());
            // Never return 0. Otherwise both cursors are considered equal and only one of them is kept by this set
            return cmp == 0 ? Integer.compare(System.identityHashCode(o1), System.identityHashCode(o2)) : cmp;
          }
        });
 
        long totalBytesSum = 0;
        for (MeteredCursor<K, V> cursor : cursors)
        {
          long previousBytesRead = cursor.getNbBytesRead();
          if (cursor.isDefined() || cursor.next())
          {
            if (orderedCursors.add(cursor))
            {
              bytesRead += (cursor.getNbBytesRead() - previousBytesRead);
              totalBytesSum += cursor.getNbBytesTotal();
            }
          }
          else
          {
            cursor.close();
          }
        }
        this.totalBytes = totalBytesSum;
      }
 
      /**
       * Try to get the next record from the cursor containing the lowest entry. If it reaches the end of the lowest
       * cursor, it calls the close method and begins reading from the next lowest cursor.
       */
      @Override
      public boolean next()
      {
        final MeteredCursor<K, V> lowestCursor = orderedCursors.pollFirst();
        if (lowestCursor == null)
        {
          key = null;
          value = null;
          return false;
        }
 
        key = lowestCursor.getKey();
        value = lowestCursor.getValue();
 
        long previousBytesRead = lowestCursor.getNbBytesRead();
        if (lowestCursor.next())
        {
          bytesRead += (lowestCursor.getNbBytesRead() - previousBytesRead);
          orderedCursors.add(lowestCursor);
        }
        else
        {
          lowestCursor.close();
        }
        return true;
      }
 
      @Override
      public boolean isDefined()
      {
        return key != null;
      }
 
      @Override
      public K getKey() throws NoSuchElementException
      {
        throwIfUndefined(this);
        return key;
      }
 
      @Override
      public V getValue() throws NoSuchElementException
      {
        throwIfUndefined(this);
        return value;
      }
 
      @Override
      public void delete() throws NoSuchElementException, UnsupportedOperationException
      {
        throw new UnsupportedOperationException();
      }
 
      @Override
      public void close()
      {
        closeSilently(orderedCursors);
      }
 
      @Override
      public String getMetricName()
      {
        return metricName;
      }
 
      @Override
      public long getNbBytesRead()
      {
        return bytesRead;
      }
 
      @Override
      public long getNbBytesTotal()
      {
        return totalBytes;
      }
    }
  }
 
  private static Chunk asChunk(TreeName treeName, Importer importer)
  {
    return new ImporterToChunkAdapter(treeName, importer);
  }
 
  /** Task to copy one {@link Chunk} into a database tree through an {@link Importer}. */
  private static final class ChunkCopierTask implements Callable<Void>
  {
    private final PhaseTwoProgressReporter reporter;
    private final TreeName treeName;
    private final Importer destination;
    private final Chunk source;
 
    ChunkCopierTask(PhaseTwoProgressReporter reporter, Chunk source, TreeName treeName, Importer destination)
    {
      this.source = source;
      this.treeName = treeName;
      this.destination = destination;
      this.reporter = reporter;
    }
 
    @Override
    public Void call() throws InterruptedException
    {
      checkThreadNotInterrupted();
      try (final SequentialCursor<ByteString, ByteString> sourceCursor = trackCursorProgress(reporter, source.flip()))
      {
        copyIntoChunk(sourceCursor, asChunk(treeName, destination));
      }
      return null;
    }
  }
 
  /** Task to copy VLV's counter chunks into a database tree. */
  private static final class VLVIndexImporterTask implements Callable<Void>
  {
    private final PhaseTwoProgressReporter reporter;
    private final VLVIndex vlvIndex;
    private final Importer destination;
    private final Chunk source;
 
    VLVIndexImporterTask(PhaseTwoProgressReporter reporter, Chunk source, VLVIndex vlvIndex, Importer destination)
    {
      this.source = source;
      this.vlvIndex = vlvIndex;
      this.destination = destination;
      this.reporter = reporter;
    }
 
    @Override
    public Void call() throws InterruptedException
    {
      checkThreadNotInterrupted();
      try (final SequentialCursor<ByteString, ByteString> sourceCursor = trackCursorProgress(reporter, source.flip()))
      {
        final long nbRecords = copyIntoChunk(sourceCursor, asChunk(vlvIndex.getName(), destination));
        vlvIndex.importCount(destination, nbRecords);
        return null;
      }
    }
  }
 
  private static long copyIntoChunk(SequentialCursor<ByteString, ByteString> source, Chunk destination)
      throws InterruptedException
  {
    long nbRecords = 0;
    checkThreadNotInterrupted();
    while (source.next())
    {
      if (!destination.put(source.getKey(), source.getValue()))
      {
        throw new IllegalStateException("Destination chunk is full");
      }
      nbRecords++;
      checkThreadNotInterrupted();
    }
    return nbRecords;
  }
 
  /**
   * This task optionally copy the dn2id chunk into the database and takes advantages of it's cursoring to compute the
   * {@link ID2ChildrenCount} index.
   */
  private static final class DN2IDImporterTask implements Callable<Void>
  {
    private final PhaseTwoProgressReporter reporter;
    private final Importer importer;
    private final File tempDir;
    private final BufferPool bufferPool;
    private final ID2Entry id2entry;
    private final DN2ID dn2id;
    private final ID2ChildrenCount id2count;
    private final Collector<?, ByteString> id2countCollector;
    private final Chunk dn2IdSourceChunk;
    private final Chunk dn2IdDestination;
 
    DN2IDImporterTask(PhaseTwoProgressReporter progressReporter, Importer importer, File tempDir, BufferPool bufferPool,
        ID2Entry id2Entry, DN2ID dn2id, Chunk dn2IdChunk, ID2ChildrenCount id2count,
        Collector<?, ByteString> id2countCollector)
    {
      this.reporter = progressReporter;
      this.importer = importer;
      this.tempDir = tempDir;
      this.bufferPool = bufferPool;
      this.id2entry = id2Entry;
      this.dn2id = dn2id;
      this.dn2IdSourceChunk = dn2IdChunk;
      this.id2count = id2count;
      this.id2countCollector = id2countCollector;
      this.dn2IdDestination = asChunk(dn2id.getName(), importer);
    }
 
    @Override
    public Void call() throws Exception
    {
      final Chunk id2CountChunk =
          new ExternalSortChunk(tempDir, id2count.getName().toString(), bufferPool, id2countCollector,
              id2countCollector, sameThreadExecutor());
      long totalNumberOfEntries = 0;
 
      final TreeVisitor<ChildrenCount> childrenCountVisitor =
          new ID2CountTreeVisitorImporter(asImporter(id2CountChunk));
      try (final SequentialCursor<ByteString, ByteString> chunkCursor =
               trackCursorProgress(reporter, dn2IdSourceChunk.flip());
           final DnValidationCursorDecorator validatorCursor =
               new DnValidationCursorDecorator(chunkCursor, id2entry, asWriteableTransaction(importer));
           final SequentialCursor<ByteString, ByteString> dn2idCursor =
               dn2id.openCursor(validatorCursor, childrenCountVisitor))
      {
        while (dn2idCursor.next())
        {
          checkThreadNotInterrupted();
          dn2IdDestination.put(dn2idCursor.getKey(), dn2idCursor.getValue());
          totalNumberOfEntries++;
        }
      }
      catch (StorageRuntimeException e)
      {
        // DnValidationCursorDecorator is using a StorageRuntimeException to wrap a DirectoryException
        if (e.getCause() instanceof DirectoryException)
        {
          throw (DirectoryException) e.getCause();
        }
        throw e;
      }
      id2count.importPutTotalCount(asImporter(id2CountChunk), Math.max(0, totalNumberOfEntries));
 
      new ChunkCopierTask(reporter, id2CountChunk, id2count.getName(), importer).call();
      return null;
    }
 
    /** TreeVisitor computing and importing the number of children per parent. */
    private final class ID2CountTreeVisitorImporter implements TreeVisitor<ChildrenCount>
    {
      private final Importer importer;
 
      ID2CountTreeVisitorImporter(Importer importer)
      {
        this.importer = importer;
      }
 
      @Override
      public ChildrenCount beginParent(EntryID parentID)
      {
        return new ChildrenCount(parentID);
      }
 
      @Override
      public void onChild(ChildrenCount parent, EntryID childID)
      {
        parent.numberOfChildren++;
      }
 
      @Override
      public void endParent(ChildrenCount parent)
      {
        if (parent.numberOfChildren > 0)
        {
          id2count.importPut(importer, parent.parentEntryID, parent.numberOfChildren);
        }
      }
    }
 
    /** Keep track of the number of children during the dn2id visit. */
    private static final class ChildrenCount
    {
      private final EntryID parentEntryID;
      private long numberOfChildren;
 
      private ChildrenCount(EntryID id)
      {
        this.parentEntryID = id;
      }
    }
  }
 
  /**
   * Throw a {@link StorageRuntimeException} when a duplicate or orphan DNs is detected. DNs returned by the decorated
   * cursor must be sorted.
   */
  static final class DnValidationCursorDecorator extends
      SequentialCursorDecorator<SequentialCursor<ByteString, ByteString>, ByteString, ByteString>
  {
    private final LinkedList<ByteString> parentDns = new LinkedList<>();
    private final ID2Entry id2entry;
    private final ReadableTransaction txn;
 
    DnValidationCursorDecorator(SequentialCursor<ByteString, ByteString> delegate, ID2Entry id2entry,
        ReadableTransaction txn)
    {
      super(delegate);
      this.id2entry = id2entry;
      this.txn = txn;
    }
 
    @Override
    public boolean next()
    {
      if (!delegate.next())
      {
        return false;
      }
      final ByteString dn = delegate.getKey();
      try
      {
        throwIfDuplicate(dn);
        throwIfOrphan(dn);
      }
      catch (DirectoryException e)
      {
        throw new StorageRuntimeException(e);
      }
      parentDns.add(dn);
      return true;
    }
 
    private void throwIfDuplicate(ByteString dn) throws DirectoryException
    {
      if (dn.equals(parentDns.peekLast()))
      {
        throw new DirectoryException(ENTRY_ALREADY_EXISTS, ERR_IMPORT_DUPLICATE_ENTRY.get(getDnAsString()));
      }
    }
 
    private String getDnAsString()
    {
      try
      {
        return id2entry.get(txn, new EntryID(delegate.getValue())).getName().toString();
      }
      catch (Exception e)
      {
        return DnKeyFormat.keyToDNString(delegate.getKey());
      }
    }
 
    private void throwIfOrphan(ByteString dn) throws DirectoryException
    {
      if (!parentExists(dn))
      {
        throw new DirectoryException(NO_SUCH_OBJECT, ERR_IMPORT_PARENT_NOT_FOUND.get(getDnAsString()));
      }
    }
 
    private boolean parentExists(ByteString childDn)
    {
      final Iterator<ByteString> it = parentDns.descendingIterator();
      int i = parentDns.size();
      while (it.hasNext())
      {
        if (DnKeyFormat.isChild(it.next(), childDn))
        {
          if (i < parentDns.size())
          {
            // Reset the last element in the stack to be the parentDn:
            // (removes siblings, nephews, grand-nephews, etc. of childDn)
            parentDns.subList(i, parentDns.size()).clear();
          }
          return true;
        }
        i--;
      }
      // First DN must represent the base-dn which is encoded as an empty ByteString.
      return parentDns.isEmpty() && childDn.isEmpty();
    }
  }
 
  private static Importer asImporter(Chunk chunk)
  {
    return new ChunkToImporterAdapter(chunk);
  }
 
  /**
   * Delegates the storage of data to the {@link Importer}. This class has same thread-safeness as the supplied
   * importer.
   */
  private static final class ImporterToChunkAdapter implements Chunk
  {
    private final TreeName treeName;
    private final Importer importer;
    private final AtomicLong size = new AtomicLong();
 
    ImporterToChunkAdapter(TreeName treeName, Importer importer)
    {
      this.treeName = treeName;
      this.importer = importer;
    }
 
    @Override
    public boolean put(ByteSequence key, ByteSequence value)
    {
      importer.put(treeName, key, value);
      size.addAndGet(key.length() + value.length());
      return true;
    }
 
    @Override
    public MeteredCursor<ByteString, ByteString> flip()
    {
      return asProgressCursor(importer.openCursor(treeName), treeName.toString(), size.get());
    }
 
    @Override
    public long size()
    {
      return size.get();
    }
  }
 
  /**
   * Delegates the {@link #put(TreeName, ByteSequence, ByteSequence)} method of {@link Importer} to a {@link Chunk}.
   * {@link #createTree(TreeName)} is a no-op, other methods throw {@link UnsupportedOperationException}. This class has
   * same thread-safeness as the supplied {@link Chunk}.
   */
  private static final class ChunkToImporterAdapter implements Importer
  {
    private final Chunk chunk;
 
    ChunkToImporterAdapter(Chunk chunk)
    {
      this.chunk = chunk;
    }
 
    @Override
    public void put(TreeName treeName, ByteSequence key, ByteSequence value)
    {
      try
      {
        chunk.put(key, value);
      }
      catch (Exception e)
      {
        throw new StorageRuntimeException(e);
      }
    }
 
    @Override
    public void clearTree(TreeName treeName)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public ByteString read(TreeName treeName, ByteSequence key)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public SequentialCursor<ByteString, ByteString> openCursor(TreeName treeName)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public void close()
    {
      // nothing to do
    }
  }
 
  /**
   * Write records into a delegated {@link Chunk} after performing a reordering of those records in regards of their key
   * by using a best-effort algorithm. This class is intended to be used when records are initially ordered but might
   * actually hit a chunk slightly disordered due to scheduling occurring in a multi-threaded environment. Records are
   * buffered and sorted before being written to the delegated chunk. Because of the buffer mechanism, records might be
   * written into the chunk after some delay. It's guaranteed that all entries will be written into the chunk only after
   * the flip() method has been called. {@link #put(TreeName, ByteSequence, ByteSequence)} is thread-safe.
   */
  private static final class MostlyOrderedChunk implements Chunk
  {
    /**
     * Number of items to queue before writing them to the storage. This number must be at least equal to the number of
     * threads which will access the put() method. If underestimated, {@link #put(ByteSequence, ByteSequence)} might
     * lead to unordered copy. If overestimated, extra memory is wasted.
     */
    private static final int QUEUE_SIZE = 128;
 
    /**
     * Maximum queued entry size. Beyond this size, entry will not be queued but written directly to the storage in
     * order to limit the heap size requirement for import.
     */
    private static final int ENTRY_MAX_SIZE = 32 * KB;
 
    private final NavigableMap<ByteSequence, ByteSequence> pendingRecords = new TreeMap<>();
    private final int queueSize;
    private final Chunk delegate;
 
    MostlyOrderedChunk(Chunk delegate)
    {
      this.delegate = delegate;
      this.queueSize = QUEUE_SIZE;
    }
 
    @Override
    public synchronized boolean put(ByteSequence key, ByteSequence value)
    {
      if ((key.length() + value.length()) >= ENTRY_MAX_SIZE)
      {
        return delegate.put(key, value);
      }
 
      pendingRecords.put(key, value);
      if (pendingRecords.size() == queueSize)
      {
        /*
         * Maximum size reached, take the record with the smallest key and persist it in the delegate chunk. this
         * ensures records are (mostly) inserted in ascending key order, which is the optimal insert order for B-trees.
         */
        final Map.Entry<ByteSequence, ByteSequence> lowestEntry = pendingRecords.pollFirstEntry();
        return delegate.put(lowestEntry.getKey(), lowestEntry.getValue());
      }
      return true;
    }
 
    @Override
    public MeteredCursor<ByteString, ByteString> flip()
    {
      // Purge pending entries
      for (Map.Entry<ByteSequence, ByteSequence> lowestEntry : pendingRecords.entrySet())
      {
        delegate.put(lowestEntry.getKey(), lowestEntry.getValue());
      }
      return delegate.flip();
    }
 
    @Override
    public long size()
    {
      return delegate.size();
    }
  }
 
  private static Chunk nullChunk()
  {
    return NullChunk.INSTANCE;
  }
 
  /** An empty Chunk which cannot store data. */
  private static final class NullChunk implements Chunk
  {
    private static final Chunk INSTANCE = new NullChunk();
 
    @Override
    public boolean put(ByteSequence key, ByteSequence value)
    {
      return false;
    }
 
    @Override
    public long size()
    {
      return 0;
    }
 
    @Override
    public MeteredCursor<ByteString, ByteString> flip()
    {
      return new MeteredCursor<ByteString, ByteString>()
      {
        @Override
        public boolean next()
        {
          return false;
        }
 
        @Override
        public boolean isDefined()
        {
          return false;
        }
 
        @Override
        public ByteString getKey() throws NoSuchElementException
        {
          throw new NoSuchElementException();
        }
 
        @Override
        public ByteString getValue() throws NoSuchElementException
        {
          throw new NoSuchElementException();
        }
 
        @Override
        public void delete() throws NoSuchElementException, UnsupportedOperationException
        {
          throw new UnsupportedOperationException();
        }
 
        @Override
        public void close()
        {
          // nothing to do
        }
 
        @Override
        public String getMetricName()
        {
          return NullChunk.class.getSimpleName();
        }
 
        @Override
        public long getNbBytesRead()
        {
          return 0;
        }
 
        @Override
        public long getNbBytesTotal()
        {
          return 0;
        }
      };
    }
  }
 
  /** Executor delegating the execution of task to the current thread. */
  private static Executor sameThreadExecutor()
  {
    return new Executor()
    {
      @Override
      public void execute(Runnable command)
      {
        command.run();
      }
    };
  }
 
  /** Collect the results of asynchronous tasks. */
  private static <K> List<K> waitTasksTermination(CompletionService<K> completionService, int nbTasks)
      throws InterruptedException, ExecutionException
  {
    final List<K> results = new ArrayList<>(nbTasks);
    for (int i = 0; i < nbTasks; i++)
    {
      results.add(completionService.take().get());
    }
    return results;
  }
 
  private static void checkThreadNotInterrupted() throws InterruptedException
  {
    if (Thread.interrupted())
    {
      throw new InterruptedException();
    }
  }
 
  /** Regularly report progress statistics from the registered list of {@link ProgressMetric}. */
  private static final class PhaseTwoProgressReporter implements Runnable, Closeable
  {
    private static final String PHASE2_REPORTER_THREAD_NAME = "PHASE2-REPORTER-%d";
 
    private final ScheduledExecutorService scheduler =
        Executors.newSingleThreadScheduledExecutor(newThreadFactory(null, PHASE2_REPORTER_THREAD_NAME, true));
    private final Map<MeteredCursor<?, ?>, Long> lastValues = new WeakHashMap<>();
    private ScheduledFuture<?> scheduledTask;
    private long lastRun = System.currentTimeMillis();
 
    synchronized void addCursor(MeteredCursor<?, ?> cursor)
    {
      if (lastValues.put(cursor, 0L) == null)
      {
        logger.info(NOTE_IMPORT_LDIF_INDEX_STARTED, cursor.getMetricName(), 1, 1);
      }
      if (scheduledTask == null)
      {
        scheduledTask = scheduler.scheduleAtFixedRate(this, 10, 10, TimeUnit.SECONDS);
      }
    }
 
    synchronized void removeCursor(MeteredCursor<?, ?> cursor)
    {
      if (lastValues.remove(cursor) != null)
      {
        logger.info(NOTE_IMPORT_LDIF_INDEX_CLOSE, cursor.getMetricName());
      }
    }
 
    @Override
    public synchronized void run()
    {
      final long deltaTime = System.currentTimeMillis() - lastRun;
      if (deltaTime == 0)
      {
        return;
      }
      for (Map.Entry<MeteredCursor<?, ?>, Long> metricLastValue : lastValues.entrySet())
      {
        final MeteredCursor<?, ?> cursor = metricLastValue.getKey();
        final long newValue = cursor.getNbBytesRead();
 
        final long totalBytes = cursor.getNbBytesTotal();
        final long valueProgress = newValue - metricLastValue.getValue();
        final int progressPercent = totalBytes > 0 ? Math.round((100f * newValue) / cursor.getNbBytesTotal()) : 0;
 
        final long progressRate = valueProgress / deltaTime;
        final long progressRemaining = (cursor.getNbBytesTotal() - newValue) / 1024;
 
        logger.info(NOTE_IMPORT_LDIF_PHASE_TWO_REPORT, cursor.getMetricName(), progressPercent, progressRemaining,
            progressRate, 1, 1);
 
        lastValues.put(cursor, newValue);
      }
      lastRun = System.currentTimeMillis();
    }
 
    @Override
    public synchronized void close()
    {
      scheduledTask = null;
      scheduler.shutdown();
    }
  }
 
  /**
   * Pre-allocate and maintain a fixed number of re-usable {@code Buffer}s. This allow to keep controls of heap memory
   * consumption and prevents the significant object allocation cost occurring for huge objects.
   */
  static final class BufferPool implements Closeable
  {
    private final BlockingQueue<MemoryBuffer> pool;
 
    BufferPool(int nbBuffer, int bufferSize, boolean allocateDirect)
    {
      this.pool = new ArrayBlockingQueue<>(nbBuffer);
      try
      {
        for (int i = 0; i < nbBuffer; i++)
        {
          pool.offer(new MemoryBuffer(allocateDirect
                          ? ByteBuffer.allocateDirect(bufferSize)
                          : ByteBuffer.allocate(bufferSize)));
        }
      }
      catch (OutOfMemoryError e)
      {
        close();
        throw e;
      }
    }
 
    private int size()
    {
      return pool.size();
    }
 
    private MemoryBuffer get()
    {
      try
      {
        return pool.take();
      }
      catch (InterruptedException e)
      {
        throw new StorageRuntimeException(e);
      }
    }
 
    private void release(MemoryBuffer buffer)
    {
      try
      {
        pool.put(buffer);
      }
      catch (InterruptedException e)
      {
        throw new StorageRuntimeException(e);
      }
    }
 
    @Override
    public void close()
    {
      boolean allMemoryBufferFreed = true;
      for (final MemoryBuffer memoryBuffer : pool)
      {
        allMemoryBufferFreed &= memoryBuffer.free();
      }
      pool.clear();
      if (!allMemoryBufferFreed)
      {
        // Some DirectByteBuffer were not freed because the cleaner method has failed/is not supported.
        // Do a best effort at freeing these buffers by requesting a GC.
        System.gc();
      }
    }
 
    /** Buffer wrapping a ByteBuffer. */
    @NotThreadSafe
    static final class MemoryBuffer
    {
      private static final boolean CLEAN_SUPPORTED;
      private static final Method directBufferCleanerMethod;
      private static final Method directBufferCleanerCleanMethod;
 
      static
      {
        Method tmpDirectBufferCleanerMethod = null;
        Method tmpDirectBufferCleanerCleanMethod = null;
        boolean tmpCleanSupported;
        try
        {
          tmpDirectBufferCleanerMethod = Class.forName("java.nio.DirectByteBuffer").getMethod("cleaner");
          tmpDirectBufferCleanerMethod.setAccessible(true);
          tmpDirectBufferCleanerCleanMethod = Class.forName("sun.misc.Cleaner").getMethod("clean");
          tmpDirectBufferCleanerCleanMethod.setAccessible(true);
          tmpCleanSupported = true;
        }
        catch (Exception e)
        {
          tmpCleanSupported = false;
        }
        CLEAN_SUPPORTED = tmpCleanSupported;
        directBufferCleanerMethod = tmpDirectBufferCleanerMethod;
        directBufferCleanerCleanMethod = tmpDirectBufferCleanerCleanMethod;
      }
 
      private final ByteBuffer buffer;
 
      MemoryBuffer(final ByteBuffer byteBuffer)
      {
        this.buffer = byteBuffer;
      }
 
      boolean free()
      {
        if (!buffer.isDirect())
        {
          // Heap buffers will be GC'd.
          return true;
        }
        if (CLEAN_SUPPORTED)
        {
          try
          {
            /**
             * DirectByteBuffers are garbage collected by using a phantom reference and a reference queue. Every once a
             * while, the JVM checks the reference queue and cleans the DirectByteBuffers. However, as this doesn't
             * happen immediately after discarding all references to a DirectByteBuffer, it's easy to OutOfMemoryError
             * yourself using DirectByteBuffers. Here we explicitly calls the Cleaner method of the DirectByteBuffer.
             */
            directBufferCleanerCleanMethod.invoke(directBufferCleanerMethod.invoke(buffer));
            return true;
          }
          catch (Exception ignored)
          {
            // silently ignore exception
          }
        }
        return false;
      }
 
      void writeInt(final int position, final int value)
      {
        buffer.putInt(position, value);
      }
 
      int readInt(final int position)
      {
        return buffer.getInt(position);
      }
 
      void writeByteSequence(int position, ByteSequence data)
      {
        buffer.position(position);
        data.copyTo(buffer);
      }
 
      int length()
      {
        return buffer.capacity();
      }
 
      ByteString readByteString(int position, int length)
      {
        if (buffer.hasArray())
        {
          return ByteString.wrap(buffer.array(), buffer.arrayOffset() + position, length);
        }
        final byte[] data = new byte[length];
        buffer.position(position);
        buffer.get(data);
        return ByteString.wrap(data);
      }
 
      int compare(int offsetA, int lengthA, int offsetB, int lengthB)
      {
        int count = Math.min(lengthA, lengthB);
        int i = offsetA;
        int j = offsetB;
        while (count-- != 0)
        {
          final int firstByte = 0xFF & buffer.get(i++);
          final int secondByte = 0xFF & buffer.get(j++);
          if (firstByte != secondByte)
          {
            return firstByte - secondByte;
          }
        }
        return lengthA - lengthB;
      }
    }
  }
 
  /** Extends {@link SequentialCursor} by providing metric related to cursor's progress. */
  interface MeteredCursor<K, V> extends SequentialCursor<K, V>
  {
    String getMetricName();
 
    long getNbBytesRead();
 
    long getNbBytesTotal();
  }
 
  /** Add the cursor to the reporter and remove it once closed. */
  private static <K, V> SequentialCursor<K, V> trackCursorProgress(final PhaseTwoProgressReporter reporter,
      final MeteredCursor<K, V> cursor)
  {
    reporter.addCursor(cursor);
    return new SequentialCursorDecorator<MeteredCursor<K, V>, K, V>(cursor)
    {
      @Override
      public void close()
      {
        reporter.removeCursor(cursor);
        cursor.close();
      }
    };
  }
 
  private static void throwIfUndefined(SequentialCursor<?, ?> cursor)
  {
    if (!cursor.isDefined())
    {
      throw new NoSuchElementException();
    }
  }
 
  /**
   * Get a new {@link Collector} which can be used to merge encoded values. The types of values to merged is deduced
   * from the {@link TreeName}
   */
  private static Collector<?, ByteString> newPhaseTwoCollector(final EntryContainer entryContainer,
      final TreeName treeName)
  {
    final DefaultIndex index = getIndex(entryContainer, treeName);
    if (index != null)
    {
      // key conflicts == merge EntryIDSets
      return new EntryIDSetsCollector(index);
    }
    else if (isID2ChildrenCount(entryContainer, treeName))
    {
      // key conflicts == sum values
      return ID2ChildrenCount.getSumLongCollectorInstance();
    }
    else if (isDN2ID(entryContainer, treeName))
    {
      // Detection of duplicate DN will be performed during phase 2 by the DNImporterTask
      return null;
    }
    else if (isDN2URI(entryContainer, treeName) || isVLVIndex(entryContainer, treeName))
    {
      // key conflicts == exception
      return UniqueValueCollector.getInstance();
    }
    throw new IllegalArgumentException("Unknown tree: " + treeName);
  }
 
  private static Collector<?, ByteString> newPhaseOneCollector(final EntryContainer entryContainer,
      final TreeName treeName)
  {
    final DefaultIndex index = getIndex(entryContainer, treeName);
    if (index != null)
    {
      // key conflicts == merge EntryIDSets
      return new EntryIDsCollector(index);
    }
    return newPhaseTwoCollector(entryContainer, treeName);
  }
 
  private static boolean isDN2ID(final EntryContainer entryContainer, final TreeName treeName)
  {
    return entryContainer.getDN2ID().getName().equals(treeName);
  }
 
  private static boolean isDN2URI(final EntryContainer entryContainer, TreeName treeName)
  {
    return entryContainer.getDN2URI().getName().equals(treeName);
  }
 
  private static boolean isID2Entry(final EntryContainer entryContainer, final TreeName treeName)
  {
    return entryContainer.getID2Entry().getName().equals(treeName);
  }
 
  private static boolean isID2ChildrenCount(final EntryContainer entryContainer, final TreeName treeName)
  {
    return entryContainer.getID2ChildrenCount().getName().equals(treeName);
  }
 
  private static boolean isVLVIndex(EntryContainer entryContainer, TreeName treeName)
  {
    return getVLVIndex(entryContainer, treeName) != null;
  }
 
  private static VLVIndex getVLVIndex(EntryContainer entryContainer, TreeName treeName)
  {
    for (VLVIndex vlvIndex : entryContainer.getVLVIndexes())
    {
      if (treeName.equals(vlvIndex.getName()))
      {
        return vlvIndex;
      }
    }
    return null;
  }
 
  private static DefaultIndex getIndex(EntryContainer entryContainer, TreeName treeName)
  {
    for (AttributeIndex attrIndex : entryContainer.getAttributeIndexes())
    {
      for (MatchingRuleIndex index : attrIndex.getNameToIndexes().values())
      {
        if (treeName.equals(index.getName()))
        {
          return index;
        }
      }
    }
    return null;
  }
 
  /**
   * A mutable reduction operation that accumulates input elements into a mutable result container, optionally
   * transforming the accumulated result into a final representation after all input elements have been processed.
   * Reduction operations can be performed either sequentially or in parallel. A Collector is specified by three
   * functions that work together to accumulate entries into a mutable result container, and optionally perform a final
   * transform on the result. They are: Creation of a new result container (get()), incorporating a new data element
   * into a result container (accept()), performing an optional final transform on the container (merge)
   *
   * @param <A>
   *          Accumulator type
   * @param <R>
   *          Result type
   * @see java.util.stream.Collector
   */
  interface Collector<A, R>
  {
    /**
     * Creates and returns a new mutable result container. Equivalent to A java.util.function.Collector.supplier().get()
     */
    A get();
 
    /**
     * Accepts two partial results and merges them. The combiner function may fold state from one argument into the
     * other and return that, or may return a new result container. Equivalent to
     * java.util.function.Collector.accumulator().accept(A, R)
     */
    A accept(A resultContainer, R value);
 
    /**
     * Perform the final transformation from the intermediate accumulation type A to the final result type R. Equivalent
     * to R java.util.function.Collector.finisher().apply(A)
     */
    R merge(A resultContainer);
  }
 
  /** {@link Collector} that throws an exception if multiple values have to be merged. */
  static final class UniqueValueCollector<V> implements Collector<V, V>
  {
    private static final Collector<Object, Object> INSTANCE = new UniqueValueCollector<>();
 
    @SuppressWarnings("unchecked")
    static <V> Collector<V, V> getInstance()
    {
      return (Collector<V, V>) INSTANCE;
    }
 
    @Override
    public V get()
    {
      return null;
    }
 
    @Override
    public V accept(V previousValue, V value)
    {
      if (previousValue != null)
      {
        throw new IllegalArgumentException("Cannot accept multiple values (current=" + previousValue + ", new=" + value
            + ")");
      }
      return value;
    }
 
    @Override
    public V merge(V latestValue)
    {
      if (latestValue == null)
      {
        throw new IllegalArgumentException("No value to merge but expected one");
      }
      return latestValue;
    }
  }
 
  /**
   * {@link Collector} that accepts encoded {@link EntryIDSet} objects and
   * produces a {@link ByteString} representing the merged {@link EntryIDSet}.
   */
  static final class EntryIDsCollector implements Collector<LongArray, ByteString>
  {
    private final DefaultIndex index;
    private final int indexLimit;
 
    EntryIDsCollector(DefaultIndex index)
    {
      this.index = index;
      this.indexLimit = index.getIndexEntryLimit();
    }
 
    @Override
    public LongArray get()
    {
      return new LongArray();
    }
 
    @Override
    public LongArray accept(LongArray resultContainer, ByteString value)
    {
      if (resultContainer.size() < indexLimit)
      {
        resultContainer.add(index.importDecodeValue(value));
      }
      /*
       * else EntryIDSet is above index entry limits, discard additional values
       * to avoid blowing up memory now, then discard all entries in merge()
       */
      return resultContainer;
    }
 
    @Override
    public ByteString merge(LongArray resultContainer)
    {
      if (resultContainer.size() >= indexLimit)
      {
        return index.toValue(EntryIDSet.newUndefinedSet());
      }
      return index.toValue(EntryIDSet.newDefinedSet(resultContainer.get()));
    }
  }
 
  /** Simple long array primitive wrapper. */
  private static final class LongArray
  {
    private long[] values = new long[16];
    private int size;
 
    void add(long value)
    {
      if (size == values.length)
      {
        values = Arrays.copyOf(values, values.length * 2);
      }
      values[size++] = value;
    }
 
    int size()
    {
      return size;
    }
 
    long[] get()
    {
      values = Arrays.copyOf(values, size);
      Arrays.sort(values);
      return values;
    }
  }
 
  /**
   * {@link Collector} that accepts encoded {@link EntryIDSet} objects and produces a {@link ByteString} representing
   * the merged {@link EntryIDSet}.
   */
  static final class EntryIDSetsCollector implements Collector<Collection<ByteString>, ByteString>
  {
    private final DefaultIndex index;
    private final int indexLimit;
 
    EntryIDSetsCollector(DefaultIndex index)
    {
      this.index = index;
      this.indexLimit = index.getIndexEntryLimit();
    }
 
    @Override
    public Collection<ByteString> get()
    {
      // LinkedList is used for it's O(1) add method (while ArrayList is O(n) when resize is required).
      return new LinkedList<>();
    }
 
    @Override
    public Collection<ByteString> accept(Collection<ByteString> resultContainer, ByteString value)
    {
      if (resultContainer.size() < indexLimit)
      {
        resultContainer.add(value);
      }
      /*
       * else EntryIDSet is above index entry limits, discard additional values to avoid blowing up memory now, then
       * discard all entries in merge()
       */
      return resultContainer;
    }
 
    @Override
    public ByteString merge(Collection<ByteString> resultContainer)
    {
      if (resultContainer.size() >= indexLimit)
      {
        return index.toValue(EntryIDSet.newUndefinedSet());
      }
      else if (resultContainer.size() == 1)
      {
        // Avoids unnecessary decoding + encoding
        return resultContainer.iterator().next();
      }
      return index.toValue(buildEntryIDSet(resultContainer));
    }
 
    private EntryIDSet buildEntryIDSet(Collection<ByteString> encodedIDSets)
    {
      final List<EntryIDSet> idSets = new ArrayList<>(encodedIDSets.size());
      int mergedSize = 0;
      for (ByteString encodedIDSet : encodedIDSets)
      {
        final EntryIDSet entryIDSet = index.decodeValue(ByteString.empty(), encodedIDSet);
        mergedSize += entryIDSet.size();
        if (!entryIDSet.isDefined() || mergedSize >= indexLimit)
        {
          // above index entry limit
          return EntryIDSet.newUndefinedSet();
        }
        idSets.add(entryIDSet);
      }
 
      final long[] entryIDs = new long[mergedSize];
      int offset = 0;
      for (EntryIDSet idSet : idSets)
      {
        offset += idSet.copyTo(entryIDs, offset);
      }
      Arrays.sort(entryIDs);
      return EntryIDSet.newDefinedSet(entryIDs);
    }
  }
 
  private static MeteredCursor<ByteString, ByteString> asProgressCursor(
      SequentialCursor<ByteString, ByteString> delegate, String metricName, long totalSize)
  {
    return new MeteredSequentialCursorDecorator(delegate, metricName, totalSize);
  }
 
  /** Decorate {@link SequentialCursor} by providing progress information while cursoring. */
  private static final class MeteredSequentialCursorDecorator extends
      SequentialCursorDecorator<SequentialCursor<ByteString, ByteString>, ByteString, ByteString>implements
      MeteredCursor<ByteString, ByteString>
  {
    private final String metricName;
    private final long totalSize;
    private volatile long bytesRead;
 
    private MeteredSequentialCursorDecorator(SequentialCursor<ByteString, ByteString> delegate, String metricName,
        long totalSize)
    {
      super(delegate);
      this.metricName = metricName;
      this.totalSize = totalSize;
    }
 
    @Override
    public boolean next()
    {
      if (delegate.next())
      {
        bytesRead += delegate.getKey().length() + delegate.getValue().length();
        return true;
      }
      return false;
    }
 
    @Override
    public void delete() throws NoSuchElementException, UnsupportedOperationException
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public long getNbBytesRead()
    {
      return bytesRead;
    }
 
    @Override
    public String getMetricName()
    {
      return metricName;
    }
 
    @Override
    public long getNbBytesTotal()
    {
      return totalSize;
    }
  }
 
  /** Helper allowing to create {@link SequentialCursor} decorator without having to re-implement all methods. */
  static abstract class SequentialCursorDecorator<D extends SequentialCursor<K, V>, K, V> implements
      SequentialCursor<K, V>
  {
    protected final D delegate;
 
    SequentialCursorDecorator(D delegate)
    {
      this.delegate = delegate;
    }
 
    @Override
    public boolean next()
    {
      return delegate.next();
    }
 
    @Override
    public boolean isDefined()
    {
      return delegate.isDefined();
    }
 
    @Override
    public K getKey() throws NoSuchElementException
    {
      return delegate.getKey();
    }
 
    @Override
    public V getValue() throws NoSuchElementException
    {
      return delegate.getValue();
    }
 
    @Override
    public void delete() throws NoSuchElementException, UnsupportedOperationException
    {
      delegate.delete();
    }
 
    @Override
    public void close()
    {
      delegate.close();
    }
  }
 
  private static void visitAttributeIndexes(final Collection<AttributeIndex> attributeIndexes,
      final Predicate<MatchingRuleIndex, AttributeIndex> predicate, final IndexVisitor visitor)
  {
    for (final AttributeIndex attribute : attributeIndexes)
    {
      for (final MatchingRuleIndex index : attribute.getNameToIndexes().values())
      {
        if (predicate.matches(index, attribute))
        {
          visitor.visitAttributeIndex(index);
        }
      }
    }
  }
 
  private static void visitIndexes(final EntryContainer entryContainer, final IndexVisitor visitor)
  {
    for (final AttributeIndex attribute : entryContainer.getAttributeIndexes())
    {
      for (final MatchingRuleIndex index : attribute.getNameToIndexes().values())
      {
        visitor.visitAttributeIndex(index);
      }
    }
    for (VLVIndex index : entryContainer.getVLVIndexes())
    {
      visitor.visitVLVIndex(index);
    }
    visitor.visitSystemIndex(entryContainer.getDN2ID());
    visitor.visitSystemIndex(entryContainer.getID2ChildrenCount());
    visitor.visitSystemIndex(entryContainer.getDN2URI());
  }
 
  /** Visitor pattern allowing to process all type of indexes. */
  private interface IndexVisitor
  {
    void visitAttributeIndex(Index index);
 
    void visitVLVIndex(VLVIndex index);
 
    void visitSystemIndex(Tree index);
  }
 
  private static final IndexVisitor setTrust(boolean trustValue, Importer importer)
  {
    return setTrust(trustValue, asWriteableTransaction(importer));
  }
 
  private static final IndexVisitor setTrust(boolean trustValue, WriteableTransaction txn)
  {
    return new TrustModifier(txn, trustValue);
  }
 
  /** Update the trust state of the visited indexes. */
  private static final class TrustModifier implements IndexVisitor
  {
    private final WriteableTransaction txn;
    private final boolean trustValue;
 
    TrustModifier(WriteableTransaction txn, boolean trustValue)
    {
      this.txn = txn;
      this.trustValue = trustValue;
    }
 
    @Override
    public void visitAttributeIndex(Index index)
    {
      index.setTrusted(txn, trustValue);
    }
 
    @Override
    public void visitVLVIndex(VLVIndex index)
    {
      index.setTrusted(txn, trustValue);
    }
 
    @Override
    public void visitSystemIndex(Tree index)
    {
      // System indexes don't have trust status
    }
  }
 
  private static IndexVisitor deleteDatabase(Importer importer)
  {
    return new DeleteDatabase(importer);
  }
 
  /** Delete & recreate the database of the visited indexes. */
  private static final class DeleteDatabase implements IndexVisitor
  {
    private final Importer importer;
 
    DeleteDatabase(Importer importer)
    {
      this.importer = importer;
    }
 
    @Override
    public void visitAttributeIndex(Index index)
    {
      deleteTree(index);
    }
 
    @Override
    public void visitVLVIndex(VLVIndex index)
    {
      deleteTree(index);
    }
 
    @Override
    public void visitSystemIndex(Tree index)
    {
      deleteTree(index);
    }
 
    private void deleteTree(Tree index)
    {
      index.delete(asWriteableTransaction(importer));
    }
  }
 
  private static IndexVisitor visitOnlyDegraded(IndexVisitor delegate)
  {
    return new DegradedIndexFilter(delegate);
  }
 
  /** Visit indexes which are in a degraded state. */
  private static final class DegradedIndexFilter implements IndexVisitor
  {
    private final IndexVisitor delegate;
 
    DegradedIndexFilter(IndexVisitor delegate)
    {
      this.delegate = delegate;
    }
 
    @Override
    public void visitAttributeIndex(Index index)
    {
      if (!index.isTrusted())
      {
        delegate.visitAttributeIndex(index);
      }
    }
 
    @Override
    public void visitVLVIndex(VLVIndex index)
    {
      if (!index.isTrusted())
      {
        delegate.visitVLVIndex(index);
      }
    }
 
    @Override
    public void visitSystemIndex(Tree index)
    {
      // System indexes don't have trust status
    }
  }
 
  /** Maintain a list containing the names of the visited indexes. */
  private static final class SelectIndexName implements IndexVisitor
  {
    private final Set<String> indexNames;
 
    SelectIndexName()
    {
      this.indexNames = new HashSet<>();
    }
 
    public Set<String> getSelectedIndexNames()
    {
      return indexNames;
    }
 
    @Override
    public void visitAttributeIndex(Index index)
    {
      addIndex(index);
    }
 
    @Override
    public void visitVLVIndex(VLVIndex index)
    {
      addIndex(index);
    }
 
    @Override
    public void visitSystemIndex(Tree index)
    {
      addIndex(index);
    }
 
    private void addIndex(Tree index)
    {
      indexNames.add(index.getName().getIndexId());
    }
  }
 
  private static final IndexVisitor visitOnlyIndexes(final Predicate<Tree, Void> predicate, final IndexVisitor delegate)
  {
    return new SpecificIndexFilter(delegate, predicate);
  }
 
  private static final Predicate<Tree, Void> indexIdIn(final Collection<String> caseIgnoredNames) {
    final Set<String> indexNames = new HashSet<>(caseIgnoredNames.size());
    for (final String indexName : caseIgnoredNames)
    {
      indexNames.add(indexName.toLowerCase());
    }
    return new Predicate<Tree, Void>()
    {
      @Override
      public boolean matches(final Tree tree, final Void p)
      {
        return indexNames.contains(tree.getName().getIndexId().toLowerCase());
      }
    };
  }
 
  private static final Predicate<MatchingRuleIndex, AttributeIndex> attributeTypeIs(final String caseIgnoredName)
  {
    return new Predicate<MatchingRuleIndex, AttributeIndex>()
    {
      @Override
      public boolean matches(final MatchingRuleIndex index, final AttributeIndex attribute)
      {
        return caseIgnoredName.equalsIgnoreCase(attribute.getAttributeType().getNameOrOID());
      }
    };
  }
 
  private static final Predicate<MatchingRuleIndex, AttributeIndex> matchingRuleIs(final MatchingRule matchingRule)
  {
    return new Predicate<MatchingRuleIndex, AttributeIndex>()
    {
      @Override
      public boolean matches(final MatchingRuleIndex index, final AttributeIndex attribute)
      {
        for (final Indexer indexer : matchingRule.createIndexers(attribute.getIndexingOptions()))
        {
          if (index.equals(attribute.getNameToIndexes().get(indexer.getIndexID())))
          {
            return true;
          }
        }
        return false;
      }
    };
  }
 
  private static final Predicate<MatchingRuleIndex, AttributeIndex> indexTypeIs(final IndexType type)
  {
    return new Predicate<MatchingRuleIndex, AttributeIndex>()
    {
      @Override
      public boolean matches(final MatchingRuleIndex index, final AttributeIndex attribute)
      {
        if (IndexType.PRESENCE.equals(type))
        {
          return index.equals(attribute.getNameToIndexes().get(IndexType.PRESENCE.toString()));
        }
        try
        {
          final MatchingRule matchingRule = AttributeIndex.getMatchingRule(type, attribute.getAttributeType());
          if (matchingRule != null && matchingRuleIs(matchingRule).matches(index, attribute))
          {
            return true;
          }
        }
        catch (IllegalArgumentException iae)
        {
          // getMatchingRule() not implemented for the specified index type. Ignore silently.
        }
        return false;
      }
    };
  }
 
  private static final <M, A> Predicate<M, A> matchingAllOf(final Iterable<Predicate<M, A>> predicates)
  {
    return new Predicate<M, A>()
    {
      @Override
      public boolean matches(M value, A p)
      {
        for (Predicate<M, A> predicate : predicates)
        {
          if (!predicate.matches(value, p))
          {
            return false;
          }
        }
        return true;
      }
    };
  }
 
  /** Visit indexes only if they match the provided predicate. */
  private static final class SpecificIndexFilter implements IndexVisitor
  {
    private final IndexVisitor delegate;
    private final Predicate<Tree, Void> predicate;
 
    SpecificIndexFilter(IndexVisitor delegate, Predicate<Tree, Void> predicate)
    {
      this.delegate = delegate;
      this.predicate = predicate;
    }
 
    @Override
    public void visitAttributeIndex(Index index)
    {
      if (predicate.matches(index, null))
      {
        delegate.visitAttributeIndex(index);
      }
    }
 
    @Override
    public void visitVLVIndex(VLVIndex index)
    {
      if (predicate.matches(index, null))
      {
        delegate.visitVLVIndex(index);
      }
    }
 
    @Override
    public void visitSystemIndex(Tree index)
    {
      if (predicate.matches(index, null))
      {
        delegate.visitSystemIndex(index);
      }
    }
  }
 
  private static WriteableTransaction asWriteableTransaction(Importer importer)
  {
    return new ImporterToWriteableTransactionAdapter(importer);
  }
 
  /** Adapter allowing to use an {@link Importer} as a {@link WriteableTransaction}. */
  private static final class ImporterToWriteableTransactionAdapter implements WriteableTransaction
  {
    private final Importer importer;
 
    ImporterToWriteableTransactionAdapter(Importer importer)
    {
      this.importer = importer;
    }
 
    @Override
    public ByteString read(TreeName treeName, ByteSequence key)
    {
      return importer.read(treeName, key);
    }
 
    @Override
    public void put(TreeName treeName, ByteSequence key, ByteSequence value)
    {
      importer.put(treeName, key, value);
    }
 
    @Override
    public boolean update(TreeName treeName, ByteSequence key, UpdateFunction f)
    {
      final ByteString value = importer.read(treeName, key);
      final ByteSequence newValue = f.computeNewValue(value);
      Reject.ifNull(newValue, "Importer cannot delete records.");
      if (!Objects.equals(value, newValue))
      {
        importer.put(treeName, key, newValue);
        return true;
      }
      return false;
    }
 
    @Override
    public Cursor<ByteString, ByteString> openCursor(TreeName treeName)
    {
      return new SequentialCursorAdapter<>(importer.openCursor(treeName));
    }
 
    @Override
    public long getRecordCount(TreeName treeName)
    {
      long counter = 0;
      try (final SequentialCursor<ByteString, ByteString> cursor = importer.openCursor(treeName))
      {
        while (cursor.next())
        {
          counter++;
        }
      }
      return counter;
    }
 
    @Override
    public void openTree(TreeName name, boolean createOnDemand)
    {
      throw new UnsupportedOperationException();
    }
 
    @Override
    public void deleteTree(TreeName name)
    {
      importer.clearTree(name);
    }
 
    @Override
    public boolean delete(TreeName treeName, ByteSequence key)
    {
      throw new UnsupportedOperationException();
    }
  }
}