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

Jean-Noël Rouvignac
28.10.2015 07e7cb84f497a907074b5ca46f3147f65488d6ed
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
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
 * or http://forgerock.org/license/CDDLv1.0.html.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at legal-notices/CDDLv1_0.txt.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2006-2010 Sun Microsystems, Inc.
 *      Portions Copyright 2011-2015 ForgeRock AS
 */
package org.opends.server.util;
 
import static org.opends.messages.UtilityMessages.*;
import static org.opends.server.util.ServerConstants.*;
 
import java.io.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
 
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
import org.forgerock.i18n.LocalizableMessage;
import org.forgerock.i18n.LocalizableMessageBuilder;
import org.forgerock.i18n.LocalizableMessageDescriptor;
import org.forgerock.i18n.slf4j.LocalizedLogger;
import org.forgerock.opendj.ldap.ByteSequence;
import org.forgerock.opendj.ldap.ByteString;
import org.forgerock.util.Reject;
import org.opends.messages.ToolMessages;
import org.opends.server.api.ClientConnection;
import org.opends.server.core.DirectoryServer;
import org.opends.server.core.ServerContext;
import org.opends.server.types.*;
 
import com.forgerock.opendj.cli.Argument;
import com.forgerock.opendj.cli.ArgumentException;
 
/**
 * This class defines a number of static utility methods that may be used
 * throughout the server.  Note that because of the frequency with which these
 * methods are expected to be used, very little debug logging will be performed
 * to prevent the log from filling up with unimportant calls and to reduce the
 * impact that debugging may have on performance.
 */
@org.opends.server.types.PublicAPI(
     stability=org.opends.server.types.StabilityLevel.UNCOMMITTED,
     mayInstantiate=false,
     mayExtend=false,
     mayInvoke=true)
public final class StaticUtils
{
  private static final LocalizedLogger logger = LocalizedLogger.getLoggerForThisClass();
 
  /** The number of bytes of a Java int. A Java int is 32 bits, i.e. 4 bytes. */
  public static final int INT_SIZE = 4;
  /** The number of bytes of a Java long. A Java int is 64 bits, i.e. 8 bytes. */
  public static final int LONG_SIZE = 8;
 
  /**
   * Number of bytes in a Kibibyte.
   * <p>
   * Example usage:
   * <pre>
   * int _10KB = 10 * KB;
   * </pre>
   */
  public static final int KB = 1024;
  /**
   * Number of bytes in a Mebibyte.
   * <p>
   * Example usage:
   * <pre>
   * int _10MB = 10 * MB;
   * </pre>
   */
  public static final int MB = KB * KB;
 
  /** Private constructor to prevent instantiation. */
  private StaticUtils() {
    // No implementation required.
  }
 
  /**
   * Construct a byte array containing the UTF-8 encoding of the
   * provided string. This is significantly faster
   * than calling {@link String#getBytes(String)} for ASCII strings.
   *
   * @param s
   *          The string to convert to a UTF-8 byte array.
   * @return Returns a byte array containing the UTF-8 encoding of the
   *         provided string.
   */
  public static byte[] getBytes(String s)
  {
    return com.forgerock.opendj.util.StaticUtils.getBytes(s);
  }
 
 
  /**
   * Returns the provided byte array decoded as a UTF-8 string without throwing
   * an UnsupportedEncodingException. This method is equivalent to:
   *
   * <pre>
   * try
   * {
   *   return new String(bytes, &quot;UTF-8&quot;);
   * }
   * catch (UnsupportedEncodingException e)
   * {
   *   // Should never happen: UTF-8 is always supported.
   *   throw new RuntimeException(e);
   * }
   * </pre>
   *
   * @param bytes
   *          The byte array to be decoded as a UTF-8 string.
   * @return The decoded string.
   */
  public static String decodeUTF8(final byte[] bytes)
  {
    Reject.ifNull(bytes);
 
    if (bytes.length == 0)
    {
      return "".intern();
    }
 
    final StringBuilder builder = new StringBuilder(bytes.length);
    final int sz = bytes.length;
 
    for (int i = 0; i < sz; i++)
    {
      final byte b = bytes[i];
      if ((b & 0x7f) != b)
      {
        try
        {
          builder.append(new String(bytes, i, (sz - i), "UTF-8"));
        }
        catch (UnsupportedEncodingException e)
        {
          // Should never happen: UTF-8 is always supported.
          throw new RuntimeException(e);
        }
        break;
      }
      builder.append((char) b);
    }
    return builder.toString();
  }
 
 
 
  /**
   * Retrieves a string representation of the provided byte in hexadecimal.
   *
   * @param b
   *            The byte for which to retrieve the hexadecimal string
   *            representation.
   * @return The string representation of the provided byte in hexadecimal.
   */
 
  public static String byteToHex(final byte b)
  {
    return com.forgerock.opendj.util.StaticUtils.byteToHex(b);
  }
  /**
   * Retrieves a string representation of the provided byte in hexadecimal.
   *
   * @param  b  The byte for which to retrieve the hexadecimal string
   *            representation.
   * @return The string representation of the provided byte in hexadecimal
   *         using lowercase characters.
   */
  public static String byteToLowerHex(final byte b)
  {
    return com.forgerock.opendj.util.StaticUtils.byteToLowerHex(b);
  }
 
  /**
   * Retrieves a string representation of the contents of the provided byte
   * array using hexadecimal characters with no space between each byte.
   *
   * @param  b  The byte array containing the data.
   *
   * @return  A string representation of the contents of the provided byte
   *          array using hexadecimal characters.
   */
  public static String bytesToHexNoSpace(byte[] b)
  {
    if (b == null || b.length == 0)
    {
      return "";
    }
 
    int arrayLength = b.length;
    StringBuilder buffer = new StringBuilder(arrayLength * 2);
 
    for (int i=0; i < arrayLength; i++)
    {
      buffer.append(byteToHex(b[i]));
    }
 
    return buffer.toString();
  }
 
 
 
  /**
   * Retrieves a string representation of the contents of the provided byte
   * array using hexadecimal characters and a space between each byte.
   *
   * @param  b  The byte array containing the data.
   * @return  A string representation of the contents of the provided byte
   *          array using hexadecimal characters.
   */
  public static String bytesToHex(byte[] b)
  {
    if (b == null || b.length == 0)
    {
      return "";
    }
 
    int arrayLength = b.length;
    StringBuilder buffer = new StringBuilder((arrayLength - 1) * 3 + 2);
    buffer.append(byteToHex(b[0]));
 
    for (int i=1; i < arrayLength; i++)
    {
      buffer.append(" ");
      buffer.append(byteToHex(b[i]));
    }
 
    return buffer.toString();
  }
 
  /**
   * Retrieves a string representation of the contents of the provided byte
   * sequence using hexadecimal characters and a space between each byte.
   *
   * @param b The byte sequence containing the data.
   * @return A string representation of the contents of the provided byte
   *         sequence using hexadecimal characters.
   */
  public static String bytesToHex(ByteSequence b)
  {
    if (b == null || b.length() == 0)
    {
      return "";
    }
 
    int arrayLength = b.length();
    StringBuilder buffer = new StringBuilder((arrayLength - 1) * 3 + 2);
    buffer.append(byteToHex(b.byteAt(0)));
 
    for (int i=1; i < arrayLength; i++)
    {
      buffer.append(" ");
      buffer.append(byteToHex(b.byteAt(i)));
    }
 
    return buffer.toString();
  }
 
 
 
  /**
   * Retrieves a string representation of the contents of the provided byte
   * array using hexadecimal characters and a colon between each byte.
   *
   * @param  b  The byte array containing the data.
   *
   * @return  A string representation of the contents of the provided byte
   *          array using hexadecimal characters.
   */
  public static String bytesToColonDelimitedHex(byte[] b)
  {
    if (b == null || b.length == 0)
    {
      return "";
    }
 
    int arrayLength = b.length;
    StringBuilder buffer = new StringBuilder((arrayLength - 1) * 3 + 2);
    buffer.append(byteToHex(b[0]));
 
    for (int i=1; i < arrayLength; i++)
    {
      buffer.append(":");
      buffer.append(byteToHex(b[i]));
    }
 
    return buffer.toString();
  }
 
 
 
  /**
   * Retrieves a string representation of the contents of the provided byte
   * buffer using hexadecimal characters and a space between each byte.
   *
   * @param  b  The byte buffer containing the data.
   *
   * @return  A string representation of the contents of the provided byte
   *          buffer using hexadecimal characters.
   */
  public static String bytesToHex(ByteBuffer b)
  {
    if (b == null)
    {
      return "";
    }
 
    int position = b.position();
    int limit    = b.limit();
    int length   = limit - position;
 
    if (length == 0)
    {
      return "";
    }
 
    StringBuilder buffer = new StringBuilder((length - 1) * 3 + 2);
    buffer.append(byteToHex(b.get()));
 
    for (int i=1; i < length; i++)
    {
      buffer.append(" ");
      buffer.append(byteToHex(b.get()));
    }
 
    b.position(position);
    b.limit(limit);
 
    return buffer.toString();
  }
 
 
 
