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

Chris Ridd
08.30.2012 0eb671e7cb4324437780e64a9d23cd66baf6b3ff
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2009-2010 Sun Microsystems, Inc.
 *      Portions copyright 2011-2012 ForgeRock AS
 */
 
package org.forgerock.opendj.ldap.schema;
 
import static com.forgerock.opendj.util.StaticUtils.toLowerCase;
import static org.forgerock.opendj.ldap.CoreMessages.*;
import static org.forgerock.opendj.ldap.ErrorResultException.newErrorResult;
import static org.forgerock.opendj.ldap.schema.Schema.*;
import static org.forgerock.opendj.ldap.schema.SchemaConstants.EXTENSIBLE_OBJECT_OBJECTCLASS_OID;
import static org.forgerock.opendj.ldap.schema.SchemaConstants.OMR_GENERIC_ENUM_NAME;
import static org.forgerock.opendj.ldap.schema.SchemaConstants.SCHEMA_PROPERTY_APPROX_RULE;
import static org.forgerock.opendj.ldap.schema.SchemaConstants.TOP_OBJECTCLASS_NAME;
import static org.forgerock.opendj.ldap.schema.SchemaUtils.unmodifiableCopyOfExtraProperties;
import static org.forgerock.opendj.ldap.schema.SchemaUtils.unmodifiableCopyOfList;
import static org.forgerock.opendj.ldap.schema.SchemaUtils.unmodifiableCopyOfSet;
 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Pattern;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizedIllegalArgumentException;
import org.forgerock.opendj.ldap.Attribute;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.opendj.ldap.Connection;
import org.forgerock.opendj.ldap.DN;
import org.forgerock.opendj.ldap.DecodeException;
import org.forgerock.opendj.ldap.Entry;
import org.forgerock.opendj.ldap.EntryNotFoundException;
import org.forgerock.opendj.ldap.ErrorResultException;
import org.forgerock.opendj.ldap.Filter;
import org.forgerock.opendj.ldap.FutureResult;
import org.forgerock.opendj.ldap.ResultCode;
import org.forgerock.opendj.ldap.ResultHandler;
import org.forgerock.opendj.ldap.SearchScope;
import org.forgerock.opendj.ldap.requests.Requests;
import org.forgerock.opendj.ldap.requests.SearchRequest;
import org.forgerock.opendj.ldap.responses.SearchResultEntry;
 
import com.forgerock.opendj.util.FutureResultTransformer;
import com.forgerock.opendj.util.RecursiveFutureResult;
import com.forgerock.opendj.util.StaticUtils;
import com.forgerock.opendj.util.SubstringReader;
import com.forgerock.opendj.util.Validator;
 
/**
 * Schema builders should be used for incremental construction of new schemas.
 */
public final class SchemaBuilder {
 
    private static final String ATTR_SUBSCHEMA_SUBENTRY = "subschemaSubentry";
 
    private static final String[] SUBSCHEMA_ATTRS = new String[] { ATTR_LDAP_SYNTAXES,
        ATTR_ATTRIBUTE_TYPES, ATTR_DIT_CONTENT_RULES, ATTR_DIT_STRUCTURE_RULES,
        ATTR_MATCHING_RULE_USE, ATTR_MATCHING_RULES, ATTR_NAME_FORMS, ATTR_OBJECT_CLASSES };
 
    private static final Filter SUBSCHEMA_FILTER = Filter.valueOf("(objectClass=subschema)");
 
    private static final String[] SUBSCHEMA_SUBENTRY_ATTRS =
            new String[] { ATTR_SUBSCHEMA_SUBENTRY };
 
    // Constructs a search request for retrieving the subschemaSubentry
    // attribute from the named entry.
    private static SearchRequest getReadSchemaForEntrySearchRequest(final DN dn) {
        return Requests.newSearchRequest(dn, SearchScope.BASE_OBJECT, Filter
                .objectClassPresent(), SUBSCHEMA_SUBENTRY_ATTRS);
    }
 
    // Constructs a search request for retrieving the named subschema
    // sub-entry.
    private static SearchRequest getReadSchemaSearchRequest(final DN dn) {
        return Requests.newSearchRequest(dn, SearchScope.BASE_OBJECT, SUBSCHEMA_FILTER,
                SUBSCHEMA_ATTRS);
    }
 
    private static DN getSubschemaSubentryDN(final DN name, final Entry entry)
            throws ErrorResultException {
        final Attribute subentryAttr = entry.getAttribute(ATTR_SUBSCHEMA_SUBENTRY);
 
        if (subentryAttr == null || subentryAttr.isEmpty()) {
            // Did not get the subschema sub-entry attribute.
            throw newErrorResult(ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED,
                    ERR_NO_SUBSCHEMA_SUBENTRY_ATTR.get(name.toString()).toString());
        }
 
        final String dnString = subentryAttr.iterator().next().toString();
        DN subschemaDN;
        try {
            subschemaDN = DN.valueOf(dnString);
        } catch (final LocalizedIllegalArgumentException e) {
            throw newErrorResult(ResultCode.CLIENT_SIDE_NO_RESULTS_RETURNED,
                    ERR_INVALID_SUBSCHEMA_SUBENTRY_ATTR.get(name.toString(), dnString,
                            e.getMessageObject()).toString());
        }
        return subschemaDN;
    }
 
    private Map<Integer, DITStructureRule> id2StructureRules;
 
    private Map<String, List<AttributeType>> name2AttributeTypes;
 
    private Map<String, List<DITContentRule>> name2ContentRules;
 
    private Map<String, List<MatchingRule>> name2MatchingRules;
 
    private Map<String, List<MatchingRuleUse>> name2MatchingRuleUses;
 
    private Map<String, List<NameForm>> name2NameForms;
 
    private Map<String, List<ObjectClass>> name2ObjectClasses;
 
    private Map<String, List<DITStructureRule>> name2StructureRules;
 
    private Map<String, List<DITStructureRule>> nameForm2StructureRules;
 
    private Map<String, AttributeType> numericOID2AttributeTypes;
 
    private Map<String, DITContentRule> numericOID2ContentRules;
 
    private Map<String, MatchingRule> numericOID2MatchingRules;
 
    private Map<String, MatchingRuleUse> numericOID2MatchingRuleUses;
 
    private Map<String, NameForm> numericOID2NameForms;
 
    private Map<String, ObjectClass> numericOID2ObjectClasses;
 
    private Map<String, Syntax> numericOID2Syntaxes;
 
    private Map<String, List<NameForm>> objectClass2NameForms;
 
    private String schemaName;
 
    private List<LocalizableMessage> warnings;
 
    private boolean allowNonStandardTelephoneNumbers;
 
    private boolean allowZeroLengthDirectoryStrings;
 
    private boolean allowMalformedNamesAndOptions;
 
    private boolean allowMalformedJPEGPhotos;
 
    // A schema which should be copied into this builder on any mutation.
    private Schema copyOnWriteSchema = null;
 
    // A unique ID which can be used to uniquely identify schemas
    // constructed without a name.
    private static final AtomicInteger NEXT_SCHEMA_ID = new AtomicInteger();
 
    /**
     * Creates a new schema builder with no schema elements and default
     * compatibility options.
     */
    public SchemaBuilder() {
        preLazyInitBuilder(null, null);
    }
 
    /**
     * Creates a new schema builder containing all of the schema elements
     * contained in the provided subschema subentry. Any problems encountered
     * while parsing the entry can be retrieved using the returned schema's
     * {@link Schema#getWarnings()} method.
     *
     * @param entry
     *            The subschema subentry to be parsed.
     * @throws NullPointerException
     *             If {@code entry} was {@code null}.
     */
    public SchemaBuilder(final Entry entry) {
        preLazyInitBuilder(entry.getName().toString(), null);
        addSchema(entry, true);
    }
 
    /**
     * Creates a new schema builder containing all of the schema elements from
     * the provided schema and its compatibility options.
     *
     * @param schema
     *            The initial contents of the schema builder.
     * @throws NullPointerException
     *             If {@code schema} was {@code null}.
     */
    public SchemaBuilder(final Schema schema) {
        preLazyInitBuilder(schema.getSchemaName(), schema);
    }
 
    /**
     * Creates a new schema builder with no schema elements and default
     * compatibility options.
     *
     * @param schemaName
     *            The user-friendly name of this schema which may be used for
     *            debugging purposes.
     */
    public SchemaBuilder(final String schemaName) {
        preLazyInitBuilder(schemaName, null);
    }
 