  /**
   * Appends a string representation of the provided byte array to the given
   * buffer using the specified indent.  The data will be formatted with sixteen
   * hex bytes in a row followed by the ASCII representation, then wrapping to a
   * new line as necessary.
   *
   * @param  buffer  The buffer to which the information is to be appended.
   * @param  b       The byte array containing the data to write.
   * @param  indent  The number of spaces to indent the output.
   */
  public static void byteArrayToHexPlusAscii(StringBuilder buffer, byte[] b,
                                             int indent)
  {
    StringBuilder indentBuf = new StringBuilder(indent);
    for (int i=0 ; i < indent; i++)
    {
      indentBuf.append(' ');
    }
 
 
 
    int length = b.length;
    int pos    = 0;
    while (length - pos >= 16)
    {
      StringBuilder asciiBuf = new StringBuilder(17);
 
      buffer.append(indentBuf);
      buffer.append(byteToHex(b[pos]));
      asciiBuf.append(byteToASCII(b[pos]));
      pos++;
 
      for (int i=1; i < 16; i++, pos++)
      {
        buffer.append(' ');
        buffer.append(byteToHex(b[pos]));
        asciiBuf.append(byteToASCII(b[pos]));
 
        if (i == 7)
        {
          buffer.append("  ");
          asciiBuf.append(' ');
        }
      }
 
      buffer.append("  ");
      buffer.append(asciiBuf);
      buffer.append(EOL);
    }
 
 
    int remaining = length - pos;
    if (remaining > 0)
    {
      StringBuilder asciiBuf = new StringBuilder(remaining+1);
 
      buffer.append(indentBuf);
      buffer.append(byteToHex(b[pos]));
      asciiBuf.append(byteToASCII(b[pos]));
      pos++;
 
      for (int i=1; i < 16; i++)
      {
        buffer.append(' ');
 
        if (i < remaining)
        {
          buffer.append(byteToHex(b[pos]));
          asciiBuf.append(byteToASCII(b[pos]));
          pos++;
        }
        else
        {
          buffer.append("  ");
        }
 
        if (i == 7)
        {
          buffer.append("  ");
 
          if (i < remaining)
          {
            asciiBuf.append(' ');
          }
        }
      }
 
      buffer.append("  ");
      buffer.append(asciiBuf);
      buffer.append(EOL);
    }
  }
 
  private static char byteToASCII(byte b)
  {
    return com.forgerock.opendj.util.StaticUtils.byteToASCII(b);
  }
 
  /**
   * Appends a string representation of the remaining unread data in the
   * provided byte buffer to the given buffer using the specified indent.
   * The data will be formatted with sixteen hex bytes in a row followed by
   * the ASCII representation, then wrapping to a new line as necessary.
   * The state of the byte buffer is not changed.
   *
   * @param  buffer  The buffer to which the information is to be appended.
   * @param  b       The byte buffer containing the data to write.
   *                 The data from the position to the limit is written.
   * @param  indent  The number of spaces to indent the output.
   */
  public static void byteArrayToHexPlusAscii(StringBuilder buffer, ByteBuffer b,
                                             int indent)
  {
    StringBuilder indentBuf = new StringBuilder(indent);
    for (int i=0 ; i < indent; i++)
    {
      indentBuf.append(' ');
    }
 
 
    int position = b.position();
    int limit    = b.limit();
    int length   = limit - position;
    int pos      = 0;
    while (length - pos >= 16)
    {
      StringBuilder asciiBuf = new StringBuilder(17);
 
      byte currentByte = b.get();
      buffer.append(indentBuf);
      buffer.append(byteToHex(currentByte));
      asciiBuf.append(byteToASCII(currentByte));
      pos++;
 
      for (int i=1; i < 16; i++, pos++)
      {
        currentByte = b.get();
        buffer.append(' ');
        buffer.append(byteToHex(currentByte));
        asciiBuf.append(byteToASCII(currentByte));
 
        if (i == 7)
        {
          buffer.append("  ");
          asciiBuf.append(' ');
        }
      }
 
      buffer.append("  ");
      buffer.append(asciiBuf);
      buffer.append(EOL);
    }
 
 
    int remaining = length - pos;
    if (remaining > 0)
    {
      StringBuilder asciiBuf = new StringBuilder(remaining+1);
 
      byte currentByte = b.get();
      buffer.append(indentBuf);
      buffer.append(byteToHex(currentByte));
      asciiBuf.append(byteToASCII(currentByte));
 
      for (int i=1; i < 16; i++)
      {
        buffer.append(' ');
 
        if (i < remaining)
        {
          currentByte = b.get();
          buffer.append(byteToHex(currentByte));
          asciiBuf.append(byteToASCII(currentByte));
        }
        else
        {
          buffer.append("  ");
        }
 
        if (i == 7)
        {
          buffer.append("  ");
 
          if (i < remaining)
          {
            asciiBuf.append(' ');
          }
        }
      }
 
      buffer.append("  ");
      buffer.append(asciiBuf);
      buffer.append(EOL);
    }
 
    b.position(position);
    b.limit(limit);
  }
 
 
 
  /**
   * Compare two byte arrays for order. Returns a negative integer,
   * zero, or a positive integer as the first argument is less than,
   * equal to, or greater than the second.
   *
   * @param a
   *          The first byte array to be compared.
   * @param a2
   *          The second byte array to be compared.
   * @return Returns a negative integer, zero, or a positive integer
   *         if the first byte array is less than, equal to, or greater
   *         than the second.
   */
  public static int compare(byte[] a, byte[] a2) {
    if (a == a2) {
      return 0;
    }
 
    if (a == null) {
      return -1;
    }
 
    if (a2 == null) {
      return 1;
    }
 
    int minLength = Math.min(a.length, a2.length);
    for (int i = 0; i < minLength; i++) {
      int firstByte = 0xFF & a[i];
      int secondByte = 0xFF & a2[i];
      if (firstByte != secondByte) {
        if (firstByte < secondByte) {
          return -1;
        } else if (firstByte > secondByte) {
          return 1;
        }
      }
    }
 
    return a.length - a2.length;
  }
 
 
 
  /**
   * Indicates whether the two array lists are equal. They will be
   * considered equal if they have the same number of elements, and
   * the corresponding elements between them are equal (in the same
   * order).
   *
   * @param list1
   *          The first list for which to make the determination.
   * @param list2
   *          The second list for which to make the determination.
   * @return <CODE>true</CODE> if the two array lists are equal, or
   *         <CODE>false</CODE> if they are not.
   */
  public static boolean listsAreEqual(List<?> list1, List<?> list2)
  {
    if (list1 == null)
    {
      return list2 == null;
    }
    else if (list2 == null)
    {
      return false;
    }
 
    int numElements = list1.size();
    if (numElements != list2.size())
    {
      return false;
    }
 
    // If either of the lists doesn't support random access, then fall back
    // on their equals methods and go ahead and create some garbage with the
    // iterators.
    if (!(list1 instanceof RandomAccess) ||
        !(list2 instanceof RandomAccess))
    {
      return list1.equals(list2);
    }
 
    // Otherwise we can just retrieve the elements efficiently via their index.
    for (int i=0; i < numElements; i++)
    {
      Object o1 = list1.get(i);
      Object o2 = list2.get(i);
 
      if (o1 == null)
      {
        if (o2 != null)
        {
          return false;
        }
      }
      else if (! o1.equals(o2))
      {
        return false;
      }
    }
 
    return true;
  }
 
  /**
   * Retrieves the best human-readable message for the provided exception.  For
   * exceptions defined in the OpenDJ project, it will attempt to use the
   * message (combining it with the message ID if available).  For some
   * exceptions that use encapsulation (e.g., InvocationTargetException), it
   * will be unwrapped and the cause will be treated.  For all others, the
   *
   *
   * @param  t  The {@code Throwable} object for which to retrieve the message.
   *
   * @return  The human-readable message generated for the provided exception.
   */
  public static LocalizableMessage getExceptionMessage(Throwable t)
  {
    if (t instanceof IdentifiedException)
    {
      IdentifiedException ie = (IdentifiedException) t;
 
      StringBuilder message = new StringBuilder();
      message.append(ie.getMessage());
      message.append(" (id=");
      LocalizableMessage ieMsg = ie.getMessageObject();
      if (ieMsg != null) {
        message.append(ieMsg.resourceName()).append("-").append(ieMsg.ordinal());
      } else {
        message.append("-1");
      }
      message.append(")");
      return LocalizableMessage.raw(message.toString());
    }
    else
    {
      return com.forgerock.opendj.util.StaticUtils.getExceptionMessage(t);
    }
  }
 
 
 
  /**
   * Retrieves a stack trace from the provided exception as a single-line
   * string.
   *
   * @param  t  The exception for which to retrieve the stack trace.
   *
   * @return  A stack trace from the provided exception as a single-line string.
   */
  public static String stackTraceToSingleLineString(Throwable t)
  {
    return com.forgerock.opendj.util.StaticUtils.stackTraceToSingleLineString(t, DynamicConstants.DEBUG_BUILD);
  }
 
 
 
  /**
   * Appends a single-line string representation of the provided exception to
   * the given buffer.
   *
   * @param  buffer  The buffer to which the information is to be appended.
   * @param  t       The exception for which to retrieve the stack trace.
   */
  public static void stackTraceToSingleLineString(StringBuilder buffer,
                                                  Throwable t)
  {
    com.forgerock.opendj.util.StaticUtils.stackTraceToSingleLineString(buffer, t, DynamicConstants.DEBUG_BUILD);
  }
 
 
 
  /**
   * Retrieves a string representation of the stack trace for the provided
   * exception.
   *
   * @param  t  The exception for which to retrieve the stack trace.
   *
   * @return  A string representation of the stack trace for the provided
   *          exception.
   */
  public static String stackTraceToString(Throwable t)
  {
    StringBuilder buffer = new StringBuilder();
    stackTraceToString(buffer, t);
    return buffer.toString();
  }
 
  /**
   * Check if the stack trace of provided exception contains a given cause.
   *
   * @param throwable
   *          exception that may contain the cause
   * @param searchedCause
   *          class of the cause to look for. Any subclass will match.
   * @return true if and only if the given cause is found as a cause of any
   *         level in the provided exception.
   */
  public static boolean stackTraceContainsCause(
      Throwable throwable, Class<? extends Throwable> searchedCause)
  {
    Throwable t = throwable;
    while ((t = t.getCause()) != null)
    {
      if (searchedCause.isAssignableFrom(t.getClass()))
      {
        return true;
      }
 
    }
    return false;
  }
 
  /**
   * Appends a string representation of the stack trace for the provided
   * exception to the given buffer.
   *
   * @param  buffer  The buffer to which the information is to be appended.
   * @param  t       The exception for which to retrieve the stack trace.
   */
  public static void stackTraceToString(StringBuilder buffer, Throwable t)
  {
    if (t == null)
    {
      return;
    }
 
    buffer.append(t);
 
    for (StackTraceElement e : t.getStackTrace())
    {
      buffer.append(EOL);
      buffer.append("  ");
      buffer.append(e.getClassName());
      buffer.append(".");
      buffer.append(e.getMethodName());
      buffer.append("(");
      buffer.append(e.getFileName());
      buffer.append(":");
      buffer.append(e.getLineNumber());
      buffer.append(")");
    }
 
    while (t.getCause() != null)
    {
      t = t.getCause();
      buffer.append(EOL);
      buffer.append("Caused by ");
      buffer.append(t);
 
      for (StackTraceElement e : t.getStackTrace())
      {
        buffer.append(EOL);
        buffer.append("  ");
        buffer.append(e.getClassName());
        buffer.append(".");
        buffer.append(e.getMethodName());
        buffer.append("(");
        buffer.append(e.getFileName());
        buffer.append(":");
        buffer.append(e.getLineNumber());
        buffer.append(")");
      }
    }
 
    buffer.append(EOL);
  }
 
 
 
  /**
   * Retrieves a backtrace for the current thread consisting only of filenames
   * and line numbers that may be useful in debugging the origin of problems
   * that should not have happened.  Note that this may be an expensive
   * operation to perform, so it should only be used for error conditions or
   * debugging.
   *
   * @return  A backtrace for the current thread.
   */
  public static String getBacktrace()
  {
    StringBuilder buffer = new StringBuilder();
 
    StackTraceElement[] elements = Thread.currentThread().getStackTrace();
 
    if (elements.length > 1)
    {
      buffer.append(elements[1].getFileName());
      buffer.append(":");
      buffer.append(elements[1].getLineNumber());
 
      for (int i=2; i < elements.length; i++)
      {
        buffer.append(" ");
        buffer.append(elements[i].getFileName());
        buffer.append(":");
        buffer.append(elements[i].getLineNumber());
      }
    }
 
    return buffer.toString();
  }
 
 
 
  /**
   * Retrieves a backtrace for the provided exception consisting of only
   * filenames and line numbers that may be useful in debugging the origin of
   * problems.  This is less expensive than the call to
   * <CODE>getBacktrace</CODE> without any arguments if an exception has already
   * been thrown.
   *
   * @param  t  The exception for which to obtain the backtrace.
   *
   * @return  A backtrace from the provided exception.
   */
  public static String getBacktrace(Throwable t)
  {
    StringBuilder buffer = new StringBuilder();
 
    StackTraceElement[] elements = t.getStackTrace();
 
    if (elements.length > 0)
    {
      buffer.append(elements[0].getFileName());
      buffer.append(":");
      buffer.append(elements[0].getLineNumber());
 
      for (int i=1; i < elements.length; i++)
      {
        buffer.append(" ");
        buffer.append(elements[i].getFileName());
        buffer.append(":");
        buffer.append(elements[i].getLineNumber());
      }
    }
 
    return buffer.toString();
  }
 
 
 
  /**
   * Indicates whether the provided character is a numeric digit.
   *
   * @param  c  The character for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided character represents a numeric
   *          digit, or <CODE>false</CODE> if not.
   */
  public static boolean isDigit(final char c) {
    return com.forgerock.opendj.util.StaticUtils.isDigit(c);
  }
 
 
 
  /**
   * Indicates whether the provided character is an ASCII alphabetic character.
   *
   * @param  c  The character for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided value is an uppercase or
   *          lowercase ASCII alphabetic character, or <CODE>false</CODE> if it
   *          is not.
   */
  public static boolean isAlpha(final char c) {
    return com.forgerock.opendj.util.StaticUtils.isAlpha(c);
  }
 
  /**
   * Indicates whether the provided character is a hexadecimal digit.
   *
   * @param  c  The character for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided character represents a
   *          hexadecimal digit, or <CODE>false</CODE> if not.
   */
  public static boolean isHexDigit(final char c) {
    return com.forgerock.opendj.util.StaticUtils.isHexDigit(c);
  }
 
  /**
   * Indicates whether the provided byte represents a hexadecimal digit.
   *
   * @param  b  The byte for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided byte represents a hexadecimal
   *          digit, or <CODE>false</CODE> if not.
   */
  public static boolean isHexDigit(byte b)
  {
    switch (b)
    {
      case '0':
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      case 'A':
      case 'B':
      case 'C':
      case 'D':
      case 'E':
      case 'F':
      case 'a':
      case 'b':
      case 'c':
      case 'd':
      case 'e':
      case 'f':
        return true;
      default:
        return false;
    }
  }
 
 
 
  /**
   * Converts the provided hexadecimal string to a byte array.
   *
   * @param  hexString  The hexadecimal string to convert to a byte array.
   *
   * @return  The byte array containing the binary representation of the
   *          provided hex string.
   *
   * @throws  ParseException  If the provided string contains invalid
   *                          hexadecimal digits or does not contain an even
   *                          number of digits.
   */
  public static byte[] hexStringToByteArray(String hexString)
         throws ParseException
  {
    int length;
    if (hexString == null || ((length = hexString.length()) == 0))
    {
      return new byte[0];
    }
 
 
    if ((length % 2) == 1)
    {
      LocalizableMessage message = ERR_HEX_DECODE_INVALID_LENGTH.get(hexString);
      throw new ParseException(message.toString(), 0);
    }
 
 
    int pos = 0;
    int arrayLength = length / 2;
    byte[] returnArray = new byte[arrayLength];
    for (int i=0; i < arrayLength; i++)
    {
      switch (hexString.charAt(pos++))
      {
        case '0':
          returnArray[i] = 0x00;
          break;
        case '1':
          returnArray[i] = 0x10;
          break;
        case '2':
          returnArray[i] = 0x20;
          break;
        case '3':
          returnArray[i] = 0x30;
          break;
        case '4':
          returnArray[i] = 0x40;
          break;
        case '5':
          returnArray[i] = 0x50;
          break;
        case '6':
          returnArray[i] = 0x60;
          break;
        case '7':
          returnArray[i] = 0x70;
          break;
        case '8':
          returnArray[i] = (byte) 0x80;
          break;
        case '9':
          returnArray[i] = (byte) 0x90;
          break;
        case 'A':
        case 'a':
          returnArray[i] = (byte) 0xA0;
          break;
        case 'B':
        case 'b':
          returnArray[i] = (byte) 0xB0;
          break;
        case 'C':
        case 'c':
          returnArray[i] = (byte) 0xC0;
          break;
        case 'D':
        case 'd':
          returnArray[i] = (byte) 0xD0;
          break;
        case 'E':
        case 'e':
          returnArray[i] = (byte) 0xE0;
          break;
        case 'F':
        case 'f':
          returnArray[i] = (byte) 0xF0;
          break;
        default:
          LocalizableMessage message = ERR_HEX_DECODE_INVALID_CHARACTER.get(
              hexString, hexString.charAt(pos-1));
          throw new ParseException(message.toString(), 0);
      }
 
      switch (hexString.charAt(pos++))
      {
        case '0':
          // No action required.
          break;
        case '1':
          returnArray[i] |= 0x01;
          break;
        case '2':
          returnArray[i] |= 0x02;
          break;
        case '3':
          returnArray[i] |= 0x03;
          break;
        case '4':
          returnArray[i] |= 0x04;
          break;
        case '5':
          returnArray[i] |= 0x05;
          break;
        case '6':
          returnArray[i] |= 0x06;
          break;
        case '7':
          returnArray[i] |= 0x07;
          break;
        case '8':
          returnArray[i] |= 0x08;
          break;
        case '9':
          returnArray[i] |= 0x09;
          break;
        case 'A':
        case 'a':
          returnArray[i] |= 0x0A;
          break;
        case 'B':
        case 'b':
          returnArray[i] |= 0x0B;
          break;
        case 'C':
        case 'c':
          returnArray[i] |= 0x0C;
          break;
        case 'D':
        case 'd':
          returnArray[i] |= 0x0D;
          break;
        case 'E':
        case 'e':
          returnArray[i] |= 0x0E;
          break;
        case 'F':
        case 'f':
          returnArray[i] |= 0x0F;
          break;
        default:
          LocalizableMessage message = ERR_HEX_DECODE_INVALID_CHARACTER.get(
              hexString, hexString.charAt(pos-1));
          throw new ParseException(message.toString(), 0);
      }
    }
 
    return returnArray;
  }
 
 
 