    /**
     * Adds the provided attribute type definition to this schema builder.
     *
     * @param definition
     *            The attribute type definition.
     * @param overwrite
     *            {@code true} if any existing attribute type with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided attribute type definition could not be
     *             parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addAttributeType(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the definition was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_ATTRTYPE_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_ATTRTYPE_EXPECTED_OPEN_PARENTHESIS.get(definition, (reader
                                .pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            String superiorType = null;
            String equalityMatchingRule = null;
            String orderingMatchingRule = null;
            String substringMatchingRule = null;
            String approximateMatchingRule = null;
            String syntax = null;
            boolean isSingleValue = false;
            boolean isCollective = false;
            boolean isNoUserModification = false;
            AttributeUsage attributeUsage = AttributeUsage.USER_APPLICATIONS;
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the definition. But before we start, set default
            // values for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("sup")) {
                    // This specifies the name or OID of the superior attribute
                    // type from which this attribute type should inherit its
                    // properties.
                    superiorType = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("equality")) {
                    // This specifies the name or OID of the equality matching
                    // rule to use for this attribute type.
                    equalityMatchingRule =
                            SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("ordering")) {
                    // This specifies the name or OID of the ordering matching
                    // rule to use for this attribute type.
                    orderingMatchingRule =
                            SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("substr")) {
                    // This specifies the name or OID of the substring matching
                    // rule to use for this attribute type.
                    substringMatchingRule =
                            SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("syntax")) {
                    // This specifies the numeric OID of the syntax for this
                    // matching rule. It may optionally be immediately followed
                    // by
                    // an open curly brace, an integer definition, and a close
                    // curly brace to suggest the minimum number of characters
                    // that should be allowed in values of that type. This
                    // implementation will ignore any such length because it
                    // does
                    // not impose any practical limit on the length of attribute
                    // values.
                    syntax = SchemaUtils.readOIDLen(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("single-definition")) {
                    // This indicates that attributes of this type are allowed
                    // to
                    // have at most one definition. We do not need any more
                    // parsing for this token.
                    isSingleValue = true;
                } else if (tokenName.equalsIgnoreCase("single-value")) {
                    // This indicates that attributes of this type are allowed
                    // to
                    // have at most one value. We do not need any more parsing
                    // for
                    // this token.
                    isSingleValue = true;
                } else if (tokenName.equalsIgnoreCase("collective")) {
                    // This indicates that attributes of this type are
                    // collective
                    // (i.e., have their values generated dynamically in some
                    // way). We do not need any more parsing for this token.
                    isCollective = true;
                } else if (tokenName.equalsIgnoreCase("no-user-modification")) {
                    // This indicates that the values of attributes of this type
                    // are not to be modified by end users. We do not need any
                    // more parsing for this token.
                    isNoUserModification = true;
                } else if (tokenName.equalsIgnoreCase("usage")) {
                    // This specifies the usage string for this attribute type.
                    // It
                    // should be followed by one of the strings
                    // "userApplications", "directoryOperation",
                    // "distributedOperation", or "dSAOperation".
                    int length = 0;
 
                    reader.skipWhitespaces();
                    reader.mark();
 
                    while (reader.read() != ' ') {
                        length++;
                    }
 
                    reader.reset();
                    final String usageStr = reader.read(length);
                    if (usageStr.equalsIgnoreCase("userapplications")) {
                        attributeUsage = AttributeUsage.USER_APPLICATIONS;
                    } else if (usageStr.equalsIgnoreCase("directoryoperation")) {
                        attributeUsage = AttributeUsage.DIRECTORY_OPERATION;
                    } else if (usageStr.equalsIgnoreCase("distributedoperation")) {
                        attributeUsage = AttributeUsage.DISTRIBUTED_OPERATION;
                    } else if (usageStr.equalsIgnoreCase("dsaoperation")) {
                        attributeUsage = AttributeUsage.DSA_OPERATION;
                    } else {
                        final LocalizableMessage message =
                                WARN_ATTR_SYNTAX_ATTRTYPE_INVALID_ATTRIBUTE_USAGE1.get(definition,
                                        usageStr);
                        throw new LocalizedIllegalArgumentException(message);
                    }
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_ATTRTYPE_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            final List<String> approxRules = extraProperties.get(SCHEMA_PROPERTY_APPROX_RULE);
            if (approxRules != null && !approxRules.isEmpty()) {
                approximateMatchingRule = approxRules.get(0);
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            if (superiorType == null && syntax == null) {
                final LocalizableMessage msg =
                        WARN_ATTR_SYNTAX_ATTRTYPE_MISSING_SYNTAX_AND_SUPERIOR.get(definition);
                throw new LocalizedIllegalArgumentException(msg);
            }
 
            final AttributeType attrType =
                    new AttributeType(oid, names, description, isObsolete, superiorType,
                            equalityMatchingRule, orderingMatchingRule, substringMatchingRule,
                            approximateMatchingRule, syntax, isSingleValue, isCollective,
                            isNoUserModification, attributeUsage, extraProperties, definition);
 
            addAttributeType(attrType, overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_ATTRTYPE_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided attribute type definition to this schema builder.
     *
     * @param oid
     *            The OID of the attribute type definition.
     * @param names
     *            The user-friendly names of the attribute type definition.
     * @param description
     *            The description of the attribute type definition.
     * @param obsolete
     *            {@code true} if the attribute type definition is obsolete,
     *            otherwise {@code false}.
     * @param superiorType
     *            The OID of the superior attribute type definition.
     * @param equalityMatchingRule
     *            The OID of the equality matching rule, which may be
     *            {@code null} indicating that the superior attribute type's
     *            matching rule should be used or, if none is defined, the
     *            default matching rule associated with the syntax.
     * @param orderingMatchingRule
     *            The OID of the ordering matching rule, which may be
     *            {@code null} indicating that the superior attribute type's
     *            matching rule should be used or, if none is defined, the
     *            default matching rule associated with the syntax.
     * @param substringMatchingRule
     *            The OID of the substring matching rule, which may be
     *            {@code null} indicating that the superior attribute type's
     *            matching rule should be used or, if none is defined, the
     *            default matching rule associated with the syntax.
     * @param approximateMatchingRule
     *            The OID of the approximate matching rule, which may be
     *            {@code null} indicating that the superior attribute type's
     *            matching rule should be used or, if none is defined, the
     *            default matching rule associated with the syntax.
     * @param syntax
     *            The OID of the syntax definition.
     * @param singleValue
     *            {@code true} if the attribute type definition is
     *            single-valued, otherwise {@code false}.
     * @param collective
     *            {@code true} if the attribute type definition is a collective
     *            attribute, otherwise {@code false}.
     * @param noUserModification
     *            {@code true} if the attribute type definition is read-only,
     *            otherwise {@code false}.
     * @param attributeUsage
     *            The intended use of the attribute type definition.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            attribute type definition.
     * @param overwrite
     *            {@code true} if any existing attribute type with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addAttributeType(final String oid, final List<String> names,
            final String description, final boolean obsolete, final String superiorType,
            final String equalityMatchingRule, final String orderingMatchingRule,
            final String substringMatchingRule, final String approximateMatchingRule,
            final String syntax, final boolean singleValue, final boolean collective,
            final boolean noUserModification, final AttributeUsage attributeUsage,
            final Map<String, List<String>> extraProperties, final boolean overwrite) {
        lazyInitBuilder();
 
        final AttributeType attrType =
                new AttributeType(oid, unmodifiableCopyOfList(names), description, obsolete,
                        superiorType, equalityMatchingRule, orderingMatchingRule,
                        substringMatchingRule, approximateMatchingRule, syntax, singleValue,
                        collective, noUserModification, attributeUsage,
                        unmodifiableCopyOfExtraProperties(extraProperties), null);
        addAttributeType(attrType, overwrite);
        return this;
    }
 
    /**
     * Adds the provided DIT content rule definition to this schema builder.
     *
     * @param definition
     *            The DIT content rule definition.
     * @param overwrite
     *            {@code true} if any existing DIT content rule with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided DIT content rule definition could not be
     *             parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addDITContentRule(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message = ERR_ATTR_SYNTAX_DCR_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_DCR_EXPECTED_OPEN_PARENTHESIS.get(definition,
                                (reader.pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String structuralClass =
                    SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            Set<String> auxiliaryClasses = Collections.emptySet();
            Set<String> optionalAttributes = Collections.emptySet();
            Set<String> prohibitedAttributes = Collections.emptySet();
            Set<String> requiredAttributes = Collections.emptySet();
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("aux")) {
                    auxiliaryClasses = SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("must")) {
                    requiredAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("may")) {
                    optionalAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("not")) {
                    prohibitedAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_DCR_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            final DITContentRule rule =
                    new DITContentRule(structuralClass, names, description, isObsolete,
                            auxiliaryClasses, optionalAttributes, prohibitedAttributes,
                            requiredAttributes, extraProperties, definition);
            addDITContentRule(rule, overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_DCR_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided DIT content rule definition to this schema builder.
     *
     * @param structuralClass
     *            The name of the structural object class to which the DIT
     *            content rule applies.
     * @param names
     *            The user-friendly names of the DIT content rule definition.
     * @param description
     *            The description of the DIT content rule definition.
     * @param obsolete
     *            {@code true} if the DIT content rule definition is obsolete,
     *            otherwise {@code false}.
     * @param auxiliaryClasses
     *            A list of auxiliary object classes that entries subject to the
     *            DIT content rule may belong to.
     * @param optionalAttributes
     *            A list of attribute types that entries subject to the DIT
     *            content rule may contain.
     * @param prohibitedAttributes
     *            A list of attribute types that entries subject to the DIT
     *            content rule must not contain.
     * @param requiredAttributes
     *            A list of attribute types that entries subject to the DIT
     *            content rule must contain.
     * @param extraProperties
     *            A map containing additional properties associated with the DIT
     *            content rule definition.
     * @param overwrite
     *            {@code true} if any existing DIT content rule with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addDITContentRule(final String structuralClass, final List<String> names,
            final String description, final boolean obsolete, final Set<String> auxiliaryClasses,
            final Set<String> optionalAttributes, final Set<String> prohibitedAttributes,
            final Set<String> requiredAttributes, final Map<String, List<String>> extraProperties,
            final boolean overwrite) {
        lazyInitBuilder();
 
        final DITContentRule rule =
                new DITContentRule(structuralClass, unmodifiableCopyOfList(names), description,
                        obsolete, unmodifiableCopyOfSet(auxiliaryClasses),
                        unmodifiableCopyOfSet(optionalAttributes),
                        unmodifiableCopyOfSet(prohibitedAttributes),
                        unmodifiableCopyOfSet(requiredAttributes),
                        unmodifiableCopyOfExtraProperties(extraProperties), null);
        addDITContentRule(rule, overwrite);
        return this;
    }
 
    /**
     * Adds the provided DIT structure rule definition to this schema builder.
     *
     * @param ruleID
     *            The rule identifier of the DIT structure rule.
     * @param names
     *            The user-friendly names of the DIT structure rule definition.
     * @param description
     *            The description of the DIT structure rule definition.
     * @param obsolete
     *            {@code true} if the DIT structure rule definition is obsolete,
     *            otherwise {@code false}.
     * @param nameForm
     *            The name form associated with the DIT structure rule.
     * @param superiorRules
     *            A list of superior rules (by rule id).
     * @param extraProperties
     *            A map containing additional properties associated with the DIT
     *            structure rule definition.
     * @param overwrite
     *            {@code true} if any existing DIT structure rule with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addDITStructureRule(final Integer ruleID, final List<String> names,
            final String description, final boolean obsolete, final String nameForm,
            final Set<Integer> superiorRules, final Map<String, List<String>> extraProperties,
            final boolean overwrite) {
        lazyInitBuilder();
 
        final DITStructureRule rule =
                new DITStructureRule(ruleID, unmodifiableCopyOfList(names), description, obsolete,
                        nameForm, unmodifiableCopyOfSet(superiorRules),
                        unmodifiableCopyOfExtraProperties(extraProperties), null);
        addDITStructureRule(rule, overwrite);
        return this;
    }
 
    /**
     * Adds the provided DIT structure rule definition to this schema builder.
     *
     * @param definition
     *            The DIT structure rule definition.
     * @param overwrite
     *            {@code true} if any existing DIT structure rule with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided DIT structure rule definition could not be
     *             parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addDITStructureRule(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message = ERR_ATTR_SYNTAX_DSR_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_DSR_EXPECTED_OPEN_PARENTHESIS.get(definition,
                                (reader.pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final Integer ruleID = SchemaUtils.readRuleID(reader);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            String nameForm = null;
            Set<Integer> superiorRules = Collections.emptySet();
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("form")) {
                    nameForm = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("sup")) {
                    superiorRules = SchemaUtils.readRuleIDs(reader);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_DSR_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            if (nameForm == null) {
                final LocalizableMessage message = ERR_ATTR_SYNTAX_DSR_NO_NAME_FORM.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            final DITStructureRule rule =
                    new DITStructureRule(ruleID, names, description, isObsolete, nameForm,
                            superiorRules, extraProperties, definition);
            addDITStructureRule(rule, overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_DSR_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided enumeration syntax definition to this schema builder.
     *
     * @param oid
     *            The OID of the enumeration syntax definition.
     * @param description
     *            The description of the enumeration syntax definition.
     * @param overwrite
     *            {@code true} if any existing syntax with the same OID should
     *            be overwritten.
     * @param enumerations
     *            The range of values which attribute values must match in order
     *            to be valid.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addEnumerationSyntax(final String oid, final String description,
            final boolean overwrite, final String... enumerations) {
        Validator.ensureNotNull((Object) enumerations);
 
        lazyInitBuilder();
 
        final EnumSyntaxImpl enumImpl = new EnumSyntaxImpl(oid, Arrays.asList(enumerations));
        final Syntax enumSyntax =
                new Syntax(oid, description, Collections.singletonMap("X-ENUM", Arrays
                        .asList(enumerations)), null, enumImpl);
        final MatchingRule enumOMR =
                new MatchingRule(enumImpl.getOrderingMatchingRule(), Collections
                        .singletonList(OMR_GENERIC_ENUM_NAME + oid), "", false, oid,
                        CoreSchemaImpl.OPENDS_ORIGIN, null, new EnumOrderingMatchingRule(enumImpl));
 
        addSyntax(enumSyntax, overwrite);
        try {
            addMatchingRule(enumOMR, overwrite);
        } catch (final ConflictingSchemaElementException e) {
            removeSyntax(oid);
        }
        return this;
    }
 
    /**
     * Adds the provided matching rule definition to this schema builder.
     *
     * @param definition
     *            The matching rule definition.
     * @param overwrite
     *            {@code true} if any existing matching rule with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided matching rule definition could not be parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addMatchingRule(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message = ERR_ATTR_SYNTAX_MR_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_MR_EXPECTED_OPEN_PARENTHESIS.get(definition,
                                (reader.pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            String syntax = null;
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the matching rule. It
                    // is
                    // an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the matching rule should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("syntax")) {
                    syntax = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_MR_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            // Make sure that a syntax was specified.
            if (syntax == null) {
                final LocalizableMessage message = ERR_ATTR_SYNTAX_MR_NO_SYNTAX.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            addMatchingRule(new MatchingRule(oid, names, description, isObsolete, syntax,
                    extraProperties, definition, null), overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_MR_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided matching rule definition to this schema builder.
     *
     * @param oid
     *            The OID of the matching rule definition.
     * @param names
     *            The user-friendly names of the matching rule definition.
     * @param description
     *            The description of the matching rule definition.
     * @param obsolete
     *            {@code true} if the matching rule definition is obsolete,
     *            otherwise {@code false}.
     * @param assertionSyntax
     *            The OID of the assertion syntax definition.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            matching rule definition.
     * @param implementation
     *            The implementation of the matching rule.
     * @param overwrite
     *            {@code true} if any existing matching rule with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addMatchingRule(final String oid, final List<String> names,
            final String description, final boolean obsolete, final String assertionSyntax,
            final Map<String, List<String>> extraProperties, final MatchingRuleImpl implementation,
            final boolean overwrite) {
        Validator.ensureNotNull(implementation);
 
        lazyInitBuilder();
 
        final MatchingRule matchingRule =
                new MatchingRule(oid, unmodifiableCopyOfList(names), description, obsolete,
                        assertionSyntax, unmodifiableCopyOfExtraProperties(extraProperties), null,
                        implementation);
        addMatchingRule(matchingRule, overwrite);
        return this;
    }
 
    /**
     * Adds the provided matching rule use definition to this schema builder.
     *
     * @param definition
     *            The matching rule use definition.
     * @param overwrite
     *            {@code true} if any existing matching rule use with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided matching rule use definition could not be
     *             parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addMatchingRuleUse(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_MRUSE_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_MRUSE_EXPECTED_OPEN_PARENTHESIS.get(definition, (reader
                                .pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            Set<String> attributes = null;
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("applies")) {
                    attributes = SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_MRUSE_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            // Make sure that the set of attributes was defined.
            if (attributes == null || attributes.size() == 0) {
                final LocalizableMessage message = ERR_ATTR_SYNTAX_MRUSE_NO_ATTR.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            final MatchingRuleUse use =
                    new MatchingRuleUse(oid, names, description, isObsolete, attributes,
                            extraProperties, definition);
            addMatchingRuleUse(use, overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_MRUSE_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided matching rule use definition to this schema builder.
     *
     * @param oid
     *            The OID of the matching rule use definition.
     * @param names
     *            The user-friendly names of the matching rule use definition.
     * @param description
     *            The description of the matching rule use definition.
     * @param obsolete
     *            {@code true} if the matching rule use definition is obsolete,
     *            otherwise {@code false}.
     * @param attributeOIDs
     *            The list of attribute types the matching rule applies to.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            matching rule use definition.
     * @param overwrite
     *            {@code true} if any existing matching rule use with the same
     *            OID should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addMatchingRuleUse(final String oid, final List<String> names,
            final String description, final boolean obsolete, final Set<String> attributeOIDs,
            final Map<String, List<String>> extraProperties, final boolean overwrite) {
        lazyInitBuilder();
 
        final MatchingRuleUse use =
                new MatchingRuleUse(oid, unmodifiableCopyOfList(names), description, obsolete,
                        unmodifiableCopyOfSet(attributeOIDs),
                        unmodifiableCopyOfExtraProperties(extraProperties), null);
        addMatchingRuleUse(use, overwrite);
        return this;
    }
 
    /**
     * Adds the provided name form definition to this schema builder.
     *
     * @param definition
     *            The name form definition.
     * @param overwrite
     *            {@code true} if any existing name form with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided name form definition could not be parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addNameForm(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_NAME_FORM_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_NAME_FORM_EXPECTED_OPEN_PARENTHESIS.get(definition, (reader
                                .pos() - 1), c);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            String structuralClass = null;
            Set<String> optionalAttributes = Collections.emptySet();
            Set<String> requiredAttributes = null;
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("oc")) {
                    structuralClass = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("must")) {
                    requiredAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("may")) {
                    optionalAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_NAME_FORM_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            // Make sure that a structural class was specified. If not, then
            // it cannot be valid.
            if (structuralClass == null) {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_NAME_FORM_NO_STRUCTURAL_CLASS1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            if (requiredAttributes == null || requiredAttributes.size() == 0) {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_NAME_FORM_NO_REQUIRED_ATTR.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            final NameForm nameForm =
                    new NameForm(oid, names, description, isObsolete, structuralClass,
                            requiredAttributes, optionalAttributes, extraProperties, definition);
            addNameForm(nameForm, overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_NAME_FORM_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided name form definition to this schema builder.
     *
     * @param oid
     *            The OID of the name form definition.
     * @param names
     *            The user-friendly names of the name form definition.
     * @param description
     *            The description of the name form definition.
     * @param obsolete
     *            {@code true} if the name form definition is obsolete,
     *            otherwise {@code false}.
     * @param structuralClass
     *            The structural object class this rule applies to.
     * @param requiredAttributes
     *            A list of naming attribute types that entries subject to the
     *            name form must contain.
     * @param optionalAttributes
     *            A list of naming attribute types that entries subject to the
     *            name form may contain.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            name form definition.
     * @param overwrite
     *            {@code true} if any existing name form use with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addNameForm(final String oid, final List<String> names,
            final String description, final boolean obsolete, final String structuralClass,
            final Set<String> requiredAttributes, final Set<String> optionalAttributes,
            final Map<String, List<String>> extraProperties, final boolean overwrite) {
        lazyInitBuilder();
 
        final NameForm nameForm =
                new NameForm(oid, unmodifiableCopyOfList(names), description, obsolete,
                        structuralClass, unmodifiableCopyOfSet(requiredAttributes),
                        unmodifiableCopyOfSet(optionalAttributes),
                        unmodifiableCopyOfExtraProperties(extraProperties), null);
        addNameForm(nameForm, overwrite);
        return this;
    }
 
    /**
     * Adds the provided object class definition to this schema builder.
     *
     * @param definition
     *            The object class definition.
     * @param overwrite
     *            {@code true} if any existing object class with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided object class definition could not be parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addObjectClass(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_OBJECTCLASS_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_OBJECTCLASS_EXPECTED_OPEN_PARENTHESIS1.get(definition,
                                (reader.pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            List<String> names = Collections.emptyList();
            String description = "".intern();
            boolean isObsolete = false;
            Set<String> superiorClasses = Collections.emptySet();
            Set<String> requiredAttributes = Collections.emptySet();
            Set<String> optionalAttributes = Collections.emptySet();
            ObjectClassType objectClassType = ObjectClassType.STRUCTURAL;
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("name")) {
                    names = SchemaUtils.readNameDescriptors(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the attribute type. It
                    // is an arbitrary string of characters enclosed in single
                    // quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.equalsIgnoreCase("obsolete")) {
                    // This indicates whether the attribute type should be
                    // considered obsolete. We do not need to do any more
                    // parsing
                    // for this token.
                    isObsolete = true;
                } else if (tokenName.equalsIgnoreCase("sup")) {
                    superiorClasses = SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("abstract")) {
                    // This indicates that entries must not include this
                    // objectclass unless they also include a non-abstract
                    // objectclass that inherits from this class. We do not need
                    // any more parsing for this token.
                    objectClassType = ObjectClassType.ABSTRACT;
                } else if (tokenName.equalsIgnoreCase("structural")) {
                    // This indicates that this is a structural objectclass. We
                    // do
                    // not need any more parsing for this token.
                    objectClassType = ObjectClassType.STRUCTURAL;
                } else if (tokenName.equalsIgnoreCase("auxiliary")) {
                    // This indicates that this is an auxiliary objectclass. We
                    // do
                    // not need any more parsing for this token.
                    objectClassType = ObjectClassType.AUXILIARY;
                } else if (tokenName.equalsIgnoreCase("must")) {
                    requiredAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.equalsIgnoreCase("may")) {
                    optionalAttributes =
                            SchemaUtils.readOIDs(reader, allowMalformedNamesAndOptions);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_OBJECTCLASS_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            if (oid.equals(EXTENSIBLE_OBJECT_OBJECTCLASS_OID)) {
                addObjectClass(new ObjectClass(description, extraProperties), overwrite);
            } else {
                if (objectClassType == ObjectClassType.STRUCTURAL && superiorClasses.isEmpty()) {
                    superiorClasses = Collections.singleton(TOP_OBJECTCLASS_NAME);
                }
 
                if (!extraProperties.isEmpty()) {
                    extraProperties = Collections.unmodifiableMap(extraProperties);
                }
 
                addObjectClass(new ObjectClass(oid, names, description, isObsolete,
                        superiorClasses, requiredAttributes, optionalAttributes, objectClassType,
                        extraProperties, definition), overwrite);
            }
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_OBJECTCLASS_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided object class definition to this schema builder.
     *
     * @param oid
     *            The OID of the object class definition.
     * @param names
     *            The user-friendly names of the object class definition.
     * @param description
     *            The description of the object class definition.
     * @param obsolete
     *            {@code true} if the object class definition is obsolete,
     *            otherwise {@code false}.
     * @param superiorClassOIDs
     *            A list of direct superclasses of the object class.
     * @param requiredAttributeOIDs
     *            A list of attribute types that entries must contain.
     * @param optionalAttributeOIDs
     *            A list of attribute types that entries may contain.
     * @param objectClassType
     *            The type of the object class.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            object class definition.
     * @param overwrite
     *            {@code true} if any existing object class with the same OID
     *            should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addObjectClass(final String oid, final List<String> names,
            final String description, final boolean obsolete, Set<String> superiorClassOIDs,
            final Set<String> requiredAttributeOIDs, final Set<String> optionalAttributeOIDs,
            final ObjectClassType objectClassType, final Map<String, List<String>> extraProperties,
            final boolean overwrite) {
        lazyInitBuilder();
 
        if (oid.equals(EXTENSIBLE_OBJECT_OBJECTCLASS_OID)) {
            addObjectClass(new ObjectClass(description,
                    unmodifiableCopyOfExtraProperties(extraProperties)), overwrite);
        } else {
            if (objectClassType == ObjectClassType.STRUCTURAL && superiorClassOIDs.isEmpty()) {
                superiorClassOIDs = Collections.singleton(TOP_OBJECTCLASS_NAME);
            }
 
            addObjectClass(new ObjectClass(oid, unmodifiableCopyOfList(names), description,
                    obsolete, unmodifiableCopyOfSet(superiorClassOIDs),
                    unmodifiableCopyOfSet(requiredAttributeOIDs),
                    unmodifiableCopyOfSet(optionalAttributeOIDs), objectClassType,
                    unmodifiableCopyOfExtraProperties(extraProperties), null), overwrite);
        }
        return this;
    }
 
    /**
     * Adds the provided pattern syntax definition to this schema builder.
     *
     * @param oid
     *            The OID of the pattern syntax definition.
     * @param description
     *            The description of the pattern syntax definition.
     * @param pattern
     *            The regular expression pattern which attribute values must
     *            match in order to be valid.
     * @param overwrite
     *            {@code true} if any existing syntax with the same OID should
     *            be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addPatternSyntax(final String oid, final String description,
            final Pattern pattern, final boolean overwrite) {
        Validator.ensureNotNull(pattern);
 
        lazyInitBuilder();
 
        addSyntax(new Syntax(oid, description, Collections.singletonMap("X-PATTERN", Collections
                .singletonList(pattern.toString())), null, null), overwrite);
        return this;
    }
 
    /**
     * Reads the schema elements contained in the named subschema sub-entry and
     * adds them to this schema builder.
     * <p>
     * If the requested schema is not returned by the Directory Server then the
     * request will fail with an {@link EntryNotFoundException}.
     *
     * @param connection
     *            A connection to the Directory Server whose schema is to be
     *            read.
     * @param name
     *            The distinguished name of the subschema sub-entry.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A reference to this schema builder.
     * @throws ErrorResultException
     *             If the result code indicates that the request failed for some
     *             reason.
     * @throws UnsupportedOperationException
     *             If the connection does not support search operations.
     * @throws IllegalStateException
     *             If the connection has already been closed, i.e. if
     *             {@code isClosed() == true}.
     * @throws NullPointerException
     *             If the {@code connection} or {@code name} was {@code null}.
     */
    public SchemaBuilder addSchema(final Connection connection, final DN name,
            final boolean overwrite) throws ErrorResultException {
        // The call to addSchema will perform copyOnWrite.
        final SearchRequest request = getReadSchemaSearchRequest(name);
        final Entry entry = connection.searchSingleEntry(request);
        return addSchema(entry, overwrite);
    }
 