  /**
   * Indicates whether the provided value needs to be base64-encoded if it is
   * represented in LDIF form.
   *
   * @param  valueBytes  The binary representation of the attribute value for
   *                     which to make the determination.
   *
   * @return  <CODE>true</CODE> if the value needs to be base64-encoded if it is
   *          represented in LDIF form, or <CODE>false</CODE> if not.
   */
  public static boolean needsBase64Encoding(ByteSequence valueBytes)
  {
    int length;
    if (valueBytes == null || ((length = valueBytes.length()) == 0))
    {
      return false;
    }
 
 
    // If the value starts with a space, colon, or less than, then it needs to
    // be base64-encoded.
    switch (valueBytes.byteAt(0))
    {
      case 0x20: // Space
      case 0x3A: // Colon
      case 0x3C: // Less-than
        return true;
    }
 
 
    // If the value ends with a space, then it needs to be base64-encoded.
    if (length > 1 && valueBytes.byteAt(length - 1) == 0x20)
    {
      return true;
    }
 
 
    // If the value contains a null, newline, or return character, then it needs
    // to be base64-encoded.
    byte b;
    for (int i = 0; i < valueBytes.length(); i++)
    {
      b = valueBytes.byteAt(i);
      if (b < 0 || 127 < b)
      {
        return true;
      }
 
      switch (b)
      {
        case 0x00: // Null
        case 0x0A: // New line
        case 0x0D: // Carriage return
          return true;
      }
    }
 
 
    // If we've made it here, then there's no reason to base64-encode.
    return false;
  }
 
 
 
  /**
   * Indicates whether the provided value needs to be base64-encoded if it is
   * represented in LDIF form.
   *
   * @param  valueString  The string representation of the attribute value for
   *                      which to make the determination.
   *
   * @return  <CODE>true</CODE> if the value needs to be base64-encoded if it is
   *          represented in LDIF form, or <CODE>false</CODE> if not.
   */
  public static boolean needsBase64Encoding(String valueString)
  {
    int length;
    if (valueString == null || ((length = valueString.length()) == 0))
    {
      return false;
    }
 
 
    // If the value starts with a space, colon, or less than, then it needs to
    // be base64-encoded.
    switch (valueString.charAt(0))
    {
      case ' ':
      case ':':
      case '<':
        return true;
    }
 
 
    // If the value ends with a space, then it needs to be base64-encoded.
    if (length > 1 && valueString.charAt(length - 1) == ' ')
    {
      return true;
    }
 
 
    // If the value contains a null, newline, or return character, then it needs
    // to be base64-encoded.
    for (int i=0; i < length; i++)
    {
      char c = valueString.charAt(i);
      if (c <= 0 || c == 0x0A || c == 0x0D || c > 127)
      {
        return true;
      }
    }
 
 
    // If we've made it here, then there's no reason to base64-encode.
    return false;
  }
 
 
 
  /**
   * Indicates whether the use of the exec method will be allowed on this
   * system.  It will be allowed by default, but that capability will be removed
   * if the org.opends.server.DisableExec system property is set and has any
   * value other than "false", "off", "no", or "0".
   *
   * @return  <CODE>true</CODE> if the use of the exec method should be allowed,
   *          or <CODE>false</CODE> if it should not be allowed.
   */
  public static boolean mayUseExec()
  {
    return !DirectoryServer.getEnvironmentConfig().disableExec();
  }
 
 
 
  /**
   * Executes the specified command on the system and captures its output.  This
   * will not return until the specified process has completed.
   *
   * @param  command           The command to execute.
   * @param  args              The set of arguments to provide to the command.
   * @param  workingDirectory  The working directory to use for the command, or
   *                           <CODE>null</CODE> if the default directory
   *                           should be used.
   * @param  environment       The set of environment variables that should be
   *                           set when executing the command, or
   *                           <CODE>null</CODE> if none are needed.
   * @param  output            The output generated by the command while it was
   *                           running.  This will include both standard
   *                           output and standard error.  It may be
   *                           <CODE>null</CODE> if the output does not need to
   *                           be captured.
   *
   * @return  The exit code for the command.
   *
   * @throws  IOException  If an I/O problem occurs while trying to execute the
   *                       command.
   *
   * @throws  SecurityException  If the security policy will not allow the
   *                             command to be executed.
   *
   * @throws InterruptedException If the current thread is interrupted by
   *                              another thread while it is waiting, then
   *                              the wait is ended and an InterruptedException
   *                              is thrown.
   */
  public static int exec(String command, String[] args, File workingDirectory,
                         Map<String,String> environment, List<String> output)
         throws IOException, SecurityException, InterruptedException
  {
    // See whether we'll allow the use of exec on this system.  If not, then
    // throw an exception.
    if (! mayUseExec())
    {
      throw new SecurityException(ERR_EXEC_DISABLED.get(command).toString());
    }
 
 
    ArrayList<String> commandAndArgs = new ArrayList<>();
    commandAndArgs.add(command);
    if (args != null && args.length > 0)
    {
      Collections.addAll(commandAndArgs, args);
    }
 
    ProcessBuilder processBuilder = new ProcessBuilder(commandAndArgs);
    processBuilder.redirectErrorStream(true);
 
    if (workingDirectory != null && workingDirectory.isDirectory())
    {
      processBuilder.directory(workingDirectory);
    }
 
    if (environment != null && !environment.isEmpty())
    {
      processBuilder.environment().putAll(environment);
    }
 
    Process process = processBuilder.start();
 
    // We must exhaust stdout and stderr before calling waitfor. Since we
    // redirected the error stream, we just have to read from stdout.
    InputStream processStream =  process.getInputStream();
    BufferedReader reader =
        new BufferedReader(new InputStreamReader(processStream));
    String line = null;
 
    try
    {
      while((line = reader.readLine()) != null)
      {
        if(output != null)
        {
          output.add(line);
        }
      }
    }
    catch(IOException ioe)
    {
      // If this happens, then we have no choice but to forcefully terminate
      // the process.
      try
      {
        process.destroy();
      }
      catch (Exception e)
      {
        logger.traceException(e);
      }
 
      throw ioe;
    }
    finally
    {
      try
      {
        reader.close();
      }
      catch(IOException e)
      {
        logger.traceException(e);
      }
    }
 
    return process.waitFor();
  }
 
 
 
  /**
   * Indicates whether the provided string contains a name or OID for a schema
   * element like an attribute type or objectclass.
   *
   * @param  element        The string containing the substring for which to
   *                        make the determination.
   * @param  startPos       The position of the first character that is to be
   *                        checked.
   * @param  endPos         The position of the first character after the start
   *                        position that is not to be checked.
   * @param  invalidReason  The buffer to which the invalid reason is to be
   *                        appended if a problem is found.
   *
   * @return  <CODE>true</CODE> if the provided string contains a valid name or
   *          OID for a schema element, or <CODE>false</CODE> if it does not.
   */
  public static boolean isValidSchemaElement(String element, int startPos,
                                             int endPos,
                                             LocalizableMessageBuilder invalidReason)
  {
    if (element == null || startPos >= endPos)
    {
      invalidReason.append(ERR_SCHEMANAME_EMPTY_VALUE.get());
      return false;
    }
 
 
    char c = element.charAt(startPos);
    if (isAlpha(c))
    {
      // This can only be a name and not an OID.  The only remaining characters
      // must be letters, digits, dashes, and possibly the underscore.
      for (int i=startPos+1; i < endPos; i++)
      {
        c = element.charAt(i);
        if (!isAlpha(c)
            && !isDigit(c)
            && c != '-'
            && (c != '_' || !DirectoryServer.allowAttributeNameExceptions()))
        {
          // This is an illegal character for an attribute name.
          invalidReason.append(ERR_SCHEMANAME_ILLEGAL_CHAR.get(element, c, i));
          return false;
        }
      }
    }
    else if (isDigit(c))
    {
      // This should indicate an OID, but it may also be a name if name
      // exceptions are enabled.  Since we don't know for sure, we'll just
      // hold off until we know for sure.
      boolean isKnown    = !DirectoryServer.allowAttributeNameExceptions();
      boolean isNumeric  = true;
      boolean lastWasDot = false;
 
      for (int i=startPos+1; i < endPos; i++)
      {
        c = element.charAt(i);
        if (c == '.')
        {
          if (isKnown)
          {
            if (isNumeric)
            {
              // This is probably legal unless the last character was also a
              // period.
              if (lastWasDot)
              {
                invalidReason.append(ERR_SCHEMANAME_CONSECUTIVE_PERIODS.get(
                        element, i));
                return false;
              }
              else
              {
                lastWasDot = true;
              }
            }
            else
            {
              // This is an illegal character.
              invalidReason.append(ERR_SCHEMANAME_ILLEGAL_CHAR.get(
                      element, c, i));
              return false;
            }
          }
          else
          {
            // Now we know that this must be a numeric OID and not an attribute
            // name with exceptions allowed.
            lastWasDot = true;
            isKnown    = true;
            isNumeric  = true;
          }
        }
        else
        {
          lastWasDot = false;
 
          if (isAlpha(c) || c == '-' || c == '_')
          {
            if (isKnown)
            {
              if (isNumeric)
              {
                // This is an illegal character for a numeric OID.
                invalidReason.append(ERR_SCHEMANAME_ILLEGAL_CHAR.get(
                        element, c, i));
                return false;
              }
            }
            else
            {
              // Now we know that this must be an attribute name with exceptions
              // allowed and not a numeric OID.
              isKnown   = true;
              isNumeric = false;
            }
          }
          else if (! isDigit(c))
          {
            // This is an illegal character.
            invalidReason.append(ERR_SCHEMANAME_ILLEGAL_CHAR.get(
                    element, c, i));
            return false;
          }
        }
      }
    }
    else
    {
      // This is an illegal character.
      invalidReason.append(ERR_SCHEMANAME_ILLEGAL_CHAR.get(
              element, c, startPos));
      return false;
    }
 
 
    // If we've gotten here, then the value is fine.
    return true;
  }
 
 
 
  /**
   * Indicates whether the provided TCP address is already in use.
   *
   * @param  address        IP address of the TCP address for which to make
   *                        the determination.
   * @param  port           TCP port number of the TCP address for which to
   *                        make the determination.
   * @param  allowReuse     Whether or not TCP address reuse is allowed when
   *                        making the determination.
   *
   * @return  <CODE>true</CODE> if the provided TCP address is already in
   *          use, or <CODE>false</CODE> otherwise.
   */
  public static boolean isAddressInUse(
    InetAddress address, int port,
    boolean allowReuse)
  {
    // Return pessimistic.
    boolean isInUse = true;
    Socket clientSocket = null;
    ServerSocket serverSocket = null;
    try {
      // HACK:
      // With dual stacks we can have a situation when INADDR_ANY/PORT
      // is bound in TCP4 space but available in TCP6 space and since
      // JavaServerSocket implemantation will always use TCP46 on dual
      // stacks the bind below will always succeed in such cases thus
      // shadowing anything that is already bound to INADDR_ANY/PORT.
      // While technically correct, with IPv4 and IPv6 being separate
      // address spaces, it presents a problem to end users because a
      // common case scenario is to have a single service serving both
      // address spaces ie listening to the same port in both spaces
      // on wildcard addresses 0 and ::. ServerSocket implemantation
      // does not provide any means of working with each address space
      // separately such as doing TCP4 or TCP6 only binds thus we have
      // to do a dummy connect to INADDR_ANY/PORT to check if it is
      // bound to something already. This is only needed for wildcard
      // addresses as specific IPv4 or IPv6 addresses will always be
      // handled in their respective address space.
      if (address.isAnyLocalAddress()) {
        clientSocket = new Socket();
        try {
          // This might fail on some stacks but this is the best we
          // can do. No need for explicit timeout since it is local
          // address and we have to know for sure unless it fails.
          clientSocket.connect(new InetSocketAddress(address, port));
        } catch (IOException e) {
        // Expected, ignore.
        }
        if (clientSocket.isConnected()) {
          return true;
        }
      }
      serverSocket = new ServerSocket();
      serverSocket.setReuseAddress(allowReuse);
      serverSocket.bind(new InetSocketAddress(address, port));
      isInUse = false;
    } catch (IOException e) {
      isInUse = true;
    } finally {
      try {
        if (serverSocket != null) {
          serverSocket.close();
        }
      } catch (Exception e) {}
      try {
        if (clientSocket != null) {
          clientSocket.close();
        }
      } catch (Exception e) {}
    }
    return isInUse;
  }
 
 
 
  /**
   * Returns a lower-case string representation of a given string, verifying for null input string.
   * {@see com.forgerock.opendj.util.StaticUtils#toLowerCase(String s)}
   *
   * @param s the mixed case string
   * @return a lower-case string
   */
  public static String toLowerCase(String s)
  {
    return (s == null ? null : com.forgerock.opendj.util.StaticUtils.toLowerCase(s));
  }
 
  /**
   * Appends a lower-case string representation of a given ByteSequence to a StringBuilder,
   * verifying for null input.
   * {@see com.forgerock.opendj.util.StaticUtils#toLowerCase(ByteSequence s, StringBuilder string)}
   *
   * @param  b       The byte array for which to obtain the lowercase string
   *                 representation.
   * @param  buffer  The buffer to which the lowercase form of the string should
   *                 be appended.
   * @param  trim    Indicates whether leading and trailing spaces should be
   *                 omitted from the string representation.
   */
  public static void toLowerCase(ByteSequence b, StringBuilder buffer, boolean trim)
  {
    if (b == null)
    {
      return;
    }
 
    if (trim)
    {
      int begin = 0;
      int end = b.length() - 1;
      while (begin <= end)
      {
        if (b.byteAt(begin) == ' ')
        {
          begin++;
        }
        else if (b.byteAt(end) == ' ')
        {
          end--;
        }
        else
        {
          break;
        }
      }
      if (begin > 0 || end < b.length() - 1)
      {
        b = b.subSequence(begin, end + 1);
      }
    }
 
    com.forgerock.opendj.util.StaticUtils.toLowerCase(b, buffer);
  }
 
 
 
  /**
   * Retrieves an uppercase representation of the given string.  This
   * implementation presumes that the provided string will contain only ASCII
   * characters and is optimized for that case.  However, if a non-ASCII
   * character is encountered it will fall back on a more expensive algorithm
   * that will work properly for non-ASCII characters.
   *
   * @param  s  The string for which to obtain the uppercase representation.
   *
   * @return  The uppercase representation of the given string.
   */
  public static String toUpperCase(String s)
  {
    if (s == null)
    {
      return null;
    }
 
    StringBuilder buffer = new StringBuilder(s.length());
    toUpperCase(s, buffer);
    return buffer.toString();
  }
 
 
 
  /**
   * Appends an uppercase representation of the given string to the provided
   * buffer.  This implementation presumes that the provided string will contain
   * only ASCII characters and is optimized for that case.  However, if a
   * non-ASCII character is encountered it will fall back on a more expensive
   * algorithm that will work properly for non-ASCII characters.
   *
   * @param  s       The string for which to obtain the uppercase
   *                 representation.
   * @param  buffer  The buffer to which the uppercase form of the string should
   *                 be appended.
   */
  public static void toUpperCase(String s, StringBuilder buffer)
  {
    if (s == null)
    {
      return;
    }
 
    int length = s.length();
    for (int i=0; i < length; i++)
    {
      char c = s.charAt(i);
 
      if ((c & 0x7F) != c)
      {
        buffer.append(s.substring(i).toUpperCase());
        return;
      }
 
      switch (c)
      {
        case 'a':
          buffer.append('A');
          break;
        case 'b':
          buffer.append('B');
          break;
        case 'c':
          buffer.append('C');
          break;
        case 'd':
          buffer.append('D');
          break;
        case 'e':
          buffer.append('E');
          break;
        case 'f':
          buffer.append('F');
          break;
        case 'g':
          buffer.append('G');
          break;
        case 'h':
          buffer.append('H');
          break;
        case 'i':
          buffer.append('I');
          break;
        case 'j':
          buffer.append('J');
          break;
        case 'k':
          buffer.append('K');
          break;
        case 'l':
          buffer.append('L');
          break;
        case 'm':
          buffer.append('M');
          break;
        case 'n':
          buffer.append('N');
          break;
        case 'o':
          buffer.append('O');
          break;
        case 'p':
          buffer.append('P');
          break;
        case 'q':
          buffer.append('Q');
          break;
        case 'r':
          buffer.append('R');
          break;
        case 's':
          buffer.append('S');
          break;
        case 't':
          buffer.append('T');
          break;
        case 'u':
          buffer.append('U');
          break;
        case 'v':
          buffer.append('V');
          break;
        case 'w':
          buffer.append('W');
          break;
        case 'x':
          buffer.append('X');
          break;
        case 'y':
          buffer.append('Y');
          break;
        case 'z':
          buffer.append('Z');
          break;
        default:
          buffer.append(c);
      }
    }
  }
 
 
 
  /**
   * Appends an uppercase string representation of the contents of the given
   * byte array to the provided buffer, optionally trimming leading and trailing
   * spaces.  This implementation presumes that the provided string will contain
   * only ASCII characters and is optimized for that case.  However, if a
   * non-ASCII character is encountered it will fall back on a more expensive
   * algorithm that will work properly for non-ASCII characters.
   *
   * @param  b       The byte array for which to obtain the uppercase string
   *                 representation.
   * @param  buffer  The buffer to which the uppercase form of the string should
   *                 be appended.
   * @param  trim    Indicates whether leading and trailing spaces should be
   *                 omitted from the string representation.
   */
  public static void toUpperCase(byte[] b, StringBuilder buffer, boolean trim)
  {
    if (b == null)
    {
      return;
    }
 
    int length = b.length;
    for (int i=0; i < length; i++)
    {
      if ((b[i] & 0x7F) != b[i])
      {
        try
        {
          buffer.append(new String(b, i, (length-i), "UTF-8").toUpperCase());
        }
        catch (Exception e)
        {
          logger.traceException(e);
          buffer.append(new String(b, i, (length - i)).toUpperCase());
        }
        break;
      }
 
      int bufferLength = buffer.length();
      switch (b[i])
      {
        case ' ':
          // If we don't care about trimming, then we can always append the
          // space.  Otherwise, only do so if there are other characters in the value.
          if (trim && bufferLength == 0)
          {
            break;
          }
 
          buffer.append(' ');
          break;
        case 'a':
          buffer.append('A');
          break;
        case 'b':
          buffer.append('B');
          break;
        case 'c':
          buffer.append('C');
          break;
        case 'd':
          buffer.append('D');
          break;
        case 'e':
          buffer.append('E');
          break;
        case 'f':
          buffer.append('F');
          break;
        case 'g':
          buffer.append('G');
          break;
        case 'h':
          buffer.append('H');
          break;
        case 'i':
          buffer.append('I');
          break;
        case 'j':
          buffer.append('J');
          break;
        case 'k':
          buffer.append('K');
          break;
        case 'l':
          buffer.append('L');
          break;
        case 'm':
          buffer.append('M');
          break;
        case 'n':
          buffer.append('N');
          break;
        case 'o':
          buffer.append('O');
          break;
        case 'p':
          buffer.append('P');
          break;
        case 'q':
          buffer.append('Q');
          break;
        case 'r':
          buffer.append('R');
          break;
        case 's':
          buffer.append('S');
          break;
        case 't':
          buffer.append('T');
          break;
        case 'u':
          buffer.append('U');
          break;
        case 'v':
          buffer.append('V');
          break;
        case 'w':
          buffer.append('W');
          break;
        case 'x':
          buffer.append('X');
          break;
        case 'y':
          buffer.append('Y');
          break;
        case 'z':
          buffer.append('Z');
          break;
        default:
          buffer.append((char) b[i]);
      }
    }
 
    if (trim)
    {
      // Strip off any trailing spaces.
      for (int i=buffer.length()-1; i > 0; i--)
      {
        if (buffer.charAt(i) == ' ')
        {
          buffer.delete(i, i+1);
        }
        else
        {
          break;
        }
      }
    }
  }
 
 
 