    /**
     * Adds all of the schema elements contained in the provided subschema
     * subentry to this schema builder. Any problems encountered while parsing
     * the entry can be retrieved using the returned schema's
     * {@link Schema#getWarnings()} method.
     *
     * @param entry
     *            The subschema subentry to be parsed.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A reference to this schema builder.
     * @throws NullPointerException
     *             If {@code entry} was {@code null}.
     */
    public SchemaBuilder addSchema(final Entry entry, final boolean overwrite) {
        Validator.ensureNotNull(entry);
 
        lazyInitBuilder();
 
        Attribute attr = entry.getAttribute(Schema.ATTR_LDAP_SYNTAXES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addSyntax(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_ATTRIBUTE_TYPES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addAttributeType(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_OBJECT_CLASSES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addObjectClass(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_MATCHING_RULE_USE);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addMatchingRuleUse(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_MATCHING_RULES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addMatchingRule(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_DIT_CONTENT_RULES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addDITContentRule(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_DIT_STRUCTURE_RULES);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addDITStructureRule(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        attr = entry.getAttribute(Schema.ATTR_NAME_FORMS);
        if (attr != null) {
            for (final ByteString def : attr) {
                try {
                    addNameForm(def.toString(), overwrite);
                } catch (final LocalizedIllegalArgumentException e) {
                    warnings.add(e.getMessageObject());
                }
            }
        }
 
        return this;
    }
 
    /**
     * Adds all of the schema elements in the provided schema to this schema
     * builder.
     *
     * @param schema
     *            The schema to be copied into this schema builder.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and conflicting schema
     *             elements were found.
     * @throws NullPointerException
     *             If {@code schema} was {@code null}.
     */
    public SchemaBuilder addSchema(final Schema schema, final boolean overwrite) {
        Validator.ensureNotNull(schema);
 
        lazyInitBuilder();
 
        addSchema0(schema, overwrite);
        return this;
    }
 
    /**
     * Asynchronously reads the schema elements contained in the named subschema
     * sub-entry and adds them to this schema builder.
     * <p>
     * If the requested schema is not returned by the Directory Server then the
     * request will fail with an {@link EntryNotFoundException}.
     *
     * @param connection
     *            A connection to the Directory Server whose schema is to be
     *            read.
     * @param name
     *            The distinguished name of the subschema sub-entry.
     * @param handler
     *            A result handler which can be used to asynchronously process
     *            the operation result when it is received, may be {@code null}.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A future representing the updated schema builder.
     * @throws UnsupportedOperationException
     *             If the connection does not support search operations.
     * @throws IllegalStateException
     *             If the connection has already been closed, i.e. if
     *             {@code connection.isClosed() == true}.
     * @throws NullPointerException
     *             If the {@code connection} or {@code name} was {@code null}.
     */
    public FutureResult<SchemaBuilder> addSchemaAsync(final Connection connection, final DN name,
            final ResultHandler<? super SchemaBuilder> handler, final boolean overwrite) {
        // The call to addSchema will perform copyOnWrite.
        final SearchRequest request = getReadSchemaSearchRequest(name);
 
        final FutureResultTransformer<SearchResultEntry, SchemaBuilder> future =
                new FutureResultTransformer<SearchResultEntry, SchemaBuilder>(handler) {
 
                    @Override
                    protected SchemaBuilder transformResult(final SearchResultEntry result)
                            throws ErrorResultException {
                        addSchema(result, overwrite);
                        return SchemaBuilder.this;
                    }
 
                };
 
        final FutureResult<SearchResultEntry> innerFuture =
                connection.searchSingleEntryAsync(request, future);
        future.setFutureResult(innerFuture);
        return future;
    }
 
    /**
     * Reads the schema elements contained in the subschema sub-entry which
     * applies to the named entry and adds them to this schema builder.
     * <p>
     * If the requested entry or its associated schema are not returned by the
     * Directory Server then the request will fail with an
     * {@link EntryNotFoundException}.
     * <p>
     * This implementation first reads the {@code subschemaSubentry} attribute
     * of the entry in order to identify the schema and then invokes
     * {@link #addSchemaForEntry(Connection, DN, boolean)} to read the schema.
     *
     * @param connection
     *            A connection to the Directory Server whose schema is to be
     *            read.
     * @param name
     *            The distinguished name of the entry whose schema is to be
     *            located.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A reference to this schema builder.
     * @throws ErrorResultException
     *             If the result code indicates that the request failed for some
     *             reason.
     * @throws UnsupportedOperationException
     *             If the connection does not support search operations.
     * @throws IllegalStateException
     *             If the connection has already been closed, i.e. if
     *             {@code connection.isClosed() == true}.
     * @throws NullPointerException
     *             If the {@code connection} or {@code name} was {@code null}.
     */
    public SchemaBuilder addSchemaForEntry(final Connection connection, final DN name,
            final boolean overwrite) throws ErrorResultException {
        // The call to addSchema will perform copyOnWrite.
        final SearchRequest request = getReadSchemaForEntrySearchRequest(name);
        final Entry entry = connection.searchSingleEntry(request);
        final DN subschemaDN = getSubschemaSubentryDN(name, entry);
        return addSchema(connection, subschemaDN, overwrite);
    }
 
    /**
     * Asynchronously reads the schema elements contained in the subschema
     * sub-entry which applies to the named entry and adds them to this schema
     * builder.
     * <p>
     * If the requested entry or its associated schema are not returned by the
     * Directory Server then the request will fail with an
     * {@link EntryNotFoundException}.
     * <p>
     * This implementation first reads the {@code subschemaSubentry} attribute
     * of the entry in order to identify the schema and then invokes
     * {@link #addSchemaAsync(Connection, DN, ResultHandler, boolean)} to read
     * the schema.
     *
     * @param connection
     *            A connection to the Directory Server whose schema is to be
     *            read.
     * @param name
     *            The distinguished name of the entry whose schema is to be
     *            located.
     * @param handler
     *            A result handler which can be used to asynchronously process
     *            the operation result when it is received, may be {@code null}.
     * @param overwrite
     *            {@code true} if existing schema elements with the same
     *            conflicting OIDs should be overwritten.
     * @return A future representing the updated schema builder.
     * @throws UnsupportedOperationException
     *             If the connection does not support search operations.
     * @throws IllegalStateException
     *             If the connection has already been closed, i.e. if
     *             {@code connection.isClosed() == true}.
     * @throws NullPointerException
     *             If the {@code connection} or {@code name} was {@code null}.
     */
    public FutureResult<SchemaBuilder> addSchemaForEntryAsync(final Connection connection,
            final DN name, final ResultHandler<? super SchemaBuilder> handler,
            final boolean overwrite) {
        // The call to addSchema will perform copyOnWrite.
        final RecursiveFutureResult<SearchResultEntry, SchemaBuilder> future =
                new RecursiveFutureResult<SearchResultEntry, SchemaBuilder>(handler) {
 
                    @Override
                    protected FutureResult<SchemaBuilder> chainResult(
                            final SearchResultEntry innerResult,
                            final ResultHandler<? super SchemaBuilder> handler)
                            throws ErrorResultException {
                        final DN subschemaDN = getSubschemaSubentryDN(name, innerResult);
                        return addSchemaAsync(connection, subschemaDN, handler, overwrite);
                    }
 
                };
 
        final SearchRequest request = getReadSchemaForEntrySearchRequest(name);
        final FutureResult<SearchResultEntry> innerFuture =
                connection.searchSingleEntryAsync(request, future);
        future.setFutureResult(innerFuture);
        return future;
    }
 
    /**
     * Adds the provided substitution syntax definition to this schema builder.
     *
     * @param oid
     *            The OID of the substitution syntax definition.
     * @param description
     *            The description of the substitution syntax definition.
     * @param substituteSyntax
     *            The OID of the syntax whose implementation should be
     *            substituted.
     * @param overwrite
     *            {@code true} if any existing syntax with the same OID should
     *            be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     */
    public SchemaBuilder addSubstitutionSyntax(final String oid, final String description,
            final String substituteSyntax, final boolean overwrite) {
        Validator.ensureNotNull(substituteSyntax);
 
        lazyInitBuilder();
 
        addSyntax(new Syntax(oid, description, Collections.singletonMap("X-SUBST", Collections
                .singletonList(substituteSyntax)), null, null), overwrite);
        return this;
    }
 
    /**
     * Adds the provided syntax definition to this schema builder.
     *
     * @param definition
     *            The syntax definition.
     * @param overwrite
     *            {@code true} if any existing syntax with the same OID should
     *            be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws LocalizedIllegalArgumentException
     *             If the provided syntax definition could not be parsed.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addSyntax(final String definition, final boolean overwrite) {
        Validator.ensureNotNull(definition);
 
        lazyInitBuilder();
 
        try {
            final SubstringReader reader = new SubstringReader(definition);
 
            // We'll do this a character at a time. First, skip over any
            // leading whitespace.
            reader.skipWhitespaces();
 
            if (reader.remaining() <= 0) {
                // This means that the value was empty or contained only
                // whitespace. That is illegal.
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_ATTRSYNTAX_EMPTY_VALUE1.get(definition);
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // The next character must be an open parenthesis. If it is not,
            // then that is an error.
            final char c = reader.read();
            if (c != '(') {
                final LocalizableMessage message =
                        ERR_ATTR_SYNTAX_ATTRSYNTAX_EXPECTED_OPEN_PARENTHESIS.get(definition,
                                (reader.pos() - 1), String.valueOf(c));
                throw new LocalizedIllegalArgumentException(message);
            }
 
            // Skip over any spaces immediately following the opening
            // parenthesis.
            reader.skipWhitespaces();
 
            // The next set of characters must be the OID.
            final String oid = SchemaUtils.readOID(reader, allowMalformedNamesAndOptions);
 
            String description = "".intern();
            Map<String, List<String>> extraProperties = Collections.emptyMap();
 
            // At this point, we should have a pretty specific syntax that
            // describes what may come next, but some of the components are
            // optional and it would be pretty easy to put something in the
            // wrong order, so we will be very flexible about what we can
            // accept. Just look at the next token, figure out what it is and
            // how to treat what comes after it, then repeat until we get to
            // the end of the value. But before we start, set default values
            // for everything else we might need to know.
            while (true) {
                final String tokenName = SchemaUtils.readTokenName(reader);
 
                if (tokenName == null) {
                    // No more tokens.
                    break;
                } else if (tokenName.equalsIgnoreCase("desc")) {
                    // This specifies the description for the syntax. It is an
                    // arbitrary string of characters enclosed in single quotes.
                    description = SchemaUtils.readQuotedString(reader);
                } else if (tokenName.matches("^X-[A-Za-z_-]+$")) {
                    // This must be a non-standard property and it must be
                    // followed by either a single definition in single quotes
                    // or
                    // an open parenthesis followed by one or more values in
                    // single quotes separated by spaces followed by a close
                    // parenthesis.
                    if (extraProperties.isEmpty()) {
                        extraProperties = new HashMap<String, List<String>>();
                    }
                    extraProperties.put(tokenName, SchemaUtils.readExtensions(reader));
                } else {
                    final LocalizableMessage message =
                            ERR_ATTR_SYNTAX_ATTRSYNTAX_ILLEGAL_TOKEN1.get(definition, tokenName);
                    throw new LocalizedIllegalArgumentException(message);
                }
            }
 
            if (!extraProperties.isEmpty()) {
                extraProperties = Collections.unmodifiableMap(extraProperties);
            }
 
            // See if it is a enum syntax
            for (final Map.Entry<String, List<String>> property : extraProperties.entrySet()) {
                if (property.getKey().equalsIgnoreCase("x-enum")) {
                    final EnumSyntaxImpl enumImpl = new EnumSyntaxImpl(oid, property.getValue());
                    final Syntax enumSyntax =
                            new Syntax(oid, description, extraProperties, definition, enumImpl);
                    final MatchingRule enumOMR =
                            new MatchingRule(enumImpl.getOrderingMatchingRule(), Collections
                                    .singletonList(OMR_GENERIC_ENUM_NAME + oid), "", false, oid,
                                    CoreSchemaImpl.OPENDS_ORIGIN, null,
                                    new EnumOrderingMatchingRule(enumImpl));
 
                    addSyntax(enumSyntax, overwrite);
                    addMatchingRule(enumOMR, overwrite);
                    return this;
                }
            }
 
            addSyntax(new Syntax(oid, description, extraProperties, definition, null), overwrite);
        } catch (final DecodeException e) {
            final LocalizableMessage msg =
                    ERR_ATTR_SYNTAX_ATTRSYNTAX_INVALID1.get(definition, e.getMessageObject());
            throw new LocalizedIllegalArgumentException(msg, e.getCause());
        }
        return this;
    }
 
    /**
     * Adds the provided syntax definition to this schema builder.
     *
     * @param oid
     *            The OID of the syntax definition.
     * @param description
     *            The description of the syntax definition.
     * @param extraProperties
     *            A map containing additional properties associated with the
     *            syntax definition.
     * @param implementation
     *            The implementation of the syntax.
     * @param overwrite
     *            {@code true} if any existing syntax with the same OID should
     *            be overwritten.
     * @return A reference to this schema builder.
     * @throws ConflictingSchemaElementException
     *             If {@code overwrite} was {@code false} and a conflicting
     *             schema element was found.
     * @throws NullPointerException
     *             If {@code definition} was {@code null}.
     */
    public SchemaBuilder addSyntax(final String oid, final String description,
            final Map<String, List<String>> extraProperties, final SyntaxImpl implementation,
            final boolean overwrite) {
        lazyInitBuilder();
 
        addSyntax(new Syntax(oid, description, unmodifiableCopyOfExtraProperties(extraProperties),
                null, implementation), overwrite);
        return this;
    }
 
    /**
     * Specifies whether or not the schema should allow certain illegal
     * characters in OIDs and attribute options. When this compatibility option
     * is set to {@code true} the following illegal characters will be permitted
     * in addition to those permitted in section 1.4 of RFC 4512:
     *
     * <pre>
     * USCORE  = %x5F ; underscore ("_")
     * DOT     = %x2E ; period (".")
     * </pre>
     *
     * By default this compatibility option is set to {@code true} because these
     * characters are often used for naming purposes (such as collation rules).
     *
     * @param allowMalformedNamesAndOptions
     *            {@code true} if the schema should allow certain illegal
     *            characters in OIDs and attribute options.
     * @return A reference to this {@code SchemaBuilder}.
     * @see <a href="http://tools.ietf.org/html/rfc4512">RFC 4512 - Lightweight
     *      Directory Access Protocol (LDAP): Directory Information Models </a>
     */
    public SchemaBuilder allowMalformedNamesAndOptions(final boolean allowMalformedNamesAndOptions) {
        lazyInitBuilder();
 
        this.allowMalformedNamesAndOptions = allowMalformedNamesAndOptions;
        return this;
    }
 
    /**
     * Specifies whether or not the JPEG Photo syntax should allow values
     * which do not conform to the JFIF or Exif specifications.
     * <p>
     * By default this compatibility option is set to {@code true}.
     *
     * @param allowMalformedJPEGPhotos
     *            {@code true} if the JPEG Photo syntax should allow
     *            values which do not conform to the JFIF or Exif
     *            specifications.
     * @return A reference to this {@code SchemaBuilder}.
     */
    public SchemaBuilder allowMalformedJPEGPhotos(
            final boolean allowMalformedJPEGPhotos) {
        lazyInitBuilder();
 
        this.allowMalformedJPEGPhotos = allowMalformedJPEGPhotos;
        return this;
    }
 
    /**
     * Specifies whether or not the Telephone Number syntax should allow values
     * which do not conform to the E.123 international telephone number format.
     * <p>
     * By default this compatibility option is set to {@code true}.
     *
     * @param allowNonStandardTelephoneNumbers
     *            {@code true} if the Telephone Number syntax should allow
     *            values which do not conform to the E.123 international
     *            telephone number format.
     * @return A reference to this {@code SchemaBuilder}.
     */
    public SchemaBuilder allowNonStandardTelephoneNumbers(
            final boolean allowNonStandardTelephoneNumbers) {
        lazyInitBuilder();
 
        this.allowNonStandardTelephoneNumbers = allowNonStandardTelephoneNumbers;
        return this;
    }
 
    /**
     * Specifies whether or not zero-length values will be allowed by the
     * Directory String syntax. This is technically forbidden by the LDAP
     * specification, but it was allowed in earlier versions of the server, and
     * the discussion of the directory string syntax in RFC 2252 does not
     * explicitly state that they are not allowed.
     * <p>
     * By default this compatibility option is set to {@code false}.
     *
     * @param allowZeroLengthDirectoryStrings
     *            {@code true} if zero-length values will be allowed by the
     *            Directory String syntax, or {@code false} if not.
     * @return A reference to this {@code SchemaBuilder}.
     */
    public SchemaBuilder allowZeroLengthDirectoryStrings(
            final boolean allowZeroLengthDirectoryStrings) {
        lazyInitBuilder();
 
        this.allowZeroLengthDirectoryStrings = allowZeroLengthDirectoryStrings;
        return this;
    }
 
    /**
     * Removes the named attribute type from this schema builder.
     *
     * @param name
     *            The name or OID of the attribute type to be removed.
     * @return {@code true} if the attribute type was found.
     */
    public boolean removeAttributeType(final String name) {
        lazyInitBuilder();
 
        final AttributeType element = numericOID2AttributeTypes.get(name);
        if (element != null) {
            removeAttributeType(element);
            return true;
        }
        final List<AttributeType> elements = name2AttributeTypes.get(toLowerCase(name));
        if (elements != null) {
            for (final AttributeType e : elements) {
                removeAttributeType(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named DIT content rule from this schema builder.
     *
     * @param name
     *            The name or OID of the DIT content rule to be removed.
     * @return {@code true} if the DIT content rule was found.
     */
    public boolean removeDITContentRule(final String name) {
        lazyInitBuilder();
 
        final DITContentRule element = numericOID2ContentRules.get(name);
        if (element != null) {
            removeDITContentRule(element);
            return true;
        }
        final List<DITContentRule> elements = name2ContentRules.get(toLowerCase(name));
        if (elements != null) {
            for (final DITContentRule e : elements) {
                removeDITContentRule(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the specified DIT structure rule from this schema builder.
     *
     * @param ruleID
     *            The ID of the DIT structure rule to be removed.
     * @return {@code true} if the DIT structure rule was found.
     */
    public boolean removeDITStructureRule(final int ruleID) {
        lazyInitBuilder();
 
        final DITStructureRule element = id2StructureRules.get(ruleID);
        if (element != null) {
            removeDITStructureRule(element);
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named matching rule from this schema builder.
     *
     * @param name
     *            The name or OID of the matching rule to be removed.
     * @return {@code true} if the matching rule was found.
     */
    public boolean removeMatchingRule(final String name) {
        lazyInitBuilder();
 
        final MatchingRule element = numericOID2MatchingRules.get(name);
        if (element != null) {
            removeMatchingRule(element);
            return true;
        }
        final List<MatchingRule> elements = name2MatchingRules.get(toLowerCase(name));
        if (elements != null) {
            for (final MatchingRule e : elements) {
                removeMatchingRule(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named matching rule use from this schema builder.
     *
     * @param name
     *            The name or OID of the matching rule use to be removed.
     * @return {@code true} if the matching rule use was found.
     */
    public boolean removeMatchingRuleUse(final String name) {
        lazyInitBuilder();
 
        final MatchingRuleUse element = numericOID2MatchingRuleUses.get(name);
        if (element != null) {
            removeMatchingRuleUse(element);
            return true;
        }
        final List<MatchingRuleUse> elements = name2MatchingRuleUses.get(toLowerCase(name));
        if (elements != null) {
            for (final MatchingRuleUse e : elements) {
                removeMatchingRuleUse(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named name form from this schema builder.
     *
     * @param name
     *            The name or OID of the name form to be removed.
     * @return {@code true} if the name form was found.
     */
    public boolean removeNameForm(final String name) {
        lazyInitBuilder();
 
        final NameForm element = numericOID2NameForms.get(name);
        if (element != null) {
            removeNameForm(element);
            return true;
        }
        final List<NameForm> elements = name2NameForms.get(toLowerCase(name));
        if (elements != null) {
            for (final NameForm e : elements) {
                removeNameForm(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named object class from this schema builder.
     *
     * @param name
     *            The name or OID of the object class to be removed.
     * @return {@code true} if the object class was found.
     */
    public boolean removeObjectClass(final String name) {
        lazyInitBuilder();
 
        final ObjectClass element = numericOID2ObjectClasses.get(name);
        if (element != null) {
            removeObjectClass(element);
            return true;
        }
        final List<ObjectClass> elements = name2ObjectClasses.get(toLowerCase(name));
        if (elements != null) {
            for (final ObjectClass e : elements) {
                removeObjectClass(e);
            }
            return true;
        }
        return false;
    }
 
    /**
     * Removes the named syntax from this schema builder.
     *
     * @param numericOID
     *            The name of the syntax to be removed.
     * @return {@code true} if the syntax was found.
     */
    public boolean removeSyntax(final String numericOID) {
        lazyInitBuilder();
 
        final Syntax element = numericOID2Syntaxes.get(numericOID);
        if (element != null) {
            removeSyntax(element);
            return true;
        }
        return false;
    }
 
    /**
     * Returns a strict {@code Schema} containing all of the schema elements
     * contained in this schema builder as well as the same set of schema
     * compatibility options.
     * <p>
     * This method does not alter the contents of this schema builder.
     *
     * @return A {@code Schema} containing all of the schema elements contained
     *         in this schema builder as well as the same set of schema
     *         compatibility options
     */
    public Schema toSchema() {
        // If this schema builder was initialized from another schema and no
        // modifications have been made since then we can simply return the
        // original
        // schema.
        if (copyOnWriteSchema != null) {
            return copyOnWriteSchema;
        }
 
        // We still need to ensure that this builder has been initialized
        // (otherwise
        // some fields may still be null).
        lazyInitBuilder();
 
        final String localSchemaName;
        if (schemaName != null) {
            localSchemaName = schemaName;
        } else {
            localSchemaName = String.format("Schema#%d", NEXT_SCHEMA_ID.getAndIncrement());
        }
 
        final Schema schema =
                new Schema(localSchemaName, allowMalformedNamesAndOptions,
                        allowMalformedJPEGPhotos, allowNonStandardTelephoneNumbers,
                        allowZeroLengthDirectoryStrings, numericOID2Syntaxes,
                        numericOID2MatchingRules, numericOID2MatchingRuleUses,
                        numericOID2AttributeTypes, numericOID2ObjectClasses, numericOID2NameForms,
                        numericOID2ContentRules, id2StructureRules, name2MatchingRules,
                        name2MatchingRuleUses, name2AttributeTypes, name2ObjectClasses,
                        name2NameForms, name2ContentRules, name2StructureRules,
                        objectClass2NameForms, nameForm2StructureRules, warnings);
 
        validate(schema);
 
        // Re-init this builder so that it can continue to be used afterwards.
        preLazyInitBuilder(schemaName, schema);
 
        return schema;
    }
 
    private void addAttributeType(final AttributeType attribute, final boolean overwrite) {
        AttributeType conflictingAttribute;
        if (numericOID2AttributeTypes.containsKey(attribute.getOID())) {
            conflictingAttribute = numericOID2AttributeTypes.get(attribute.getOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_ATTRIBUTE_OID.get(attribute.getNameOrOID(),
                                attribute.getOID(), conflictingAttribute.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeAttributeType(conflictingAttribute);
        }
 
        numericOID2AttributeTypes.put(attribute.getOID(), attribute);
        for (final String name : attribute.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<AttributeType> attrs;
            if ((attrs = name2AttributeTypes.get(lowerName)) == null) {
                name2AttributeTypes.put(lowerName, Collections.singletonList(attribute));
            } else if (attrs.size() == 1) {
                attrs = new ArrayList<AttributeType>(attrs);
                attrs.add(attribute);
                name2AttributeTypes.put(lowerName, attrs);
            } else {
                attrs.add(attribute);
            }
        }
    }
 
    private void addDITContentRule(final DITContentRule rule, final boolean overwrite) {
        DITContentRule conflictingRule;
        if (numericOID2ContentRules.containsKey(rule.getStructuralClassOID())) {
            conflictingRule = numericOID2ContentRules.get(rule.getStructuralClassOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_DIT_CONTENT_RULE1.get(rule.getNameOrOID(), rule
                                .getStructuralClassOID(), conflictingRule.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeDITContentRule(conflictingRule);
        }
 
        numericOID2ContentRules.put(rule.getStructuralClassOID(), rule);
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<DITContentRule> rules;
            if ((rules = name2ContentRules.get(lowerName)) == null) {
                name2ContentRules.put(lowerName, Collections.singletonList(rule));
            } else if (rules.size() == 1) {
                rules = new ArrayList<DITContentRule>(rules);
                rules.add(rule);
                name2ContentRules.put(lowerName, rules);
            } else {
                rules.add(rule);
            }
        }
    }
 
    private void addDITStructureRule(final DITStructureRule rule, final boolean overwrite) {
        DITStructureRule conflictingRule;
        if (id2StructureRules.containsKey(rule.getRuleID())) {
            conflictingRule = id2StructureRules.get(rule.getRuleID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_DIT_STRUCTURE_RULE_ID.get(rule.getNameOrRuleID(),
                                rule.getRuleID(), conflictingRule.getNameOrRuleID());
                throw new ConflictingSchemaElementException(message);
            }
            removeDITStructureRule(conflictingRule);
        }
 
        id2StructureRules.put(rule.getRuleID(), rule);
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<DITStructureRule> rules;
            if ((rules = name2StructureRules.get(lowerName)) == null) {
                name2StructureRules.put(lowerName, Collections.singletonList(rule));
            } else if (rules.size() == 1) {
                rules = new ArrayList<DITStructureRule>(rules);
                rules.add(rule);
                name2StructureRules.put(lowerName, rules);
            } else {
                rules.add(rule);
            }
        }
    }
 
    private void addMatchingRule(final MatchingRule rule, final boolean overwrite) {
        MatchingRule conflictingRule;
        if (numericOID2MatchingRules.containsKey(rule.getOID())) {
            conflictingRule = numericOID2MatchingRules.get(rule.getOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_MR_OID.get(rule.getNameOrOID(), rule.getOID(),
                                conflictingRule.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeMatchingRule(conflictingRule);
        }
 
        numericOID2MatchingRules.put(rule.getOID(), rule);
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<MatchingRule> rules;
            if ((rules = name2MatchingRules.get(lowerName)) == null) {
                name2MatchingRules.put(lowerName, Collections.singletonList(rule));
            } else if (rules.size() == 1) {
                rules = new ArrayList<MatchingRule>(rules);
                rules.add(rule);
                name2MatchingRules.put(lowerName, rules);
            } else {
                rules.add(rule);
            }
        }
    }
 
    private void addMatchingRuleUse(final MatchingRuleUse use, final boolean overwrite) {
        MatchingRuleUse conflictingUse;
        if (numericOID2MatchingRuleUses.containsKey(use.getMatchingRuleOID())) {
            conflictingUse = numericOID2MatchingRuleUses.get(use.getMatchingRuleOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_MATCHING_RULE_USE.get(use.getNameOrOID(), use
                                .getMatchingRuleOID(), conflictingUse.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeMatchingRuleUse(conflictingUse);
        }
 
        numericOID2MatchingRuleUses.put(use.getMatchingRuleOID(), use);
        for (final String name : use.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<MatchingRuleUse> uses;
            if ((uses = name2MatchingRuleUses.get(lowerName)) == null) {
                name2MatchingRuleUses.put(lowerName, Collections.singletonList(use));
            } else if (uses.size() == 1) {
                uses = new ArrayList<MatchingRuleUse>(uses);
                uses.add(use);
                name2MatchingRuleUses.put(lowerName, uses);
            } else {
                uses.add(use);
            }
        }
    }
 
    private void addNameForm(final NameForm form, final boolean overwrite) {
        NameForm conflictingForm;
        if (numericOID2NameForms.containsKey(form.getOID())) {
            conflictingForm = numericOID2NameForms.get(form.getOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_NAME_FORM_OID.get(form.getNameOrOID(),
                                form.getOID(), conflictingForm.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeNameForm(conflictingForm);
        }
 
        numericOID2NameForms.put(form.getOID(), form);
        for (final String name : form.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<NameForm> forms;
            if ((forms = name2NameForms.get(lowerName)) == null) {
                name2NameForms.put(lowerName, Collections.singletonList(form));
            } else if (forms.size() == 1) {
                forms = new ArrayList<NameForm>(forms);
                forms.add(form);
                name2NameForms.put(lowerName, forms);
            } else {
                forms.add(form);
            }
        }
    }
 
    private void addObjectClass(final ObjectClass oc, final boolean overwrite) {
        ObjectClass conflictingOC;
        if (numericOID2ObjectClasses.containsKey(oc.getOID())) {
            conflictingOC = numericOID2ObjectClasses.get(oc.getOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_OBJECTCLASS_OID1.get(oc.getNameOrOID(), oc.getOID(),
                                conflictingOC.getNameOrOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeObjectClass(conflictingOC);
        }
 
        numericOID2ObjectClasses.put(oc.getOID(), oc);
        for (final String name : oc.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            List<ObjectClass> classes;
            if ((classes = name2ObjectClasses.get(lowerName)) == null) {
                name2ObjectClasses.put(lowerName, Collections.singletonList(oc));
            } else if (classes.size() == 1) {
                classes = new ArrayList<ObjectClass>(classes);
                classes.add(oc);
                name2ObjectClasses.put(lowerName, classes);
            } else {
                classes.add(oc);
            }
        }
    }
 
    private void addSchema0(final Schema schema, final boolean overwrite) {
        // All of the schema elements must be duplicated because validation will
        // cause them to update all their internal references which, although
        // unlikely, may be different in the new schema.
 
        for (final Syntax syntax : schema.getSyntaxes()) {
            addSyntax(syntax.duplicate(), overwrite);
        }
 
        for (final MatchingRule matchingRule : schema.getMatchingRules()) {
            addMatchingRule(matchingRule.duplicate(), overwrite);
        }
 
        for (final MatchingRuleUse matchingRuleUse : schema.getMatchingRuleUses()) {
            addMatchingRuleUse(matchingRuleUse.duplicate(), overwrite);
        }
 
        for (final AttributeType attributeType : schema.getAttributeTypes()) {
            addAttributeType(attributeType.duplicate(), overwrite);
        }
 
        for (final ObjectClass objectClass : schema.getObjectClasses()) {
            addObjectClass(objectClass.duplicate(), overwrite);
        }
 
        for (final NameForm nameForm : schema.getNameForms()) {
            addNameForm(nameForm.duplicate(), overwrite);
        }
 
        for (final DITContentRule contentRule : schema.getDITContentRules()) {
            addDITContentRule(contentRule.duplicate(), overwrite);
        }
 
        for (final DITStructureRule structureRule : schema.getDITStuctureRules()) {
            addDITStructureRule(structureRule.duplicate(), overwrite);
        }
    }
 
    private void addSyntax(final Syntax syntax, final boolean overwrite) {
        Syntax conflictingSyntax;
        if (numericOID2Syntaxes.containsKey(syntax.getOID())) {
            conflictingSyntax = numericOID2Syntaxes.get(syntax.getOID());
            if (!overwrite) {
                final LocalizableMessage message =
                        ERR_SCHEMA_CONFLICTING_SYNTAX_OID.get(syntax.toString(), syntax.getOID(),
                                conflictingSyntax.getOID());
                throw new ConflictingSchemaElementException(message);
            }
            removeSyntax(conflictingSyntax);
        }
        numericOID2Syntaxes.put(syntax.getOID(), syntax);
    }
 
    private void lazyInitBuilder() {
        // Lazy initialization.
        if (numericOID2Syntaxes == null) {
            allowMalformedNamesAndOptions = true;
            allowMalformedJPEGPhotos = true;
            allowNonStandardTelephoneNumbers = true;
            allowZeroLengthDirectoryStrings = false;
 
            numericOID2Syntaxes = new LinkedHashMap<String, Syntax>();
            numericOID2MatchingRules = new LinkedHashMap<String, MatchingRule>();
            numericOID2MatchingRuleUses = new LinkedHashMap<String, MatchingRuleUse>();
            numericOID2AttributeTypes = new LinkedHashMap<String, AttributeType>();
            numericOID2ObjectClasses = new LinkedHashMap<String, ObjectClass>();
            numericOID2NameForms = new LinkedHashMap<String, NameForm>();
            numericOID2ContentRules = new LinkedHashMap<String, DITContentRule>();
            id2StructureRules = new LinkedHashMap<Integer, DITStructureRule>();
 
            name2MatchingRules = new LinkedHashMap<String, List<MatchingRule>>();
            name2MatchingRuleUses = new LinkedHashMap<String, List<MatchingRuleUse>>();
            name2AttributeTypes = new LinkedHashMap<String, List<AttributeType>>();
            name2ObjectClasses = new LinkedHashMap<String, List<ObjectClass>>();
            name2NameForms = new LinkedHashMap<String, List<NameForm>>();
            name2ContentRules = new LinkedHashMap<String, List<DITContentRule>>();
            name2StructureRules = new LinkedHashMap<String, List<DITStructureRule>>();
 
            objectClass2NameForms = new HashMap<String, List<NameForm>>();
            nameForm2StructureRules = new HashMap<String, List<DITStructureRule>>();
            warnings = new LinkedList<LocalizableMessage>();
        }
 
        if (copyOnWriteSchema != null) {
            // Copy the schema.
            addSchema0(copyOnWriteSchema, true);
 
            allowMalformedNamesAndOptions = copyOnWriteSchema.allowMalformedNamesAndOptions();
            allowMalformedJPEGPhotos = copyOnWriteSchema.allowMalformedJPEGPhotos();
            allowNonStandardTelephoneNumbers = copyOnWriteSchema.allowNonStandardTelephoneNumbers();
            allowZeroLengthDirectoryStrings = copyOnWriteSchema.allowZeroLengthDirectoryStrings();
 
            copyOnWriteSchema = null;
        }
    }
 
    private void preLazyInitBuilder(final String schemaName, final Schema copyOnWriteSchema) {
        this.schemaName = schemaName;
        this.copyOnWriteSchema = copyOnWriteSchema;
 
        this.allowMalformedNamesAndOptions = true;
        this.allowMalformedJPEGPhotos = true;
        this.allowNonStandardTelephoneNumbers = true;
        this.allowZeroLengthDirectoryStrings = false;
 
        this.numericOID2Syntaxes = null;
        this.numericOID2MatchingRules = null;
        this.numericOID2MatchingRuleUses = null;
        this.numericOID2AttributeTypes = null;
        this.numericOID2ObjectClasses = null;
        this.numericOID2NameForms = null;
        this.numericOID2ContentRules = null;
        this.id2StructureRules = null;
 
        this.name2MatchingRules = null;
        this.name2MatchingRuleUses = null;
        this.name2AttributeTypes = null;
        this.name2ObjectClasses = null;
        this.name2NameForms = null;
        this.name2ContentRules = null;
        this.name2StructureRules = null;
 
        this.objectClass2NameForms = null;
        this.nameForm2StructureRules = null;
        this.warnings = null;
    }
 
    private void removeAttributeType(final AttributeType attributeType) {
        numericOID2AttributeTypes.remove(attributeType.getOID());
        for (final String name : attributeType.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<AttributeType> attributes = name2AttributeTypes.get(lowerName);
            if (attributes != null && attributes.contains(attributeType)) {
                if (attributes.size() <= 1) {
                    name2AttributeTypes.remove(lowerName);
                } else {
                    attributes.remove(attributeType);
                }
            }
        }
    }
 
    private void removeDITContentRule(final DITContentRule rule) {
        numericOID2ContentRules.remove(rule.getStructuralClassOID());
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<DITContentRule> rules = name2ContentRules.get(lowerName);
            if (rules != null && rules.contains(rule)) {
                if (rules.size() <= 1) {
                    name2AttributeTypes.remove(lowerName);
                } else {
                    rules.remove(rule);
                }
            }
        }
    }
 
    private void removeDITStructureRule(final DITStructureRule rule) {
        id2StructureRules.remove(rule.getRuleID());
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<DITStructureRule> rules = name2StructureRules.get(lowerName);
            if (rules != null && rules.contains(rule)) {
                if (rules.size() <= 1) {
                    name2StructureRules.remove(lowerName);
                } else {
                    rules.remove(rule);
                }
            }
        }
    }
 
    private void removeMatchingRule(final MatchingRule rule) {
        numericOID2MatchingRules.remove(rule.getOID());
        for (final String name : rule.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<MatchingRule> rules = name2MatchingRules.get(lowerName);
            if (rules != null && rules.contains(rule)) {
                if (rules.size() <= 1) {
                    name2MatchingRules.remove(lowerName);
                } else {
                    rules.remove(rule);
                }
            }
        }
    }
 
    private void removeMatchingRuleUse(final MatchingRuleUse use) {
        numericOID2MatchingRuleUses.remove(use.getMatchingRuleOID());
        for (final String name : use.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<MatchingRuleUse> uses = name2MatchingRuleUses.get(lowerName);
            if (uses != null && uses.contains(use)) {
                if (uses.size() <= 1) {
                    name2MatchingRuleUses.remove(lowerName);
                } else {
                    uses.remove(use);
                }
            }
        }
    }
 
    private void removeNameForm(final NameForm form) {
        numericOID2NameForms.remove(form.getOID());
        name2NameForms.remove(form.getOID());
        for (final String name : form.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<NameForm> forms = name2NameForms.get(lowerName);
            if (forms != null && forms.contains(form)) {
                if (forms.size() <= 1) {
                    name2NameForms.remove(lowerName);
                } else {
                    forms.remove(form);
                }
            }
        }
    }
 
    private void removeObjectClass(final ObjectClass oc) {
        numericOID2ObjectClasses.remove(oc.getOID());
        name2ObjectClasses.remove(oc.getOID());
        for (final String name : oc.getNames()) {
            final String lowerName = StaticUtils.toLowerCase(name);
            final List<ObjectClass> classes = name2ObjectClasses.get(lowerName);
            if (classes != null && classes.contains(oc)) {
                if (classes.size() <= 1) {
                    name2ObjectClasses.remove(lowerName);
                } else {
                    classes.remove(oc);
                }
            }
        }
    }
 
    private void removeSyntax(final Syntax syntax) {
        numericOID2Syntaxes.remove(syntax.getOID());
    }
 
    private void validate(final Schema schema) {
        // Verify all references in all elements
        for (final Syntax syntax : numericOID2Syntaxes.values().toArray(
                new Syntax[numericOID2Syntaxes.values().size()])) {
            try {
                syntax.validate(schema, warnings);
            } catch (final SchemaException e) {
                removeSyntax(syntax);
                warnings.add(ERR_SYNTAX_VALIDATION_FAIL
                        .get(syntax.toString(), e.getMessageObject()));
            }
        }
 
        for (final MatchingRule rule : numericOID2MatchingRules.values().toArray(
                new MatchingRule[numericOID2MatchingRules.values().size()])) {
            try {
                rule.validate(schema, warnings);
            } catch (final SchemaException e) {
                removeMatchingRule(rule);
                warnings.add(ERR_MR_VALIDATION_FAIL.get(rule.toString(), e.getMessageObject()));
            }
        }
 
        // Attribute types need special processing because they have
        // hierarchical
        // dependencies.
        final List<AttributeType> invalidAttributeTypes = new LinkedList<AttributeType>();
        for (final AttributeType attributeType : numericOID2AttributeTypes.values()) {
            attributeType.validate(schema, invalidAttributeTypes, warnings);
        }
 
        for (final AttributeType attributeType : invalidAttributeTypes) {
            removeAttributeType(attributeType);
        }
 
        // Object classes need special processing because they have hierarchical
        // dependencies.
        final List<ObjectClass> invalidObjectClasses = new LinkedList<ObjectClass>();
        for (final ObjectClass objectClass : numericOID2ObjectClasses.values()) {
            objectClass.validate(schema, invalidObjectClasses, warnings);
        }
 
        for (final ObjectClass objectClass : invalidObjectClasses) {
            removeObjectClass(objectClass);
        }
 
        for (final MatchingRuleUse use : numericOID2MatchingRuleUses.values().toArray(
                new MatchingRuleUse[numericOID2MatchingRuleUses.values().size()])) {
            try {
                use.validate(schema, warnings);
            } catch (final SchemaException e) {
                removeMatchingRuleUse(use);
                warnings.add(ERR_MRU_VALIDATION_FAIL.get(use.toString(), e.getMessageObject()));
            }
        }
 
        for (final NameForm form : numericOID2NameForms.values().toArray(
                new NameForm[numericOID2NameForms.values().size()])) {
            try {
                form.validate(schema, warnings);
 
                // build the objectClass2NameForms map
                List<NameForm> forms;
                final String ocOID = form.getStructuralClass().getOID();
                if ((forms = objectClass2NameForms.get(ocOID)) == null) {
                    objectClass2NameForms.put(ocOID, Collections.singletonList(form));
                } else if (forms.size() == 1) {
                    forms = new ArrayList<NameForm>(forms);
                    forms.add(form);
                    objectClass2NameForms.put(ocOID, forms);
                } else {
                    forms.add(form);
                }
            } catch (final SchemaException e) {
                removeNameForm(form);
                warnings.add(ERR_NAMEFORM_VALIDATION_FAIL
                        .get(form.toString(), e.getMessageObject()));
            }
        }
 
        for (final DITContentRule rule : numericOID2ContentRules.values().toArray(
                new DITContentRule[numericOID2ContentRules.values().size()])) {
            try {
                rule.validate(schema, warnings);
            } catch (final SchemaException e) {
                removeDITContentRule(rule);
                warnings.add(ERR_DCR_VALIDATION_FAIL.get(rule.toString(), e.getMessageObject()));
            }
        }
 
        // DIT structure rules need special processing because they have
        // hierarchical dependencies.
        final List<DITStructureRule> invalidStructureRules = new LinkedList<DITStructureRule>();
        for (final DITStructureRule rule : id2StructureRules.values()) {
            rule.validate(schema, invalidStructureRules, warnings);
        }
 
        for (final DITStructureRule rule : invalidStructureRules) {
            removeDITStructureRule(rule);
        }
 
        for (final DITStructureRule rule : id2StructureRules.values()) {
            // build the nameForm2StructureRules map
            List<DITStructureRule> rules;
            final String ocOID = rule.getNameForm().getOID();
            if ((rules = nameForm2StructureRules.get(ocOID)) == null) {
                nameForm2StructureRules.put(ocOID, Collections.singletonList(rule));
            } else if (rules.size() == 1) {
                rules = new ArrayList<DITStructureRule>(rules);
                rules.add(rule);
                nameForm2StructureRules.put(ocOID, rules);
            } else {
                rules.add(rule);
            }
        }
    }
}