  /**
   * Append a string to a string builder, escaping any double quotes
   * according to the StringValue production in RFC 3641.
   * <p>
   * In RFC 3641 the StringValue production looks like this:
   *
   * <pre>
   *    StringValue       = dquote *SafeUTF8Character dquote
   *    dquote            = %x22 ; &quot; (double quote)
   *    SafeUTF8Character = %x00-21 / %x23-7F /   ; ASCII minus dquote
   *                        dquote dquote /       ; escaped double quote
   *                        %xC0-DF %x80-BF /     ; 2 byte UTF-8 character
   *                        %xE0-EF 2(%x80-BF) /  ; 3 byte UTF-8 character
   *                        %xF0-F7 3(%x80-BF)    ; 4 byte UTF-8 character
   * </pre>
   *
   * <p>
   * That is, strings are surrounded by double-quotes and any internal
   * double-quotes are doubled up.
   *
   * @param builder
   *          The string builder.
   * @param string
   *          The string to escape and append.
   * @return Returns the string builder.
   */
  public static StringBuilder toRFC3641StringValue(StringBuilder builder,
      String string)
  {
    // Initial double-quote.
    builder.append('"');
 
    for (char c : string.toCharArray())
    {
      if (c == '"')
      {
        // Internal double-quotes are escaped using a double-quote.
        builder.append('"');
      }
      builder.append(c);
    }
 
    // Trailing double-quote.
    builder.append('"');
 
    return builder;
  }
 
 
 
  /**
   * Retrieves a string array containing the contents of the provided
   * list of strings.
   *
   * @param stringList
   *          The string list to convert to an array.
   * @return A string array containing the contents of the provided list
   *         of strings.
   */
  public static String[] listToArray(List<String> stringList)
  {
    if (stringList == null)
    {
      return null;
    }
 
    String[] stringArray = new String[stringList.size()];
    stringList.toArray(stringArray);
    return stringArray;
  }
 
  /**
   * Retrieves an array list containing the contents of the provided array.
   *
   * @param  stringArray  The string array to convert to an array list.
   *
   * @return  An array list containing the contents of the provided array.
   */
  public static ArrayList<String> arrayToList(String... stringArray)
  {
    if (stringArray == null)
    {
      return null;
    }
 
    ArrayList<String> stringList = new ArrayList<>(stringArray.length);
    Collections.addAll(stringList, stringArray);
    return stringList;
  }
 
 
  /**
   * Attempts to delete the specified file or directory. If it is a directory,
   * then any files or subdirectories that it contains will be recursively
   * deleted as well.
   *
   * @param file
   *          The file or directory to be removed.
   * @return {@code true} if the specified file and any subordinates are all
   *         successfully removed, or {@code false} if at least one element in
   *         the subtree could not be removed or file does not exists.
   */
  public static boolean recursiveDelete(File file)
  {
    if (file.exists())
    {
      boolean successful = true;
      if (file.isDirectory())
      {
        File[] childList = file.listFiles();
        if (childList != null)
        {
          for (File f : childList)
          {
            successful &= recursiveDelete(f);
          }
        }
      }
 
      return successful & file.delete();
    }
    return false;
  }
 
 
 
  /**
   * Moves the indicated file to the specified directory by creating a new file
   * in the target directory, copying the contents of the existing file, and
   * removing the existing file.  The file to move must exist and must be a
   * file.  The target directory must exist, must be a directory, and must not
   * be the directory in which the file currently resides.
   *
   * @param  fileToMove       The file to move to the target directory.
   * @param  targetDirectory  The directory into which the file should be moved.
   *
   * @throws  IOException  If a problem occurs while attempting to move the
   *                       file.
   */
  public static void moveFile(File fileToMove, File targetDirectory)
         throws IOException
  {
    if (! fileToMove.exists())
    {
      LocalizableMessage message = ERR_MOVEFILE_NO_SUCH_FILE.get(fileToMove.getPath());
      throw new IOException(message.toString());
    }
 
    if (! fileToMove.isFile())
    {
      LocalizableMessage message = ERR_MOVEFILE_NOT_FILE.get(fileToMove.getPath());
      throw new IOException(message.toString());
    }
 
    if (! targetDirectory.exists())
    {
      LocalizableMessage message =
          ERR_MOVEFILE_NO_SUCH_DIRECTORY.get(targetDirectory.getPath());
      throw new IOException(message.toString());
    }
 
    if (! targetDirectory.isDirectory())
    {
      LocalizableMessage message =
          ERR_MOVEFILE_NOT_DIRECTORY.get(targetDirectory.getPath());
      throw new IOException(message.toString());
    }
 
    String newFilePath = targetDirectory.getPath() + File.separator +
                         fileToMove.getName();
    FileInputStream  inputStream  = new FileInputStream(fileToMove);
    FileOutputStream outputStream = new FileOutputStream(newFilePath, false);
    byte[] buffer = new byte[8192];
    while (true)
    {
      int bytesRead = inputStream.read(buffer);
      if (bytesRead < 0)
      {
        break;
      }
 
      outputStream.write(buffer, 0, bytesRead);
    }
 
    outputStream.flush();
    outputStream.close();
    inputStream.close();
    fileToMove.delete();
  }
 
  /**
   * Renames the source file to the target file.  If the target file exists
   * it is first deleted.  The rename and delete operation return values
   * are checked for success and if unsuccessful, this method throws an
   * exception.
   *
   * @param fileToRename The file to rename.
   * @param target       The file to which <code>fileToRename</code> will be
   *                     moved.
   * @throws IOException If a problem occurs while attempting to rename the
   *                     file.  On the Windows platform, this typically
   *                     indicates that the file is in use by this or another
   *                     application.
   */
  public static void renameFile(File fileToRename, File target)
          throws IOException {
    if (fileToRename != null && target != null)
    {
      synchronized(target)
      {
        if (target.exists() && !target.delete())
        {
          LocalizableMessage message =
              ERR_RENAMEFILE_CANNOT_DELETE_TARGET.get(target.getPath());
          throw new IOException(message.toString());
        }
      }
      if (!fileToRename.renameTo(target))
      {
        LocalizableMessage message = ERR_RENAMEFILE_CANNOT_RENAME.get(
            fileToRename.getPath(), target.getPath());
        throw new IOException(message.toString());
 
      }
    }
  }
 
 
  /**
   * Indicates whether the provided path refers to a relative path rather than
   * an absolute path.
   *
   * @param  path  The path string for which to make the determination.
   *
   * @return  <CODE>true</CODE> if the provided path is relative, or
   *          <CODE>false</CODE> if it is absolute.
   */
  public static boolean isRelativePath(String path)
  {
    File f = new File(path);
    return !f.isAbsolute();
  }
 
 
 
  /**
   * Retrieves a <CODE>File</CODE> object corresponding to the specified path.
   * If the given path is an absolute path, then it will be used.  If the path
   * is relative, then it will be interpreted as if it were relative to the
   * Directory Server root.
   *
   * @param  path  The path string to be retrieved as a <CODE>File</CODE>
   *
   * @return  A <CODE>File</CODE> object that corresponds to the specified path.
   */
  public static File getFileForPath(String path)
  {
    File f = new File (path);
 
    if (f.isAbsolute())
    {
      return f;
    }
    else
    {
      return new File(DirectoryServer.getInstanceRoot() + File.separator +
          path);
    }
  }
 
  /**
   * Retrieves a <CODE>File</CODE> object corresponding to the specified path.
   * If the given path is an absolute path, then it will be used.  If the path
   * is relative, then it will be interpreted as if it were relative to the
   * Directory Server root.
   *
   * @param path
   *           The path string to be retrieved as a <CODE>File</CODE>.
   * @param serverContext
   *           The server context.
   *
   * @return  A <CODE>File</CODE> object that corresponds to the specified path.
   */
  public static File getFileForPath(String path, ServerContext serverContext)
  {
    File f = new File (path);
 
    if (f.isAbsolute())
    {
      return f;
    }
    else
    {
      return new File(serverContext.getInstanceRoot() + File.separator +
          path);
    }
  }
 
 
 
  /**
   * Creates a new, blank entry with the given DN.  It will contain only the
   * attribute(s) contained in the RDN.  The choice of objectclasses will be
   * based on the RDN attribute.  If there is a single RDN attribute, then the
   * following mapping will be used:
   * <BR>
   * <UL>
   *   <LI>c attribute :: country objectclass</LI>
   *   <LI>dc attribute :: domain objectclass</LI>
   *   <LI>o attribute :: organization objectclass</LI>
   *   <LI>ou attribute :: organizationalUnit objectclass</LI>
   * </UL>
   * <BR>
   * Any other single RDN attribute types, or any case in which there are
   * multiple RDN attributes, will use the untypedObject objectclass.  If the
   * RDN includes one or more attributes that are not allowed in the
   * untypedObject objectclass, then the extensibleObject class will also be
   * added.  Note that this method cannot be used to generate an entry
   * with an empty or null DN.
   *
   * @param  dn  The DN to use for the entry.
   *
   * @return  The entry created with the provided DN.
   */
  public static Entry createEntry(DN dn)
  {
    // If the provided DN was null or empty, then return null because we don't
    // support it.
    if (dn == null || dn.isRootDN())
    {
      return null;
    }
 
 
    // Get the information about the RDN attributes.
    RDN rdn = dn.rdn();
    int numAVAs = rdn.getNumValues();
 
    // If there is only one RDN attribute, then see which objectclass we should use.
    ObjectClass structuralClass = DirectoryServer.getObjectClass(getObjectClassName(rdn, numAVAs));
 
    // Get the top and untypedObject classes to include in the entry.
    LinkedHashMap<ObjectClass,String> objectClasses = new LinkedHashMap<>(3);
 
    objectClasses.put(DirectoryServer.getTopObjectClass(), OC_TOP);
    objectClasses.put(structuralClass, structuralClass.getNameOrOID());
 
 
    // Iterate through the RDN attributes and add them to the set of user or
    // operational attributes.
    LinkedHashMap<AttributeType,List<Attribute>> userAttributes = new LinkedHashMap<>();
    LinkedHashMap<AttributeType,List<Attribute>> operationalAttributes = new LinkedHashMap<>();
 
    boolean extensibleObjectAdded = false;
    for (int i=0; i < numAVAs; i++)
    {
      AttributeType attrType = rdn.getAttributeType(i);
      ByteString attrValue = rdn.getAttributeValue(i);
      String attrName = rdn.getAttributeName(i);
 
      // First, see if this type is allowed by the untypedObject class.  If not,
      // then we'll need to include the extensibleObject class.
      if (!structuralClass.isRequiredOrOptional(attrType) && !extensibleObjectAdded)
      {
        ObjectClass extensibleObjectOC =
             DirectoryServer.getObjectClass(OC_EXTENSIBLE_OBJECT_LC);
        if (extensibleObjectOC == null)
        {
          extensibleObjectOC =
               DirectoryServer.getDefaultObjectClass(OC_EXTENSIBLE_OBJECT);
        }
        objectClasses.put(extensibleObjectOC, OC_EXTENSIBLE_OBJECT);
        extensibleObjectAdded = true;
      }
 
 
      // Create the attribute and add it to the appropriate map.
      if (attrType.isOperational())
      {
        addAttributeValue(operationalAttributes, attrType, attrName, attrValue);
      }
      else
      {
        addAttributeValue(userAttributes, attrType, attrName, attrValue);
      }
    }
 
 
    // Create and return the entry.
    return new Entry(dn, objectClasses, userAttributes, operationalAttributes);
  }
 
  private static String getObjectClassName(RDN rdn, int numAVAs)
  {
    if (numAVAs == 1)
    {
      final AttributeType attrType = rdn.getAttributeType(0);
      if (attrType.hasName(ATTR_C))
      {
        return OC_COUNTRY;
      }
      else if (attrType.hasName(ATTR_DC))
      {
        return OC_DOMAIN;
      }
      else if (attrType.hasName(ATTR_O))
      {
        return OC_ORGANIZATION;
      }
      else if (attrType.hasName(ATTR_OU))
      {
        return OC_ORGANIZATIONAL_UNIT_LC;
      }
    }
    return OC_UNTYPED_OBJECT_LC;
  }
 
  private static void addAttributeValue(LinkedHashMap<AttributeType, List<Attribute>> attrs,
      AttributeType attrType, String attrName, ByteString attrValue)
  {
    List<Attribute> attrList = attrs.get(attrType);
    if (attrList != null && !attrList.isEmpty())
    {
      AttributeBuilder builder = new AttributeBuilder(attrList.get(0));
      builder.add(attrValue);
      attrList.set(0, builder.toAttribute());
    }
    else
    {
      AttributeBuilder builder = new AttributeBuilder(attrType, attrName);
      builder.add(attrValue);
      attrs.put(attrType, builder.toAttributeList());
    }
  }
 
  /**
   * Retrieves a user-friendly string that indicates the length of time (in
   * days, hours, minutes, and seconds) in the specified number of seconds.
   *
   * @param  numSeconds  The number of seconds to be converted to a more
   *                     user-friendly value.
   *
   * @return  The user-friendly representation of the specified number of
   *          seconds.
   */
  public static LocalizableMessage secondsToTimeString(long numSeconds)
  {
    if (numSeconds < 60)
    {
      // We can express it in seconds.
      return INFO_TIME_IN_SECONDS.get(numSeconds);
    }
    else if (numSeconds < 3600)
    {
      // We can express it in minutes and seconds.
      long m = numSeconds / 60;
      long s = numSeconds % 60;
      return INFO_TIME_IN_MINUTES_SECONDS.get(m, s);
    }
    else if (numSeconds < 86400)
    {
      // We can express it in hours, minutes, and seconds.
      long h = numSeconds / 3600;
      long m = (numSeconds % 3600) / 60;
      long s = numSeconds % 3600 % 60;
      return INFO_TIME_IN_HOURS_MINUTES_SECONDS.get(h, m, s);
    }
    else
    {
      // We can express it in days, hours, minutes, and seconds.
      long d = numSeconds / 86400;
      long h = (numSeconds % 86400) / 3600;
      long m = (numSeconds % 86400 % 3600) / 60;
      long s = numSeconds % 86400 % 3600 % 60;
      return INFO_TIME_IN_DAYS_HOURS_MINUTES_SECONDS.get(d, h, m, s);
    }
  }
 
  /**
   * Checks that no more that one of a set of arguments is present.  This
   * utility should be used after argument parser has parsed a set of
   * arguments.
   *
   * @param  args to test for the presence of more than one
   * @throws ArgumentException if more than one of <code>args</code> is
   *         present and containing an error message identifying the
   *         arguments in violation
   */
  public static void checkOnlyOneArgPresent(Argument... args)
    throws ArgumentException
  {
    if (args != null) {
      for (Argument arg : args) {
        for (Argument otherArg : args) {
          if (arg != otherArg && arg.isPresent() && otherArg.isPresent()) {
            throw new ArgumentException(
                    ToolMessages.ERR_INCOMPATIBLE_ARGUMENTS.get(
                            arg.getName(), otherArg.getName()));
          }
        }
      }
    }
  }
 
  /**
   * Converts a string representing a time in "yyyyMMddHHmmss.SSS'Z'" or
   * "yyyyMMddHHmmss" to a <code>Date</code>.
   *
   * @param timeStr string formatted appropriately
   * @return Date object; null if <code>timeStr</code> is null
   * @throws ParseException if there was a problem converting the string to
   *         a <code>Date</code>.
   */
  public static Date parseDateTimeString(String timeStr) throws ParseException
  {
    Date dateTime = null;
    if (timeStr != null)
    {
      if (timeStr.endsWith("Z"))
      {
        try
        {
          SimpleDateFormat dateFormat =
            new SimpleDateFormat(DATE_FORMAT_GENERALIZED_TIME);
          dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
          dateFormat.setLenient(true);
          dateTime = dateFormat.parse(timeStr);
        }
        catch (ParseException pe)
        {
          // Best effort: try with GMT time.
          SimpleDateFormat dateFormat =
            new SimpleDateFormat(DATE_FORMAT_GMT_TIME);
          dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
          dateFormat.setLenient(true);
          dateTime = dateFormat.parse(timeStr);
        }
      }
      else
      {
        SimpleDateFormat dateFormat =
            new SimpleDateFormat(DATE_FORMAT_COMPACT_LOCAL_TIME);
        dateFormat.setLenient(true);
        dateTime = dateFormat.parse(timeStr);
      }
    }
    return dateTime;
  }
 
  /**
   * Formats a Date to String representation in "yyyyMMddHHmmss'Z'".
   *
   * @param date to format; null if <code>date</code> is null
   * @return string representation of the date
   */
  public static String formatDateTimeString(Date date)
  {
    String timeStr = null;
    if (date != null)
    {
      SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_GMT_TIME);
      dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
      timeStr = dateFormat.format(date);
    }
    return timeStr;
  }
 
  /**
   * Indicates whether or not a string represents a syntactically correct
   * email address.
   *
   * @param addr to validate
   * @return boolean where <code>true</code> indicates that the string is a
   *         syntactically correct email address
   */
  public static boolean isEmailAddress(String addr) {
 
    // This just does basic syntax checking.  Perhaps we
    // might want to be stricter about this.
    return addr != null && addr.contains("@") && addr.contains(".");
 
  }
 
 
 
  /**
   * Writes the contents of the provided buffer to the client,
   * terminating the connection if the write is unsuccessful for too
   * long (e.g., if the client is unresponsive or there is a network
   * problem). If possible, it will attempt to use the selector returned
   * by the {@code ClientConnection.getWriteSelector} method, but it is
   * capable of working even if that method returns {@code null}. <BR>
   *
   * Note that the original position and limit values will not be
   * preserved, so if that is important to the caller, then it should
   * record them before calling this method and restore them after it
   * returns.
   *
   * @param clientConnection
   *          The client connection to which the data is to be written.
   * @param buffer
   *          The data to be written to the client.
   * @return <CODE>true</CODE> if all the data in the provided buffer was
   *         written to the client and the connection may remain
   *         established, or <CODE>false</CODE> if a problem occurred
   *         and the client connection is no longer valid. Note that if
   *         this method does return <CODE>false</CODE>, then it must
   *         have already disconnected the client.
   * @throws IOException
   *           If a problem occurs while attempting to write data to the
   *           client. The caller will be responsible for catching this
   *           and terminating the client connection.
   */
  public static boolean writeWithTimeout(ClientConnection clientConnection,
      ByteBuffer buffer) throws IOException
  {
    SocketChannel socketChannel = clientConnection.getSocketChannel();
    long startTime = System.currentTimeMillis();
    long waitTime = clientConnection.getMaxBlockedWriteTimeLimit();
    if (waitTime <= 0)
    {
      // We won't support an infinite time limit, so fall back to using
      // five minutes, which is a very long timeout given that we're
      // blocking a worker thread.
      waitTime = 300000L;
    }
 
    long stopTime = startTime + waitTime;
 
    Selector selector = clientConnection.getWriteSelector();
    if (selector == null)
    {
      // The client connection does not provide a selector, so we'll
      // fall back
      // to a more inefficient way that will work without a selector.
      while (buffer.hasRemaining()
          && System.currentTimeMillis() < stopTime)
      {
        if (socketChannel.write(buffer) < 0)
        {
          // The client connection has been closed.
          return false;
        }
      }
 
      if (buffer.hasRemaining())
      {
        // If we've gotten here, then the write timed out.
        return false;
      }
 
      return true;
    }
 
    // Register with the selector for handling write operations.
    SelectionKey key =
        socketChannel.register(selector, SelectionKey.OP_WRITE);
 
    try
    {
      selector.select(waitTime);
      while (buffer.hasRemaining())
      {
        long currentTime = System.currentTimeMillis();
        if (currentTime >= stopTime)
        {
          // We've been blocked for too long.
          return false;
        }
        else
        {
          waitTime = stopTime - currentTime;
        }
 
        Iterator<SelectionKey> iterator =
            selector.selectedKeys().iterator();
        while (iterator.hasNext())
        {
          SelectionKey k = iterator.next();
          if (k.isWritable())
          {
            int bytesWritten = socketChannel.write(buffer);
            if (bytesWritten < 0)
            {
              // The client connection has been closed.
              return false;
            }
 
            iterator.remove();
          }
        }
 
        if (buffer.hasRemaining())
        {
          selector.select(waitTime);
        }
      }
 
      return true;
    }
    finally
    {
      if (key.isValid())
      {
        key.cancel();
        selector.selectNow();
      }
    }
  }
 
 
 
  /**
   * Add all of the superior objectclasses to the specified objectclass
   * map if they don't already exist. Used by add and import-ldif to
   * add missing superior objectclasses to entries that don't have them.
   *
   * @param objectClasses A Map of objectclasses.
   */
  public static void addSuperiorObjectClasses(Map<ObjectClass,
      String> objectClasses) {
      HashSet<ObjectClass> additionalClasses = null;
      for (ObjectClass oc : objectClasses.keySet())
      {
        for(ObjectClass superiorClass : oc.getSuperiorClasses())
        {
          if (! objectClasses.containsKey(superiorClass))
          {
            if (additionalClasses == null)
            {
              additionalClasses = new HashSet<>();
            }
 
            additionalClasses.add(superiorClass);
          }
        }
      }
 
      if (additionalClasses != null)
      {
        for (ObjectClass oc : additionalClasses)
        {
          addObjectClassChain(oc, objectClasses);
        }
      }
  }
 
  private static void addObjectClassChain(ObjectClass objectClass,
      Map<ObjectClass, String> objectClasses)
  {
    if (objectClasses != null){
      if (! objectClasses.containsKey(objectClass))
      {
        objectClasses.put(objectClass, objectClass.getNameOrOID());
      }
 
      for(ObjectClass superiorClass : objectClass.getSuperiorClasses())
      {
        if (! objectClasses.containsKey(superiorClass))
        {
          addObjectClassChain(superiorClass, objectClasses);
        }
      }
    }
  }
 
 
  /**
   * Closes the provided {@link Closeable}'s ignoring any errors which
   * occurred.
   *
   * @param closeables The closeables to be closed, which may be
   *        <code>null</code>.
   */
  public static void close(Closeable... closeables)
  {
    if (closeables == null)
    {
      return;
    }
    close(Arrays.asList(closeables));
  }
 
  /**
   * Closes the provided {@link Closeable}'s ignoring any errors which occurred.
   *
   * @param closeables
   *          The closeables to be closed, which may be <code>null</code>.
   */
  public static void close(Collection<? extends Closeable> closeables)
  {
    if (closeables == null)
    {
      return;
    }
    for (Closeable closeable : closeables)
    {
      if (closeable != null)
      {
        try
        {
          closeable.close();
        }
        catch (IOException ignored)
        {
          logger.traceException(ignored);
        }
      }
    }
  }
 
  /**
   * Closes the provided {@link InitialContext}s ignoring any errors which occurred.
   *
   * @param ctxs
   *          The contexts to be closed, which may be <code>null</code>.
   */
  public static void close(InitialContext... ctxs)
  {
    if (ctxs == null)
    {
      return;
    }
    for (InitialContext ctx : ctxs)
    {
      if (ctx != null)
      {
        try
        {
          ctx.close();
        }
        catch (NamingException ignored)
        {
          // ignore
        }
      }
    }
  }
 
  /**
   * Calls {@link Thread#sleep(long)}, surrounding it with the mandatory
   * <code>try</code> / <code>catch(InterruptedException)</code> block.
   *
   * @param millis
   *          the length of time to sleep in milliseconds
   */
  public static void sleep(long millis)
  {
    try
    {
      Thread.sleep(millis);
    }
    catch (InterruptedException wokenUp)
    {
      // ignore
    }
  }
 
  /**
   * Test if the provided message corresponds to the provided descriptor.
   *
   * @param msg
   *          The i18n message.
   * @param desc
   *          The message descriptor.
   * @return {@code true} if message corresponds to descriptor
   */
  public static boolean hasDescriptor(LocalizableMessage msg,
      LocalizableMessageDescriptor.Arg0 desc)
  {
    return msg.ordinal() == desc.ordinal()
        && msg.resourceName().equals(desc.resourceName());
  }
 
  /**
   * Test if the provided message corresponds to the provided descriptor.
   *
   * @param msg
   *          The i18n message.
   * @param desc
   *          The message descriptor.
   * @return {@code true} if message corresponds to descriptor
   */
  public static boolean hasDescriptor(LocalizableMessage msg,
      LocalizableMessageDescriptor.Arg1 desc)
  {
    return msg.ordinal() == desc.ordinal()
        && msg.resourceName().equals(desc.resourceName());
  }
 
  /**
   * Test if the provided message corresponds to the provided descriptor.
   *
   * @param msg
   *          The i18n message.
   * @param desc
   *          The message descriptor.
   * @return {@code true} if message corresponds to descriptor
   */
  public static boolean hasDescriptor(LocalizableMessage msg,
      LocalizableMessageDescriptor.Arg2 desc)
  {
    return msg.ordinal() == desc.ordinal()
        && msg.resourceName().equals(desc.resourceName());
  }
 
  /**
   * Test if the provided message corresponds to the provided descriptor.
   *
   * @param msg
   *          The i18n message.
   * @param desc
   *          The message descriptor.
   * @return {@code true} if message corresponds to descriptor
   */
  public static boolean hasDescriptor(LocalizableMessage msg,
      LocalizableMessageDescriptor.Arg3 desc)
  {
    return msg.ordinal() == desc.ordinal()
        && msg.resourceName().equals(desc.resourceName());
  }
 
  /**
   * Test if the provided message corresponds to the provided descriptor.
   *
   * @param msg
   *          The i18n message.
   * @param desc
   *          The message descriptor.
   * @return {@code true} if message corresponds to descriptor
   */
  public static boolean hasDescriptor(LocalizableMessage msg,
      LocalizableMessageDescriptor.Arg7 desc)
  {
    return msg.ordinal() == desc.ordinal()
        && msg.resourceName().equals(desc.resourceName());
  }
 
  /**
   * Returns an {@link Iterable} returning the passed in {@link Iterator}. THis
   * allows using methods returning Iterators with foreach statements.
   * <p>
   * For example, consider a method with this signature:
   * <p>
   * <code>public Iterator&lt;String&gt; myIteratorMethod();</code>
   * <p>
   * Classical use with for or while loop:
   *
   * <pre>
   * for (Iterator&lt;String&gt; it = myIteratorMethod(); it.hasNext();)
   * {
   *   String s = it.next();
   *   // use it
   * }
   *
   * Iterator&lt;String&gt; it = myIteratorMethod();
   * while(it.hasNext();)
   * {
   *   String s = it.next();
   *   // use it
   * }
   * </pre>
   *
   * Improved use with foreach:
   *
   * <pre>
   * for (String s : StaticUtils.toIterable(myIteratorMethod()))
   * {
   * }
   * </pre>
   *
   * </p>
   *
   * @param <T>
   *          the generic type of the passed in Iterator and for the returned
   *          Iterable.
   * @param iterator
   *          the Iterator that will be returned by the Iterable.
   * @return an Iterable returning the passed in Iterator
   */
  public static <T> Iterable<T> toIterable(final Iterator<T> iterator)
  {
    return new Iterable<T>()
    {
      @Override
      public Iterator<T> iterator()
      {
        return iterator;
      }
    };
  }
}