File: LDAPConnection.java

package info (click to toggle)
ldapjdk 4.20.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 9,708 kB
  • sloc: ansic: 44,727; java: 39,132; xml: 7,419; sh: 4,185; perl: 3,774; makefile: 1,681; cpp: 979
file content (5732 lines) | stat: -rw-r--r-- 234,875 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
 *
 * ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is mozilla.org code.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 2001
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
package org.ietf.ldap;

import java.io.*;
import java.net.*;
import java.util.*;
import javax.security.auth.callback.CallbackHandler;

import org.ietf.ldap.client.*;
import org.ietf.ldap.client.opers.*;
import org.ietf.ldap.ber.stream.*;
import org.ietf.ldap.util.*;

/**
 * Represents a connection to an LDAP server. <P>
 *
 * Use objects of this class to perform LDAP operations (such as
 * search, modify, and add) on an LDAP server. <P>
 *
 * To perform an LDAP operation on a server, you need to follow
 * these steps: <P>
 *
 * <OL>
 * <LI>Create a new <CODE>LDAPConnection</CODE> object.
 * <LI>Use the <CODE>connect</CODE> method to connect to the
 * LDAP server.
 * <LI>Use the <CODE>authenticate</CODE> method to authenticate
 * to server.
 * <LI>Perform the LDAP operation.
 * <LI>Use the <CODE>disconnect</CODE> method to disconnect from
 * the server when done.
 * </OL>
 * <P>
 *
 * All operations block until completion (with the exception of
 * the search method in which the results may not all return at
 * the same time).
 * <P>
 *
 * This class also specifies a default set of constraints
 * (such as the maximum length of time to allow for an operation before timing out)
 * which apply to all operations. To get and set these constraints,
 * use the <CODE>getOption</CODE> and <CODE>setOption</CODE> methods.
 * To override these constraints for an individual operation,
 * define a new set of constraints by creating a <CODE>LDAPConstraints</CODE>
 * object and pass the object to the method for the operation. For search 
 * operations, additional constraints are defined in <CODE>LDAPSearchConstraints</CODE>
 * (a subclass of <CODE>LDAPConstraints</CODE>). To override the default search
 * constraints, create an <CODE>LDAPSearchConstraints</CODE> object and pass it
 * to the <CODE>search</CODE> method.
 * <P>
 *
 * If you set up your client to follow referrals automatically,
 * an operation that results in a referral will create a new connection
 * to the LDAP server identified in the referral.  In order to have
 * your client authenticate to that LDAP server automatically, you need
 * to define a class that implements the <CODE>LDAPAuthHandler</CODE> interface.
 * In your definition of the class, you need to define a
 * <CODE>getAuthProvider</CODE> method that creates an <CODE>LDAPAuthProvider</CODE>
 * object containing the distinguished name and password to use for reauthentication.
 * <P>
 *
 * Most errors that occur raise the same exception (<CODE>LDAPException</CODE>).
 * In order to determine the exact problem that occurred, you can retrieve the
 * result code from this exception and compare its value against a set of defined
 * result codes.
 * <P>
 *
 * @version 1.0
 * @see org.ietf.ldap.LDAPConstraints
 * @see org.ietf.ldap.LDAPSearchConstraints
 * @see org.ietf.ldap.LDAPAuthHandler
 * @see org.ietf.ldap.LDAPAuthProvider
 * @see org.ietf.ldap.LDAPException
 */
public class LDAPConnection implements Cloneable, Serializable {

    static final long serialVersionUID = -8698420087475771144L;

    /**
     * Version of the LDAP protocol used by default.
     * <CODE>LDAP_VERSION</CODE> is 2, so your client will
     * attempt to authenticate to LDAP servers as an LDAP v2 client.
     * The following is an example of some code that prints the
     * value of this variable:
     * <P>
     *
     * <PRE>
     * LDAPConnection ld = new LDAPConnection();
     * System.out.println( "The default LDAP protocol version used is "
     *                      ld.LDAP_VERSION );
     * </PRE>
     *
     * If you want to authenticate as an LDAP v3 client,
     * use the <A HREF="#bind(int, java.lang.String, byte[])"><CODE>bind(int version, String dn, byte[] passwd)</CODE></A> method.
     * For example:
     * <P>
     *
     * <PRE>
     * ld.bind( 3, myDN, myPW );
     * </PRE>
     *
     * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
     */
    public final static int LDAP_VERSION              = 2;
    /**
     * Name of the property specifying the version of the SDK. <P>
     *
     * To get the version number, pass this name to the
     * <CODE>getProperty</CODE> method.  The SDK version number
     * is of the type <CODE>Float</CODE>. For example:<P>
     * <PRE>
     *      ...
     *      Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
     *      System.out.println( "SDK version: " + sdkVersion );
     *      ... </PRE>
     * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
     */
    public final static String LDAP_PROPERTY_SDK      = "version.sdk";
    /**
     * Name of the property specifying the highest supported version of
     * the LDAP protocol. <P>
     *
     * To get the version number, pass this name to the
     * <CODE>getProperty</CODE> method.  The LDAP protocol version number
     * is of the type <CODE>Float</CODE>. For example:<P>
     * <PRE>
     *      ...
     *      Float LDAPVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_PROTOCOL );
     *      System.out.println( "Highest supported LDAP protocol version: " + LDAPVersion );
     *      ... </PRE>
     * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
     */
    public final static String LDAP_PROPERTY_PROTOCOL = "version.protocol";
    /**
     * Name of the property specifying the types of authentication allowed by this
     * API (for example, anonymous authentication and simple authentication). <P>
     *
     * To get the supported types, pass this name to the
     * <CODE>getProperty</CODE> method.  The value of this property is
     * of the type <CODE>String</CODE>. For example:<P>
     * <PRE>
     *      ...
     *      String authTypes = ( String )myConn.getProperty( myConn.LDAP_PROPERTY_SECURITY );
     *      System.out.println( "Supported authentication types: " + authTypes );
     *      ... </PRE>
     * @see org.ietf.ldap.LDAPConnection#getProperty(java.lang.String)
     */
    public final static String LDAP_PROPERTY_SECURITY = "version.security";

    /**
     * Name of the property to enable/disable LDAP message trace. <P>
     *
     * The property can be specified either as a system property 
     * (java -D command line option),  or programmatically with the
     * <CODE>setProperty</CODE> method.
     * <P>
     * When -D command line option is used, defining the property with
     * no value will send the trace output to the standard error. If the 
     * value is defined, it is assumed to be the name of an output file.
     * If the file name is prefixed with a '+' character, the file is
     * opened in append mode.
     * <P>
     * When the property is set with the <CODE>setProperty</CODE> method,
     * the property value must be either a String (represents a file name)
     * an OutputStream or an instance of LDAPTraceWriter. To stop tracing,
     * <CODE>null</CODE> should be  passed as the property value.
     * 
     * @see org.ietf.ldap.LDAPConnection#setProperty(java.lang.String, java.lang.Object)
     */
    public final static String TRACE_PROPERTY = "com.org.ietf.ldap.trace";

    /**
     * Specifies the serial connection setup policy when a list of hosts is
     * passed to  the <CODE>connect</CODE> method.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
     */    
    public final static int NODELAY_SERIAL = -1;
    /**
     * Specifies the parallel connection setup policy with no delay when a
     * list of hosts is passed to the <CODE>connect</CODE> method.
     * For each host in the list, a separate thread is created to attempt
     * to connect to the host. All threads are started simultaneously.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay(int)
     */    
    public final static int NODELAY_PARALLEL = 0;

    /**
     * Constants
     */
    private final static String defaultFilter = "(objectClass=*)";
    private final static LDAPConstraints readConstraints = new
      LDAPSearchConstraints();

    /**
     * The default port number for LDAP servers.  You can specify
     * this identifier when calling the <CODE>LDAPConnection.connect</CODE>
     * method to connect to an LDAP server.
     * @see org.ietf.ldap.LDAPConnection#connect
     */
    public final static int DEFAULT_PORT = 389;

    /**
     * Option specifying how aliases are dereferenced.
     * <P>
     *
     * This option can have one of the following values:
     * <UL>
     * <LI><A HREF="#DEREF_NEVER"><CODE>DEREF_NEVER</CODE></A>
     * <LI><A HREF="#DEREF_FINDING"><CODE>DEREF_FINDING</CODE></A>
     * <LI><A HREF="#DEREF_SEARCHING"><CODE>DEREF_SEARCHING</CODE></A>
     * <LI><A HREF="#DEREF_ALWAYS"><CODE>DEREF_ALWAYS</CODE></A>
     * </UL>
     * <P>
     *
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int DEREF = 2;

    /**
     * Option specifying the maximum number of search results to
     * return.
     * <P>
     *
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int SIZELIMIT = 3;

    /**
     * Option specifying the maximum number of milliseconds to
     * wait for an operation to complete.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int TIMELIMIT = 4;

    /**
     * Option specifying the maximum number of milliseconds the 
     * server should spend returning search results before aborting
     * the search. 
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int SERVER_TIMELIMIT = 5;

    /**
     * Option specifying whether or not referrals to other LDAP
     * servers are followed automatically.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     * @see org.ietf.ldap.LDAPAuthHandler
     * @see org.ietf.ldap.LDAPAuthProvider
     */
    public static final int REFERRALS = 8;

    /**
     * Option specifying the object containing the method for
     * getting authentication information (the distinguished name
     * and password) used during a referral.  For example, when
     * referred to another LDAP server, your client uses this object
     * to obtain the DN and password.  Your client authenticates to
     * the LDAP server using this DN and password.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     * @see org.ietf.ldap.LDAPAuthHandler
     * @see org.ietf.ldap.LDAPAuthProvider
     */
    public static final int REFERRALS_REBIND_PROC = 9;

    /**
     * Option specifying the maximum number of referrals to follow
     * in a sequence when requesting an LDAP operation.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int REFERRALS_HOP_LIMIT   = 10;
    
    /**
     * Option specifying the object containing the method for
     * authenticating to the server.  
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     * @see org.ietf.ldap.LDAPBindHandler
     */
    public static final int BIND = 13;

    /**
     * Option specifying the version of the LDAP protocol
     * used by your client when interacting with the LDAP server.
     * If no version is set, the default version is 2.  If you
     * are planning to use LDAP v3 features (such as controls
     * or extended operations), you should set this version to 3
     * or specify version 3 as an argument to the <CODE>authenticate</CODE>
     * method of the <CODE>LDAPConnection</CODE> object.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
     */
    public static final int PROTOCOL_VERSION = 17;

    /**
     * Option specifying the number of results to return at a time.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int BATCHSIZE = 20;


    /*
     * Valid options for Scope
     */

    /**
     * Specifies that the scope of a search includes
     * only the base DN (distinguished name).
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
     */
    public static final int SCOPE_BASE = 0;

    /**
     * Specifies that the scope of a search includes
     * only the entries one level below the base DN (distinguished name).
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)   */
    public static final int SCOPE_ONE = 1;

    /**
     * Specifies that the scope of a search includes
     * the base DN (distinguished name) and all entries at all levels
     * beneath that base.
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)   */
    public static final int SCOPE_SUB = 2;


    /*
     * Valid options for Dereference
     */

    /**
     * Specifies that aliases are never dereferenced.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int DEREF_NEVER = 0;

    /**
     * Specifies that aliases are dereferenced when searching the
     * entries beneath the starting point of the search (but
     * not when finding the starting entry).
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int DEREF_SEARCHING = 1;

    /**
     * Specifies that aliases are dereferenced when finding the
     * starting point for the search (but not when searching
     * under that starting entry).
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int DEREF_FINDING = 2;

    /**
     * Specifies that aliases are always dereferenced.
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int DEREF_ALWAYS = 3;

    /**
     * Option specifying server controls for LDAP operations. These
     * controls are passed to the LDAP server. They may also be returned by
     * the server.
     * @see org.ietf.ldap.LDAPControl
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int SERVERCONTROLS   = 12;

    /**
     * Attribute type that you can specify in the LDAPConnection
     * search method if you don't want to retrieve any of the
     * attribute types for entries found by the search.
     * @see org.ietf.ldap.LDAPConnection#search
     */
    public static final String NO_ATTRS = "1.1";

    /**
     * Attribute type that you can specify in the LDAPConnection
     * search method if you want to retrieve all attribute types.
     * You can use this if you want to retrieve all attributes in
     * addition to an operational attribute.  For example:
     * <P>
     *
     * <PRE>
     * ...
     * String [] MY_ATTRS = { LDAPConnection.ALL_USER_ATTRS, "modifiersName",
     *     "modifyTimestamp" };
     * LDAPSearchResults res = ld.search( MY_SEARCHBASE,
     *     LDAPConnection.SCOPE_SUB, MY_FILTER, MY_ATTRS, false, cons );
     * ...
     * </PRE>
     * @see org.ietf.ldap.LDAPConnection#search
     */
    public static final String ALL_USER_ATTRS = "*";

    /**
     * Internal variables
     */
    private LDAPSearchConstraints _defaultConstraints =
        new LDAPSearchConstraints();
    
    // A clone of constraints for the successful bind. Used by 
    // "smart failover" for the automatic rebind
    private LDAPConstraints _rebindConstraints;

    private Vector _responseListeners;
    private Vector _searchListeners;
    private boolean _bound;
    private String _prevBoundDN;
    private byte[] _prevBoundPasswd;
    private String _boundDN;
    private byte[] _boundPasswd;
    private int _protocolVersion = LDAP_VERSION;
    private LDAPConnSetupMgr _connMgr;
    private int _connSetupDelay = -1;
    private int _connectTimeout = 0;
    private LDAPSocketFactory _factory;
    /* _thread does all socket i/o for the object and any clones */
    private transient LDAPConnThread _thread = null;
    /* To manage received server controls on a per-thread basis,
       we keep a table of active threads and a table of controls,
       indexed by thread */
    private Vector _attachedList = new Vector();
    private Hashtable _responseControlTable = new Hashtable();
    private LDAPCache _cache = null;
    static Hashtable _threadConnTable = new Hashtable();

    // This handles the case when the client lost the connection to the
    // server. After the client reconnects with the server, the bound resets
    // to false. If the client used to have anonymous bind, then this boolean
    // will take care of the case whether the client should send anonymous bind
    // request to the server.
    private boolean _anonymousBound = false;

    private Object _security = null;
    private LDAPSaslBind _saslBinder = null;
    private CallbackHandler _saslCallbackHandler = null;
    private Properties _securityProperties;
    private Hashtable _properties = new Hashtable();
    private LDAPConnection _referralConnection;
    private String _authMethod = "none";

    /**
     * Properties
     */
    private final static Float SdkVersion = new Float(4.14f);
    private final static Float ProtocolVersion = new Float(3.0f);
    private final static String SecurityVersion = new String("none,simple,sasl");
    private final static Float MajorVersion = new Float(4.0f);
    private final static Float MinorVersion = new Float(0.14f);
    private final static String DELIM = "#";
    private final static String PersistSearchPackageName =
      "org.ietf.ldap.controls.LDAPPersistSearchControl";
    final static String EXTERNAL_MECHANISM = "external";
    private final static String EXTERNAL_MECHANISM_PACKAGE =
      "com.netscape.sasl";
    final static String DEFAULT_SASL_PACKAGE =
      "com.netscape.sasl";
    final static String SCHEMA_BUG_PROPERTY =
      "com.org.ietf.ldap.schema.quoting";
    final static String SASL_PACKAGE_PROPERTY =
      "com.org.ietf.ldap.saslpackage";

   /**
    * Constructs a new <CODE>LDAPConnection</CODE> object,
    * which represents a connection to an LDAP server. <P>
    *
    * Calling the constructor does not actually establish
    * the connection.  To connect to the LDAP server, use the
    * <CODE>connect</CODE> method.
    *
    * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
    * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
    */
    public LDAPConnection() {
        super();
        _factory = null;

        _properties.put(LDAP_PROPERTY_SDK, SdkVersion); 
        _properties.put(LDAP_PROPERTY_PROTOCOL, ProtocolVersion); 
        _properties.put(LDAP_PROPERTY_SECURITY, SecurityVersion); 
        _properties.put("version.major", MajorVersion); 
        _properties.put("version.minor", MinorVersion);
    }

    /**
     * Constructs a new <CODE>LDAPConnection</CODE> object that
     * will use the specified socket factory class to create
     * socket connections. The socket factory class must implement
     * the <CODE>LDAPSocketFactory</CODE> interface. <BR>
     * (For example, the <CODE>LDAPSSLSocketFactory</CODE>
     * class implements this interface.)
     * <P>
     *
     * Note that calling the <CODE>LDAPConnection</CODE> constructor
     * does not actually establish a connection to an LDAP server.
     * To connect to an LDAP server, use the
     * <CODE>connect</CODE> method.  The socket connection will be
     * constructed when this method is called.
     * <P>
     *
     * @see org.ietf.ldap.LDAPSocketFactory
     * @see org.ietf.ldap.LDAPSSLSocketFactory
     * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
     * @see org.ietf.ldap.LDAPConnection#bind(int, java.lang.String, byte[])
     * @see org.ietf.ldap.LDAPConnection#getSocketFactory
     * @see org.ietf.ldap.LDAPConnection#setSocketFactory(org.ietf.ldap.LDAPSocketFactory)
     */
    public LDAPConnection( LDAPSocketFactory factory ) {
        this();
        _factory = factory;
    }

    /**
     * Abandons a current search operation, notifying the server not
     * to send additional search results.
     *
     * @param searchResults the search results returned when the search
     * was started
     * @exception LDAPException Failed to notify the LDAP server.
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
     * @see org.ietf.ldap.LDAPSearchResults
     */
    public void abandon( LDAPSearchResults searchResults )
        throws LDAPException {
        abandon( searchResults, _defaultConstraints );
    }

    /**
     * Abandons a current search operation, notifying the server not
     * to send additional search results.
     *
     * @param searchResults the search results returned when the search
     * was started
     * @param cons preferences for the operation
     * @exception LDAPException Failed to notify the LDAP server.
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
     * @see org.ietf.ldap.LDAPSearchResults
     */
    public void abandon( LDAPSearchResults searchResults,
                         LDAPConstraints cons )
        throws LDAPException {
        if ( (!isConnected()) || (searchResults == null) ) {
            return;
        }

        int id = searchResults.getMessageID();
        if ( id != -1 ) {
            abandon( id );
        }
    }

    /**
     * Cancels the ldap request with the specified id and discards
     * any results already received.
     * 
     * @param id an LDAP request id
     * @exception LDAPException Failed to send request.
     */
    public void abandon( int id ) throws LDAPException {
        abandon( id, _defaultConstraints );
    }
    
    /**
     * Cancels the ldap request with the specified id and discards
     * any results already received.
     * 
     * @param id an LDAP request id
     * @param cons preferences for the operation
     * @exception LDAPException Failed to send request.
     */
    public void abandon( int id,
                         LDAPConstraints cons ) throws LDAPException {
        if (!isConnected()) {
            return;
        }
        
        for (int i=0; i<3; i++) {
            try {
                /* Tell listener thread to discard results */
                _thread.abandon( id );

                /* Tell server to stop sending results */
                _thread.sendRequest(null, new JDAPAbandonRequest(id), null, _defaultConstraints);

                /* No response is forthcoming */
                break;
            } catch (NullPointerException ne) {
                // do nothing
            }
        }
        if (_thread == null) {
            throw new LDAPException("Failed to send abandon request to the server.",
              LDAPException.OTHER);
        }
    }
    
    /**
     * Cancels all outstanding search requests associated with this
     * LDAPSearchQueue object and discards any results already received.
     * 
     * @param searchlistener a search listener returned from a search
     * @exception LDAPException Failed to send request.
     */
    public void abandon( LDAPSearchQueue searchlistener )
        throws LDAPException {
        abandon( searchlistener, _defaultConstraints );
    }
    
    /**
     * Cancels all outstanding search requests associated with this
     * LDAPSearchQueue object and discards any results already received.
     * 
     * @param searchlistener a search listener returned from a search
     * @param cons preferences for the operation
     * @exception LDAPException Failed to send request.
     */
    public void abandon( LDAPSearchQueue searchlistener,
                         LDAPConstraints cons )
        throws LDAPException {
        int[] ids = searchlistener.getMessageIDs();
        for (int i=0; i < ids.length; i++) {
            searchlistener.removeRequest(ids[i]);
            abandon(ids[i]);
        }
    }
    
    /**
     * Adds an entry to the directory. <P>
     *
     * Before using this method, you need to create an
     * <CODE>LDAPEntry</CODE> object and use it to specify the
     * distinguished name and attributes of the new entry. Make sure
     * to specify values for all required attributes in the
     * entry. If all required attributes are not specified and the LDAP server
     * checks the entry against the schema, an <CODE>LDAPException</CODE>
     * may be thrown (where the LDAP result code is
     * <CODE>OBJECT_CLASS_VIOLATION</CODE>).<P>
     *
     * For example, the following section of code creates an
     * <CODE>LDAPEntry</CODE> object for a new entry and uses the object
     * to add the new entry to the directory. Because the definition of
     * the LDAP <CODE>inetOrgPerson</CODE> class specifies that the
     * <CODE>cn</CODE>, <CODE>sn</CODE>, and <CODE>objectclass</CODE>
     * attributes are required, these attributes are specified as part
     * of the new entry.  (<CODE>mail</CODE> is not required but is shown
     * here as an example of specifying additional attributes.)
     * <P>
     *
     * <PRE>
     * ...
     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     *
     * LDAPAttribute attr1 = new LDAPAttribute( "cn", "Barbara Jensen" );
     * LDAPAttribute attr2 = new LDAPAttribute( "sn", "Jensen" );
     * LDAPAttribute attr3 = new LDAPAttribute( "objectclass", "top" );
     * LDAPAttribute attr4 = new LDAPAttribute( "objectclass", "person" );
     * LDAPAttribute attr5 = new LDAPAttribute( "objectclass", "organizationalPerson" );
     * LDAPAttribute attr6 = new LDAPAttribute( "objectclass", "inetOrgPerson" );
     * LDAPAttribute attr7 = new LDAPAttribute( "mail", "bjensen@aceindustry.com" );
     *
     * LDAPAttributeSet myAttrs = new LDAPAttributeSet();
     * myAttrs.add( attr1 );
     * myAttrs.add( attr2 );
     * myAttrs.add( attr3 );
     * myAttrs.add( attr4 );
     * myAttrs.add( attr5 );
     * myAttrs.add( attr6 );
     * myAttrs.add( attr7 );
     *
     * LDAPEntry myEntry = new LDAPEntry( myDN, myAttrs );
     *
     * myConn.add( myEntry );
     * ... </PRE>
     *
     * @param entry LDAPEntry object specifying the distinguished name and
     * attributes of the new entry
     * @exception LDAPException Failed to add the specified entry to the
     * directory.
     * @see org.ietf.ldap.LDAPEntry
     */
    public void add( LDAPEntry entry ) throws LDAPException {
        add(entry, _defaultConstraints);
    }

    /**
     * Adds an entry to the directory and allows you to specify preferences
     * for this LDAP add operation by using an
     * <CODE>LDAPConstraints</CODE> object. For
     * example, you can specify whether or not to follow referrals.
     * You can also apply LDAP v3 controls to the operation.
     * <P>
     *
     * @param entry LDAPEntry object specifying the distinguished name and
     * attributes of the new entry
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to add the specified entry to the
     * directory.
     * @see org.ietf.ldap.LDAPEntry
     * @see org.ietf.ldap.LDAPConstraints
     */
    public void add( LDAPEntry entry, LDAPConstraints cons )
        throws LDAPException {
        internalBind (cons);

        LDAPResponseQueue myListener = getResponseListener ();
        LDAPAttributeSet attrs = entry.getAttributeSet ();
        LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
        Iterator it = attrs.iterator();
        for( int i = 0; i < attrs.size(); i++ ) {
            attrList[i] = (LDAPAttribute)it.next();
        }
        int attrPosition = 0;
        LDAPMessage response;
        try {
            sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
                         myListener, cons);
            response = myListener.getResponse();
            checkMsg (response);
        } catch (LDAPReferralException e) {
            performReferrals(e, cons, JDAPProtocolOp.ADD_REQUEST,
                             null, 0, null, null, false, null, entry, null, null);
        } finally {
            releaseResponseListener (myListener);
        }
    }

    /**
     * Adds an entry to the directory.
     *
     * @param entry LDAPEntry object specifying the distinguished name and
     * attributes of the new entry
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPEntry
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue add( LDAPEntry entry,
                                  LDAPResponseQueue listener )
        throws LDAPException{
        return add( entry, listener, _defaultConstraints );
    }
 
    /**
     * Adds an entry to the directory and allows you to specify constraints
     * for this LDAP add operation by using an <CODE>LDAPConstraints</CODE>
     * object. For example, you can specify whether or not to follow referrals.
     * You can also apply LDAP v3 controls to the operation.
     * <P>
     *
     * @param entry LDAPEntry object specifying the distinguished name and
     * attributes of the new entry
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPEntry
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue add( LDAPEntry entry,
                                  LDAPResponseQueue listener,
                                  LDAPConstraints cons )
        throws LDAPException{

        if (cons == null) {
            cons = _defaultConstraints;
        }
        
        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        LDAPAttributeSet attrs = entry.getAttributeSet ();
        LDAPAttribute[] attrList = new LDAPAttribute[attrs.size()];
        Iterator it = attrs.iterator();
        for( int i = 0; i < attrs.size(); i++ ) {
            attrList[i] = (LDAPAttribute)it.next();
        }
        int attrPosition = 0;

        sendRequest (new JDAPAddRequest (entry.getDN(), attrList),
                    listener, cons);

        return listener;
    }

    /**
     * Registers an object to be notified on arrival of an unsolicited 
     * message from a server
     *
     * @param listener An object to be notified on arrival of an 
     * unsolicited message from a server
     */
    public void addUnsolicitedNotificationListener( 
        LDAPUnsolicitedNotificationListener listener ) {
    }

    /** 
     * Authenticates to the LDAP server (to which you are currently
     * connected) using the specified name and password.
     * If you are not already connected to the LDAP server, this
     * method attempts to reconnect to the server.
     * <P>
     *
     * For example, the following section of code authenticates the
     * client as Barbara Jensen.  The code assumes that the client
     * has already established a connection with an LDAP server.
     * <P>
     *
     * <PRE>
     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * String myPW = "hifalutin";
     * try {
     *     myConn.bind( myDN, myPW.getBytes() );
     * } catch ( LDAPException e ) {
     *     switch( e.getResultCode() ) {
     *         case e.NO_SUCH_OBJECT:
     *             System.out.println( "The specified user does not exist." );
     *             break;
     *         case e.INVALID_CREDENTIALS:
     *             System.out.println( "Invalid password." );
     *             break;
     *         default:
     *             System.out.println( "Error number: " + e.getResultCode() );
     *             System.out.println( "Failed to authentice as " + myDN );
     *             break;
     *     }
     *     return;
     * }
     * System.out.println( "Authenticated as " + myDN );
     * </PRE>
     *
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    private void bind( String dn, byte[] passwd) throws LDAPException {
        bind( _protocolVersion, dn, passwd, _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which you are currently
     * connected) using the specified name and password. The
     * default protocol version (version 2) is used. If the server
     * doesn't support the default version, an LDAPException is thrown
     * with the error code PROTOCOL_ERROR. This method allows the
     * user to specify the preferences for the bind operation.
     *
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @param cons preferences for the bind operation
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    private void bind( String dn, byte[] passwd,
                      LDAPConstraints cons ) throws LDAPException {
        bind( _protocolVersion, dn, passwd, cons );
    }

    /**
     * Authenticates to the LDAP server (to which you are currently
     * connected) using the specified name and password, and
     * requests that the server use at least the specified
     * protocol version. If the server doesn't support that
     * level, an LDAPException is thrown with the error code
     * PROTOCOL_ERROR.
     *
     * @param version required LDAP protocol version
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    public void bind( int version, String dn, byte[] passwd )
        throws LDAPException {
        bind( version, dn, passwd, _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which you are currently
     * connected) using the specified name and password, and
     * requesting that the server use at least the specified
     * protocol version. If the server doesn't support that
     * level, an LDAPException is thrown with the error code
     * PROTOCOL_ERROR. This method allows the user to specify the
     * preferences for the bind operation.
     *
     * @param version required LDAP protocol version
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @param cons preferences for the bind operation
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    public void bind( int version, String dn, byte[] passwd,
                      LDAPConstraints cons ) throws LDAPException {
        _prevBoundDN = _boundDN;
        _prevBoundPasswd = _boundPasswd;
        _boundDN = dn;
        _boundPasswd = passwd;

        _anonymousBound =
            ((_prevBoundDN == null) || (_prevBoundPasswd == null));

        internalBind (version, true, cons);
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and whatever SASL mechanisms
     * are supported by the server. Each supported mechanism in turn
     * is tried until authentication succeeds or an exception is thrown.
     * If the object has been disconnected from an LDAP server, this
     * method attempts to reconnect to the server. If the object had
     * already authenticated, the old authentication is discarded.
     *
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param authzid If not null and not empty, an LDAP authzID [AUTH] 
     * to be passed to the SASL layer. If null or empty, 
     * the authzId will be treated as an empty string 
     * and processed as per RFC 2222 [SASL].
     * @param props Optional qualifiers for the authentication session
     * @param cbh a class which the SASL framework can call to
     * obtain additional required information
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    public void bind( String dn,
                      String authzid,
                      Map props,
                      CallbackHandler cbh )
        throws LDAPException {
        bind( dn, authzid, props, cbh, _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and whatever SASL mechanisms
     * are supported by the server. Each supported mechanism in turn
     * is tried until authentication succeeds or an exception is thrown.
     * If the object has been disconnected from an LDAP server, this
     * method attempts to reconnect to the server. If the object had
     * already authenticated, the old authentication is discarded.
     *
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param authzid If not null and not empty, an LDAP authzID [AUTH] 
     * to be passed to the SASL layer. If null or empty, 
     * the authzId will be treated as an empty string 
     * and processed as per RFC 2222 [SASL].
     * @param props Optional qualifiers for the authentication session
     * @param cbh a class which the SASL framework can call to
     * obtain additional required information
     * @param cons preferences for the bind operation
     * @exception LDAPException Failed to authenticate to the LDAP server.
     */
    public void bind( String dn,
                      String authzid,
                      Map props,
                      CallbackHandler cbh,
                      LDAPConstraints cons )
        throws LDAPException {
        if ( !isConnected() ) {
            connect();
        }
        // Get the list of mechanisms from the server
        String[] attrs = { "supportedSaslMechanisms" };
        LDAPEntry entry = read( "", attrs );
        LDAPAttribute attr = entry.getAttribute( attrs[0] );
        if ( attr == null ) {
            throw new LDAPException( "Not found in root DSE: " +
                                     attrs[0],
                                     LDAPException.NO_SUCH_ATTRIBUTE );
        }
        bind( dn, authzid, attr.getStringValueArray(), props, cbh, cons );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and a specified SASL mechanism
     * or set of mechanisms. If the requested SASL mechanism is not
     * available, an exception is thrown.  If the object has been
     * disconnected from an LDAP server, this method attempts to reconnect
     * to the server. If the object had already authenticated, the old
     * authentication is discarded.
     *
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param authzid If not null and not empty, an LDAP authzID [AUTH] 
     * to be passed to the SASL layer. If null or empty, 
     * the authzId will be treated as an empty string 
     * and processed as per RFC 2222 [SASL].
     * @param props Optional qualifiers for the authentication session
     * @param mechanisms a list of acceptable mechanisms. The first one
     * for which a Mechanism Driver can be instantiated is returned.
     * @param cbh a class which the SASL framework can call to
     * obtain additional required information
     * @exception LDAPException Failed to authenticate to the LDAP server.
     * @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
     * CallbackHandler)
     */
    public void bind( String dn,
                      String authzid,
                      String[] mechanisms,
                      Map props,
                      CallbackHandler cbh )
        throws LDAPException {
        bind( dn, authzid, mechanisms, props, cbh, _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and a specified SASL mechanism
     * or set of mechanisms. If the requested SASL mechanism is not
     * available, an exception is thrown.  If the object has been
     * disconnected from an LDAP server, this method attempts to reconnect
     * to the server. If the object had already authenticated, the old
     * authentication is discarded.
     *
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param authzid If not null and not empty, an LDAP authzID [AUTH] 
     * to be passed to the SASL layer. If null or empty, 
     * the authzId will be treated as an empty string 
     * and processed as per RFC 2222 [SASL].
     * @param props Optional qualifiers for the authentication session
     * @param mechanisms a list of acceptable mechanisms. The first one
     * for which a Mechanism Driver can be instantiated is returned.
     * @param cbh a class which the SASL framework can call to
     * obtain additional required information
     * @param cons preferences for the bind operation
     * @exception LDAPException Failed to authenticate to the LDAP server.
     * @see org.ietf.ldap.LDAPConnection#bind(String, String, Map,
     * CallbackHandler, LDAPConstraints)
     */
    public void bind( String dn,
                      String authzid,
                      String[] mechanisms,
                      Map props,
                      CallbackHandler cbh,
                      LDAPConstraints cons )
        throws LDAPException {

        if ( !isConnected() ) {
            connect();
        } else {
            // If the thread has more than one LDAPConnection, then
            // we should disconnect first. Otherwise,
            // we can reuse the same thread for the rebind.
            if (_thread.getClientCount() > 1) {
                disconnect();
                connect();
            }
        }
        _boundDN = null;
        _protocolVersion = 3; // Must be 3 for SASL
        if ( props == null ) {
            props = new Hashtable();
        }
        _saslBinder = new LDAPSaslBind( dn, mechanisms,
                                        props, cbh );
        _saslCallbackHandler = cbh;
        _saslBinder.bind( this );
        _authMethod = "sasl";
        _boundDN = dn;
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and password. If the object
     * has been disconnected from an LDAP server, this method attempts to
     * reconnect to the server. If the object had already authenticated, the
     * old authentication is discarded.
     * 
     * @param version required LDAP protocol version
     * @param dn if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name and passwd as password
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue bind( int version,
                                   String dn,
                                   byte[] passwd,
                                   LDAPResponseQueue listener )
        throws LDAPException{
        return bind( version, dn, passwd, listener, _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and password. If the object
     * has been disconnected from an LDAP server, this method attempts to
     * reconnect to the server. If the object had already authenticated, the
     * old authentication is discarded.
     * 
     * @param dn if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name and passwd as password
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    private LDAPResponseQueue bind( String dn,
                                    byte[] passwd,
                                    LDAPResponseQueue listener)
        throws LDAPException{
        return bind( _protocolVersion, dn, passwd, listener,
                     _defaultConstraints );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and password and allows you
     * to specify constraints for this LDAP add operation by using an
     *  <CODE>LDAPConstraints</CODE> object. If the object
     * has been disconnected from an LDAP server, this method attempts to
     * reconnect to the server. If the object had already authenticated, the
     * old authentication is discarded.
     * 
     * @param dn if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name and passwd as password
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    private LDAPResponseQueue bind( String dn,
                                    byte[] passwd,
                                    LDAPResponseQueue listener,
                                    LDAPConstraints cons )
        throws LDAPException{
        return bind( _protocolVersion, dn, passwd, listener, cons );
    }

    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and password and allows you
     * to specify constraints for this LDAP add operation by using an
     *  <CODE>LDAPConstraints</CODE> object. If the object
     * has been disconnected from an LDAP server, this method attempts to
     * reconnect to the server. If the object had already authenticated, the
     * old authentication is discarded.
     * 
     * @param version required LDAP protocol version
     * @param dn if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection
     * and all operations through it should authenticate with dn as the
     * distinguished name and passwd as password
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue bind( int version,
                                   String dn,
                                   byte[] passwd,
                                   LDAPResponseQueue listener,
                                   LDAPConstraints cons ) 
        throws LDAPException{
        if (cons == null) {
            cons = _defaultConstraints;
        }

        _prevBoundDN = _boundDN;
        _prevBoundPasswd = _boundPasswd;
        _boundDN = dn;
        _boundPasswd = passwd;
        _protocolVersion = version;
        
        if (_thread == null) {
            connect();
        }
        else if (_thread.getClientCount() > 1) {
            disconnect();
            connect();
        }

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        sendRequest(new JDAPBindRequest(version, _boundDN, _boundPasswd),
            listener, cons);

        return listener;
    }
    
    /**
     * Authenticates to the LDAP server (to which the object is currently
     * connected) using the specified name and a specified SASL mechanism
     * or set of mechanisms. If the requested SASL mechanism is not
     * available, an exception is thrown.  If the object has been
     * disconnected from an LDAP server, this method attempts to reconnect
     * to the server. If the object had already authenticated, the old
     * authentication is discarded.
     *
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param authzid If not null and not empty, an LDAP authzID [AUTH] 
     * to be passed to the SASL layer. If null or empty, 
     * the authzId will be treated as an empty string 
     * and processed as per RFC 2222 [SASL].
     * @param mechanisms a list of acceptable mechanisms. The first one
     * for which a Mechanism Driver can be instantiated is returned.
     * @param packageName a package containing a SASL ClientFactory,
     * e.g. "myclasses.SASL". If null, a system default is used.
     * @param cbh a class which the SASL framework can call to
     * obtain additional required information
     * @exception LDAPException Failed to authenticate to the LDAP server.
     * @deprecated Please use authenticate without packageName
     * instead.
     */
    public void bind( String dn,
                      String authzid,
                      String[] mechanisms,
                      String packageName,
                      Map props,
                      CallbackHandler cbh,
                      LDAPConstraints cons )
        throws LDAPException {
        if ( props == null ) {
            props = new Hashtable();
        }
        props.put( LDAPSaslBind.CLIENTPKGS, packageName );
        bind( dn, authzid, mechanisms, props, cbh, cons );
    }
    
    /**
     * Creates and returns a copy of the object. The new
     * <CODE>LDAPConnection</CODE> object contains the same information as
     * the original connection, including:
     * <UL>
     * <LI>the default search constraints
     * <LI>host name and port number of the LDAP server
     * <LI>the DN and password used to authenticate to the LDAP server
     * </UL>
     * <P>
     * @return the <CODE>LDAPconnection</CODE> object representing the
     * new object.
     */
    public synchronized Object clone() {
        try {
            LDAPConnection c = (LDAPConnection)super.clone();

            if (!isConnected()) {
                this.internalBind(_defaultConstraints);
            }

            c._defaultConstraints =
                (LDAPSearchConstraints)_defaultConstraints.clone();
            c._responseListeners = null;
            c._searchListeners = null;
            c._bound = this._bound;
            c._connMgr = _connMgr;
            c._connSetupDelay = _connSetupDelay;
            c._boundDN = this._boundDN;
            c._boundPasswd = this._boundPasswd;
            c._prevBoundDN = this._prevBoundDN;
            c._prevBoundPasswd = this._prevBoundPasswd;
            c._anonymousBound = this._anonymousBound;
            c.setCache(this._cache); // increments cache reference cnt
            c._factory = this._factory;
            c._thread = this._thread; /* share current connection thread */

            synchronized (_threadConnTable) {
                Vector v = (Vector)_threadConnTable.get(this._thread);
                if (v != null) {
                    v.addElement(c);
                } else {
                    printDebug("Failed to clone");
                    return null;
                }
            }

            c._thread.register(c);
            return c;
        } catch (Exception e) {
        }
        return null;
    }

    /**
     * Checks to see if an entry contains an attribute with a specified value.
     * Returns <CODE>true</CODE> if the entry has the value. Returns
     * <CODE>false</CODE> if the entry does not have the value or the
     * attribute. To represent the value that you want compared, you need
     * to create an <CODE>LDAPAttribute</CODE> object.<P>
     *
     * Note that only string values can be compared. <P>
     *
     * For example, the following section of code checks to see if the entry
     * "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US" contains
     * the attribute "mail" with the value "bjensen@aceindustry.com".
     *
     * <PRE>
     * ...
     * LDAPConnection myConn = new LDAPConnection();
     * ...
     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * String nameOfAttr = "mail";
     * String valOfAttr = "bjensen@aceindustry.com";
     * LDAPAttribute cmpThisAttr = new LDAPAttribute( nameOfAttr, valOfAttr );
     * boolean hasValue = myConn.compare( myDN, cmpThisAttr );
     * if ( hasValue ) {
     *     System.out.println( "Attribute and value found in entry." );
     * } else {
     *     System.out.println( "Attribute and value not found in entry." );
     * }
     * ...</PRE>
     *
     * @param DN the distinguished name of the entry to use in
     * the comparison
     * @param attr the attribute to compare against the entry.
     * (The method checks to see if the entry has an attribute with the same name
     * and value as this attribute.)
     * @return true if the entry contains the specified attribute and value.
     * @exception LDAPException Failed to perform the comparison.
     * @see org.ietf.ldap.LDAPAttribute
     */
    public boolean compare( String DN, LDAPAttribute attr )
        throws LDAPException {
        return compare( DN, attr, _defaultConstraints );
    }

    public boolean compare( String DN, LDAPAttribute attr,
                            LDAPConstraints cons ) throws LDAPException {
        internalBind(cons);

        LDAPResponseQueue myListener = getResponseListener ();
        Enumeration en = attr.getStringValues();
        String val = (String)en.nextElement();
        JDAPAVA ass = new JDAPAVA(attr.getName(), val);

        LDAPMessage response;
        try {
            sendRequest (new JDAPCompareRequest (DN, ass), myListener, cons);
            response = myListener.getResponse ();

            int resultCode = ((JDAPResult)response.getProtocolOp()).getResultCode();
            if (resultCode == JDAPResult.COMPARE_FALSE) {
                return false;
            }
            if (resultCode == JDAPResult.COMPARE_TRUE) {
                return true;
            }

            checkMsg (response);

        } catch (LDAPReferralException e) {
            Vector res = new Vector();
            performReferrals(e, cons, JDAPProtocolOp.COMPARE_REQUEST,
                             DN, 0, null, null, false, null, null, attr, res);
            boolean bool = false;
            if (res.size() > 0) {
               bool = ((Boolean)res.elementAt(0)).booleanValue();
            }
            return bool;
        } finally {
            releaseResponseListener (myListener);
        }
        return false; /* this should never be executed */
    }

    /**
     * @deprecated Please use the method signature where <CODE>cons</CODE> is
     * <CODE>LDAPConstraints</CODE> instead of <CODE>LDAPSearchConstraints</CODE>
     */
    public boolean compare( String DN,
                            LDAPAttribute attr,
                            LDAPSearchConstraints cons ) throws LDAPException {
        return compare( DN, attr, (LDAPConstraints)cons );
    }        
    
    /**
     * Compare an attribute value with one in the directory. The result can 
     * be obtained by calling <CODE>getResultCode</CODE> on the 
     * <CODE>LDAPResponse</CODE> from the <CODE>LDAPResponseQueue</CODE>.
     * The code will be <CODE>LDAPException.COMPARE_TRUE</CODE> or 
     * <CODE>LDAPException.COMPARE_FALSE</CODE>. 
     * 
     * @param dn distinguished name of the entry to compare
     * @param attr attribute with a value to compare
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     */
    public LDAPResponseQueue compare( String dn, 
                                      LDAPAttribute attr, 
                                      LDAPResponseQueue listener )
        throws LDAPException {

        return compare( dn, attr, listener, _defaultConstraints );
    }
    
    /**
     * Compare an attribute value with one in the directory. The result can 
     * be obtained by calling <CODE>getResultCode</CODE> on the 
     * <CODE>LDAPResponse</CODE> from the <CODE>LDAPResponseQueue</CODE>.
     * The code will be <CODE>LDAPException.COMPARE_TRUE</CODE> or 
     * <CODE>LDAPException.COMPARE_FALSE</CODE>. 
     * 
     * @param dn distinguished name of the entry to compare
     * @param attr attribute with a value to compare
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to this operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     */
    public LDAPResponseQueue compare( String dn, 
                                      LDAPAttribute attr, 
                                      LDAPResponseQueue listener,
                                      LDAPConstraints cons )
        throws LDAPException {
        if (cons == null) {
            cons = _defaultConstraints;
        }
        
        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        Enumeration en = attr.getStringValues();
        String val = (String)en.nextElement();
        JDAPAVA ava = new JDAPAVA(attr.getName(), val);
        
        sendRequest (new JDAPCompareRequest (dn, ava), listener, cons);
        return listener;
    }
    
    /**
     * Connects to the specified host and port.  If this LDAPConnection object
     * represents an open connection, the connection is closed first
     * before the new connection is opened.
     * <P>
     *
     * For example, the following section of code establishes a connection with
     * the LDAP server running on the host ldap.netscape.com and the port 389.
     * <P>
     *
     * <PRE>
     * String ldapHost = "ldap.netscape.com";
     * int ldapPort = 389;
     * LDAPConnection myConn = new LDAPConnection();
     * try {
     *     myConn.connect( ldapHost, ldapPort );
     * } catch ( LDAPException e ) {
     *     System.out.println( "Unable to connect to " + ldapHost +
     *                         " at port " + ldapPort );
     *     return;
     * }
     * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort )
     * </PRE>
     *<P>
     * You can limit the time spent waiting for the connection to be established
     * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>. 
     * <P>
     * @param host host name of the LDAP server to which you want to connect.
     * This value can also be a space-delimited list of hostnames or
     * hostnames and port numbers (using the syntax
     * <I>hostname:portnumber</I>). For example, you can specify
     * the following values for the <CODE>host</CODE> argument:<BR>
     *<PRE>
     *   myhost
     *   myhost hishost:389 herhost:5000 whathost
     *   myhost:686 myhost:389 hishost:5000 whathost:1024
     *</PRE>
     * If multiple servers are specified in the <CODE>host</CODE> list, the connection
     *  setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
     * whether connection attempts are made serially or concurrently.
     * <P>
     * @param port port number of the LDAP server to which you want to connect.
     * This parameter is ignored for any host in the <CODE>host</CODE>
     * parameter which includes a colon and port number.
     * @exception LDAPException The connection failed.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
     */
    public void connect(String host, int port) throws LDAPException {
        connect( host, port, null, null, _defaultConstraints, false );
    }

    /**
     * Connects to the specified host and port and uses the specified DN and
     * password to authenticate to the server.  If this LDAPConnection object
     * represents an open connection, the connection is closed first
     * before the new connection is opened.
     * <P>
     *
     * For example, the following section of code establishes a connection
     * with the LDAP server running on ldap.netscape.com at port 389.  The
     * example also attempts to authenticate the client as Barbara Jensen.
     * <P>
     *
     * <PRE>
     * String ldapHost = "ldap.netscape.com";
     * int ldapPort = 389;
     * String myDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * String myPW = "hifalutin";
     * LDAPConnection myConn = new LDAPConnection();
     * try {
     *     myConn.connect( ldapHost, ldapPort, myDN, myPW );
     * } catch ( LDAPException e ) {
     *     switch( e.getResultCode() ) {
     *         case e.NO_SUCH_OBJECT:
     *             System.out.println( "The specified user does not exist." );
     *             break;
     *         case e.INVALID_CREDENTIALS:
     *             System.out.println( "Invalid password." );
     *             break;
     *         default:
     *             System.out.println( "Error number: " + e.getResultCode() );
     *             System.out.println( "Failed to connect to " + ldapHost + " at port " + ldapPort );
     *             break;
     *     }
     *     return;
     * }
     * System.out.println( "Connected to " + ldapHost + " at port " + ldapPort );
     * </PRE>
     *<P>
     * You can limit the time spent waiting for the connection to be established
     * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>. 
     * <P>
     * @param host host name of the LDAP server to which you want to connect.
     * This value can also be a space-delimited list of hostnames or
     * hostnames and port numbers (using the syntax
     * <I>hostname:portnumber</I>). For example, you can specify
     * the following values for the <CODE>host</CODE> argument:<BR>
     *<PRE>
     *   myhost
     *   myhost hishost:389 herhost:5000 whathost
     *   myhost:686 myhost:389 hishost:5000 whathost:1024
     *</PRE>
     * If multiple servers are specified in the <CODE>host</CODE> list, the connection
     *  setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
     * whether connection attempts are made serially or concurrently.
     * <P>
     * @param port port number of the LDAP server to which you want to connect.
     * This parameter is ignored for any host in the <CODE>host</CODE>
     * parameter which includes a colon and port number.
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @exception LDAPException The connection or authentication failed.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
     */
    private void connect(String host, int port, String dn, byte[] passwd)
        throws LDAPException {
        connect(host, port, dn, passwd, _defaultConstraints, true);
    }

    /**
     * Connects to the specified host and port and uses the specified DN and
     * password to authenticate to the server.  If this LDAPConnection object
     * represents an open connection, the connection is closed first
     * before the new connection is opened. This method allows the user to 
     * specify the preferences for the bind operation.
     *<P>
     * You can limit the time spent waiting for the connection to be established
     * by calling <CODE>setConnectTimeout</CODE> before <CODE>connect</CODE>. 
     * <P>
     * @param host host name of the LDAP server to which you want to connect.
     * This value can also be a space-delimited list of hostnames or
     * hostnames and port numbers (using the syntax
     * <I>hostname:portnumber</I>). For example, you can specify
     * the following values for the <CODE>host</CODE> argument:<BR>
     *<PRE>
     *   myhost
     *   myhost hishost:389 herhost:5000 whathost
     *   myhost:686 myhost:389 hishost:5000 whathost:1024
     *</PRE>
     * If multiple servers are specified in the <CODE>host</CODE> list, the connection
     *  setup policy specified with the <CODE>ConnSetupDelay</CODE> property controls
     * whether connection attempts are made serially or concurrently.
     * <P>
     * @param port port number of the LDAP server to which you want to connect.
     * This parameter is ignored for any host in the <CODE>host</CODE>
     * parameter which includes a colon and port number.
     * @param dn distinguished name used for authentication
     * @param passwd password used for authentication
     * @param cons preferences for the bind operation
     * @exception LDAPException The connection or authentication failed.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
     */
    private void connect(String host, int port, String dn, byte[] passwd,
        LDAPConstraints cons) throws LDAPException {
        connect(host, port, dn, passwd, cons, true);
    }

    private void connect(String host, int port, String dn, byte[] passwd,
      LDAPConstraints cons, boolean doAuthenticate) 
        throws LDAPException {
        if ( isConnected() ) {
            disconnect ();
        }
        if ((host == null) || (host.equals(""))) {
            throw new LDAPException ( "no host for connection",
                                      LDAPException.PARAM_ERROR );
        }

        /* Parse the list of hosts */    
        int defaultPort = port;
        StringTokenizer st = new StringTokenizer( host );
        String hostList[] = new String[st.countTokens()];
        int portList[] = new int[st.countTokens()];
        int i = 0;
        while( st.hasMoreTokens() ) {
            String s = st.nextToken();
            int colon = s.indexOf( ':' );
            if ( colon > 0 ) {
                hostList[i] = s.substring( 0, colon );
                portList[i] = Integer.parseInt( s.substring( colon+1 ) );
            } else {
                hostList[i] = s;
                portList[i] = defaultPort;
            }
            i++;
        }

        /* Create the Connection Setup Manager */
        _connMgr = new LDAPConnSetupMgr(hostList, portList, _factory);
        _connMgr.setConnSetupDelay(_connSetupDelay);
        _connMgr.setConnectTimeout(_connectTimeout);
    
        connect();

        if ( doAuthenticate ) {
            bind( dn, passwd, cons );
        }
    }

    /**
     * Connects to the specified host and port and uses the specified DN and
     * password to authenticate to the server, with the specified LDAP
     * protocol version. If the server does not support the requested
     * protocol version, an exception is thrown. If this LDAPConnection
     * object represents an open connection, the connection is closed first
     * before the new connection is opened. This is equivalent to
     * <CODE>connect(host, port)</CODE> followed by <CODE>bind(version, dn, passwd)</CODE>.<P>
     *
     * @param version requested version of LDAP: currently 2 or 3
     * @param host a hostname to which to connect or a dotted string representing
     * the IP address of this host.
     * Alternatively, this can be a space-delimited list of host names.
     * Each host name may include a trailing colon and port number. In the
     * case where more than one host name is specified, the connection setup
     * policy specified with the <CODE>ConnSetupDelay</CODE> property controls
     * whether connection attempts are made serially or concurrently.<P>
     *
     * <PRE>
     *   Examples:
     *      "directory.knowledge.com"
     *      "199.254.1.2"
     *      "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
     * </PRE>
     * @param port the TCP or UDP port number to which to connect or contact.
     * The default LDAP port is 389. "port" is ignored for any host name which
     * includes a colon and port number.
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name and passwd as password.
     * @exception LDAPException The connection or authentication failed.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     */
    private void connect(int version, String host, int port, String dn,
        byte[] passwd) throws LDAPException {

        connect(version, host, port, dn, passwd, _defaultConstraints);
    }

    /**
     * Connects to the specified host and port and uses the specified DN and
     * password to authenticate to the server, with the specified LDAP
     * protocol version. If the server does not support the requested
     * protocol version, an exception is thrown. This method allows the user
     * to specify preferences for the bind operation. If this LDAPConnection
     * object represents an open connection, the connection is closed first
     * before the new connection is opened. This is equivalent to
     * <CODE>connect(host, port)</CODE> followed by <CODE>bind(version, dn, passwd)</CODE>.<P>
     *
     * @param version requested version of LDAP: currently 2 or 3
     * @param host a hostname to which to connect or a dotted string representing
     * the IP address of this host.
     * Alternatively, this can be a space-delimited list of host names.
     * Each host name may include a trailing colon and port number. In the
     * case where more than one host name is specified, the connection setup
     * policy specified with the <CODE>ConnSetupDelay</CODE> property controls
     * whether connection attempts are made serially or concurrently.<P>
     *
     * <PRE>
     *   Examples:
     *      "directory.knowledge.com"
     *      "199.254.1.2"
     *      "directory.knowledge.com:1050 people.catalog.com 199.254.1.2"
     * </PRE>
     * @param port the TCP or UDP port number to which to connect or contact.
     * The default LDAP port is 389. "port" is ignored for any host name which
     * includes a colon and port number.
     * @param dn if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name
     * @param passwd if non-null and non-empty, specifies that the connection and
     * all operations through it should authenticate with dn as the
     * distinguished name and passwd as password
     * @param cons preferences for the bind operation
     * @exception LDAPException The connection or authentication failed.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     */
    private void connect(int version, String host, int port, String dn,
        byte[] passwd, LDAPConstraints cons) throws LDAPException {

        setProtocolVersion(version);
        connect(host, port, dn, passwd, cons);
    }

    /**
     * @deprecated Please use the method signature where <CODE>cons</CODE> is
     * <CODE>LDAPConstraints</CODE> instead of <CODE>LDAPSearchConstraints</CODE>
     */
    private void connect(int version, String host, int port, String dn,
        byte[] passwd, LDAPSearchConstraints cons) throws LDAPException {

        connect(version, host, port, dn, passwd, (LDAPConstraints)cons);
    }

    /**
     * Internal routine to connect with internal params
     * @exception LDAPException failed to connect
     */
    private synchronized void connect () throws LDAPException {
        if ( isConnected() ) {
            return;
        }

        if (_connMgr == null) {
            throw new LDAPException ( "no connection parameters",
                                      LDAPException.PARAM_ERROR );
        }        

        _connMgr.openConnection();
        _thread = getNewThread(_connMgr, _cache);
        authenticateSSLConnection();
    }

    /**
     * Deletes the entry for the specified DN from the directory. <P>
     *
     * For example, the following section of code deletes the entry for
     * Barbara Jensen from the directory. <P>
     *
     * <PRE>
     * ...
     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * myConn.delete( myEntryDN );
     * ... </PRE>
     *
     * @param DN distinguished name identifying the entry
     * to remove from the directory
     * @exception LDAPException Failed to delete the specified entry from
     * the directory.
     */
    public void delete( String DN ) throws LDAPException {
        delete(DN, _defaultConstraints);
    }

    /**
     * Deletes the entry for the specified DN from the directory and
     * allows you to specify preferences for this LDAP delete operation
     * by using an <CODE>LDAPConstraints</CODE> object. For
     * example, you can specify whether or not to follow referrals.
     * You can also apply LDAP v3 controls to the operation.
     * <P>
     *
     * @param DN distinguished name identifying the entry 
     * to remove from the directory
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to delete the specified entry from
     * the directory.
     * @see org.ietf.ldap.LDAPConstraints
     */
    public void delete( String DN, LDAPConstraints cons )
        throws LDAPException {
        internalBind (cons);

        LDAPResponseQueue myListener = getResponseListener ();
        LDAPMessage response;
        try {
            sendRequest (new JDAPDeleteRequest (DN), myListener, cons);
            response = myListener.getResponse();
            checkMsg (response);
        } catch (LDAPReferralException e) {
            performReferrals(e, cons, JDAPProtocolOp.DEL_REQUEST,
                             DN, 0, null, null, false, null, null, null, null);
        } finally {
            releaseResponseListener (myListener);
        }
    }

    /**
     * Deletes the entry for the specified DN from the directory.
     * 
     * @param dn distinguished name of the entry to delete
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue delete( String dn,
                                     LDAPResponseQueue listener )
        throws LDAPException {
        
        return delete( dn, listener, _defaultConstraints );
    }

    /**
     * Deletes the entry for the specified DN from the directory.
     * 
     * @param dn distinguished name of the entry to delete
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue delete( String dn,
                                     LDAPResponseQueue listener,
                                     LDAPConstraints cons )
        throws LDAPException {
        if (cons == null) {
            cons = _defaultConstraints;
        }

        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }
        
        sendRequest (new JDAPDeleteRequest(dn), listener, cons);
        
        return listener;

    }
    
    /**
     * Disconnects from the LDAP server. Before you can perform LDAP operations
     * again, you need to reconnect to the server by calling
     * <CODE>connect</CODE>.
     * @exception LDAPException Failed to disconnect from the LDAP server.
     * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
     */
    public synchronized void disconnect() throws LDAPException {
        if (!isConnected())
            throw new LDAPException ( "unable to disconnect() without connecting",
                                      LDAPException.OTHER );
        
        // Clone the Connection Setup Manager if the connection is shared
        if (_thread.isRunning() && _thread.getClientCount() > 1) {
            _connMgr = (LDAPConnSetupMgr) _connMgr.clone();
            _connMgr.disconnect();
        }

        if (_referralConnection != null && _referralConnection.isConnected()) {
            _referralConnection.disconnect();
        }
        _referralConnection = null;

        if (_cache != null) {
            _cache.removeReference();
            _cache = null;
        }

        deleteThreadConnEntry();
        deregisterConnection();
    }

    /**
     * Performs an extended operation on the directory.  Extended operations
     * are part of version 3 of the LDAP protocol.<P>
     *
     * Note that in order for the extended operation to work, the server
     * that you are connecting to must support LDAP v3 and must be configured
     * to process the specified extended operation.
     *
     * @param op LDAPExtendedOperation object specifying the OID of the
     * extended operation and the data to use in the operation
     * @exception LDAPException Failed to execute the operation
     * @return LDAPExtendedOperation object representing the extended response
     * returned by the server.
     * @see org.ietf.ldap.LDAPExtendedOperation
     */
    public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op )
        throws LDAPException {

        return extendedOperation(op, _defaultConstraints);
    }

    /**
     * Performs an extended operation on the directory.  Extended operations
     * are part of version 3 of the LDAP protocol. This method allows the
     * user to set the preferences for the operation.<P>
     *
     * Note that in order for the extended operation to work, the server
     * that you are connecting to must support LDAP v3 and must be configured
     * to process the specified extended operation.
     *
     * @param op LDAPExtendedOperation object specifying the OID of the
     * extended operation and the data to use in the operation
     * @param cons preferences for the extended operation
     * @exception LDAPException Failed to execute the operation
     * @return LDAPExtendedOperation object representing the extended response
     * returned by the server.
     * @see org.ietf.ldap.LDAPExtendedOperation
     */
    public LDAPExtendedOperation extendedOperation( LDAPExtendedOperation op,
                                                    LDAPConstraints cons )
        throws LDAPException {
        internalBind (cons);

        LDAPResponseQueue myListener = getResponseListener ();
        LDAPMessage response = null;
        byte[] results = null;
        String resultID;

        try {
            sendRequest ( new JDAPExtendedRequest( op.getID(),
                                                   op.getValue() ),
                          myListener, cons );
            response = myListener.getResponse();
            checkMsg (response);
            JDAPExtendedResponse res = (JDAPExtendedResponse)response.getProtocolOp();
            results = res.getValue();
            resultID = res.getID();
        } catch (LDAPReferralException e) {
            return performExtendedReferrals( e, cons, op );
        } finally {
            releaseResponseListener (myListener);
        }
        return new LDAPExtendedOperation( resultID, results );
    }

    /**
     * Performs an extended operation on the directory.  Extended operations
     * are part of version 3 of the LDAP protocol.<P>
     *
     * Note that in order for the extended operation to work, the server
     * that you are connecting to must support LDAP v3 and must be configured
     * to process the specified extended operation.
     *
     * @param op LDAPExtendedOperation object specifying the OID of the
     * extended operation and the data to use in the operation
     * @param queue handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @exception LDAPException Failed to execute the operation
     * @return LDAPExtendedOperation object representing the extended response
     * returned by the server.
     * @see org.ietf.ldap.LDAPExtendedOperation
     */
    public LDAPResponseQueue extendedOperation( 
        LDAPExtendedOperation op, 
        LDAPResponseQueue queue )
        throws LDAPException {
        return extendedOperation( op, queue, _defaultConstraints );
    }
    
    /**
     * Performs an extended operation on the directory.  Extended operations
     * are part of version 3 of the LDAP protocol.<P>
     *
     * Note that in order for the extended operation to work, the server
     * that you are connecting to must support LDAP v3 and must be configured
     * to process the specified extended operation.
     *
     * @param op LDAPExtendedOperation object specifying the OID of the
     * extended operation and the data to use in the operation
     * @param queue handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to execute the operation
     * @return LDAPExtendedOperation object representing the extended response
     * returned by the server.
     * @see org.ietf.ldap.LDAPExtendedOperation
     */
    public LDAPResponseQueue extendedOperation( 
        LDAPExtendedOperation op, 
        LDAPResponseQueue queue,
        LDAPConstraints cons )
        throws LDAPException {
        return null;
    }

    /**
     * Finalize method, which disconnects from the LDAP server
     * @exception LDAPException Thrown on error in disconnecting
     */
    protected void finalize() throws LDAPException {
        if (isConnected()) {
            disconnect();
        }
    }

    /**
     * Returns the distinguished name (DN) used for authentication over
     * this connection.
     * @return distinguished name used for authentication over this connection.
     */
    public String getAuthenticationDN () {
        return _boundDN;
    }

    /**
     * Returns the password used for authentication over this connection.
     * @return password used for authentication over this connection.
     */
    byte[] getAuthenticationPassword () {
        return _boundPasswd;
    }
    

    /**
     * Gets the authentication method used to bind:<BR>
     * "none", "simple", or "sasl"
     *
     * @return the authentication method, or "none"
     */
    public String getAuthenticationMethod() {
        return isConnected() ? _authMethod : "none";
    }

    /**
     * Gets the <CODE>LDAPCache</CODE> object associated with
     * the current <CODE>LDAPConnection</CODE> object.
     * <P>
     *
     * @return the <CODE>LDAPCache</CODE> object representing
     * the cache that the current connection should use
     * @see org.ietf.ldap.LDAPCache
     * @see org.ietf.ldap.LDAPConnection#setCache(org.ietf.ldap.LDAPCache)
     */
    public LDAPCache getCache() {
        return _cache;
    }

    /**
     * Returns the maximum time to wait for the connection to be established.
     * @return the maximum connect time in seconds or 0 (unlimited)
     * @see org.ietf.ldap.LDAPConnection#setConnectTimeout
     */
    public int getConnectTimeout () {
        return _connectTimeout;
    }

    /**
     * Returns the delay in seconds when making concurrent connection attempts to
     * multiple servers.
     * @return the delay in seconds between connection attempts:<br>
     * <CODE>NODELAY_SERIAL</CODE> The serial connection setup policy is enabled
     * (no concurrency).<br>
     * <CODE>NODELAY_PARALLEL</CODE> The parallel connection setup policy with no delay
     *  is enabled.<br>
     * <CODE>delay > 0</CODE> The parallel connection setup policy with the delay of 
     * <CODE>delay</CODE> seconds is enabled.
     * @see org.ietf.ldap.LDAPConnection#setConnSetupDelay
     */
    public int getConnSetupDelay () {
        return _connSetupDelay;
    }

    /**
     * Returns the set of constraints that apply to all operations
     * performed through this connection (unless you specify a different
     * set of constraints when calling a method). 
     * <P>
     *
     * Note that if you want to get individual constraints (rather than
     * getting the
     * entire set of constraints), call the <CODE>getOption</CODE> method.
     * <P>
     *
     * Typically, you might call the <CODE>getConstraints</CODE> method
     * to create a slightly different set of constraints for a particular 
     * operation.
     * <P>
     *
     * For example, the following section of code changes the timeout
     * to 3000 milliseconds for a specific rename. Rather than construct a new
     * set of constraints from scratch, the example gets the current
     * settings for the connections and just changes the setting for the
     * timeout.
     * <P>
     *
     * Note that this change only applies to the searches performed with this
     * custom set of constraints.  All other searches performed through this
     * connection use the original set of search constraints.
     * <P>
     *
     * <PRE>
     * ...
     * LDAPConstraints myOptions = ld.getConstraints();
     * myOptions.setTimeout( 3000 );
     * ld.search( "cn=William Jensen, ou=Accounting, o=Ace Industry,c=US",
     *            "cn=Will Jensen",
     *            null,
     *            false,
     *            myOptions );
     * ...
     * </PRE>
     *
     * @return a copy of the <CODE>LDAPConstraints</CODE> object representing the
     * set of constraints that apply (by default) to all operations
     * performed through this connection.
     * @see org.ietf.ldap.LDAPConstraints
     * @see org.ietf.ldap.LDAPConnection#getOption
     */
    public LDAPConstraints getConstraints () {
        return (LDAPConstraints)getSearchConstraints();
    }
   
    /**
     * Returns the host name of the LDAP server to which you are connected.
     * @return host name of the LDAP server.
     */
    public String getHost () {
        if (_connMgr != null) {
            return _connMgr.getHost();
        }
        return null;
    }

    /**
     * Gets the stream for reading from the listener socket
     *
     * @return the stream for reading from the listener socket, or
     * <CODE>null</CODE> if there is none
     */
    public InputStream getInputStream() {
        return (_thread != null) ? _thread.getInputStream() : null;
    }

    /**
     * Gets the stream for writing to the socket
     *
     * @return the stream for writing to the socket, or
     * <CODE>null</CODE> if there is none
     */
    public OutputStream getOutputStream() {
        return (_thread != null) ? _thread.getOutputStream() : null;
    }

    /**
     * Returns the port number of the LDAP server to which you are connected.
     * @return port number of the LDAP server.
     */
    public int getPort () {
        if (_connMgr != null) {
            return _connMgr.getPort();
        }
        return -1;
    }

    /**
     * Gets a property of a connection. <P>
     *
     * You can get the following properties for a given connection: <P>
     * <UL TYPE="DISC">
     * <LI><CODE>LDAP_PROPERTY_SDK</CODE> <P>
     * To get the version of this SDK, get this property.  The value of
     * this property is of the type <CODE>Float</CODE>. <P>
     * <LI><CODE>LDAP_PROPERTY_PROTOCOL</CODE> <P>
     * To get the highest supported version of the LDAP protocol, get
     * this property.
     * The value of this property is of the type <CODE>Float</CODE>. <P>
     * <LI><CODE>LDAP_PROPERTY_SECURITY</CODE> <P>
     * To get a comma-separated list of the types of authentication
     * supported, get this property.  The value of this property is of the
     * type <CODE>String</CODE>. <P>
     * </UL>
     * <P>
     *
     * For example, the following section of code gets the version of
     * the SDK.<P>
     *
     * <PRE>
     *       ...
     *       Float sdkVersion = ( Float )myConn.getProperty( myConn.LDAP_PROPERTY_SDK );
     *       System.out.println( "SDK version: " + sdkVersion );
     *       ... </PRE>
     *
     * @param name name of the property (for example, <CODE>LDAP_PROPERTY_SDK</CODE>) <P>
     *
     * @return the value of the property. <P>
     *
     * Since the return value is an object, you should recast it as the appropriate type.
     * (For example, when getting the <CODE>LDAP_PROPERTY_SDK</CODE> property,
     * recast the return value as a <CODE>Float</CODE>.) <P>
     *
     * If you pass this method an unknown property name, the method
     * returns null. <P>
     *
     * @exception LDAPException Unable to get the value of the
     * specified property. <P>
     *
     * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_SDK
     * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_PROTOCOL
     * @see org.ietf.ldap.LDAPConnection#LDAP_PROPERTY_SECURITY
     */
    public Object getProperty(String name) throws LDAPException {
        return _properties.get( name );
    }

    /**
     * Returns the protocol version that the connection is bound to (which 
     * currently is 3). If the connection is not bound, it returns 3.
     *
     * @return the protocol version that the connection is bound to
     */
    public int getProtocolVersion() {
        return _protocolVersion;
    }

    /**
     * Returns an array of the latest controls (if any) from server.
     * <P>
     * To retrieve the controls from a search result, call the 
     * <CODE>getResponseControls</CODE> method from the <CODE>LDAPSearchResults
     * </CODE> object returned with the result.
     * @return an array of the controls returned by an operation, or
     * null if none.
     * @see org.ietf.ldap.LDAPControl
     * @see org.ietf.ldap.LDAPSearchResults#getResponseControls
     */
    public LDAPControl[] getResponseControls() {
      LDAPControl[] controls = null;

      /* Get the latest controls returned for our thread */
      synchronized(_responseControlTable) {
          Vector responses = (Vector)_responseControlTable.get(_thread);

          if (responses != null) {
              // iterate through each response control
              for (int i=0,size=responses.size(); i<size; i++) {
                  LDAPResponseControl responseObj =
                    (LDAPResponseControl)responses.elementAt(i);

                  // check if the response belongs to this connection
                  if (responseObj.getConnection().equals(this)) {
                      controls = responseObj.getControls();
                      responses.removeElementAt(i);
                      break;
                  }
              }
          }
      }
      
      return controls;
    }

    /**
     * Returns an array of the latest controls associated with the 
     * particular request. Used internally by LDAPSearchResults to
     * get response controls returned for a search request.
     * <P>
     * @param msdid Message ID
     */
    LDAPControl[] getResponseControls(int msgID) {
      LDAPControl[] controls = null;

      /* Get the latest controls returned for our thread */
      synchronized(_responseControlTable) {
          Vector responses = (Vector)_responseControlTable.get(_thread);

          if (responses != null) {
              // iterate through each response control
              for (int i=0,size=responses.size(); i<size; i++) {
                  LDAPResponseControl responseObj =
                    (LDAPResponseControl)responses.elementAt(i);

                  // check if the response matches msgID
                  if (responseObj.getMsgID() == msgID) {
                      controls = responseObj.getControls();
                      responses.removeElementAt(i);
                      break;
                  }
              }
          }
      }
      
      return controls;
    }

    /**
     * Returns the callback handler, if any, specified on binding with a 
     * SASL mechanism
     *
     * @return the callback handler, if any, specified on binding with a 
     * SASL mechanism
     */
    public CallbackHandler getSaslBindCallbackHandler() {
        return _saslCallbackHandler;
    }

    /**
     * Returns the properties, if any, specified on binding with a 
     * SASL mechanism
     *
     * @return the properties, if any, specified on binding with a 
     * SASL mechanism
     */
    public Map getSaslBindProperties() {
        return _securityProperties;
    }

    /**
     * Returns the set of search constraints that apply to all searches
     * performed through this connection (unless you specify a different
     * set of search constraints when calling the <CODE>search</CODE>
     * method). 
     * <P>
     *
     * Note that if you want to get individual constraints (rather than
     * getting the
     * entire set of constraints), call the <CODE>getOption</CODE> method.
     * <P>
     *
     * Typically, you might call the <CODE>getSearchConstraints</CODE> method
     * to create a slightly different set of search constraints
     * to apply to a particular search.
     * <P>
     *
     * For example, the following section of code changes the maximum number
     * of results to 10 for a specific search. Rather than construct a new
     * set of search constraints from scratch, the example gets the current
     * settings for the connections and just changes the setting for the
     * maximum results.
     * <P>
     *
     * Note that this change only applies to the searches performed with this
     * custom set of constraints.  All other searches performed through this
     * connection use the original set of search constraints.
     * <P>
     *
     * <PRE>
     * ...
     * LDAPSearchConstraints myOptions = ld.getSearchConstraints();
     * myOptions.setMaxResults( 10 );
     * String[] myAttrs = { "objectclass" };
     * LDAPSearchResults myResults = ld.search( "o=Ace Industry,c=US",
     *                                          LDAPConnection.SCOPE_SUB,
     *                                          "(objectclass=*)",
     *                                          myAttrs,
     *                                          false,
     *                                          myOptions );
     * ...
     * </PRE>
     *
     * @return a copy of the <CODE>LDAPSearchConstraints</CODE> object 
     * representing the set of search constraints that apply (by default) to 
     * all searches performed through this connection.
     * @see org.ietf.ldap.LDAPSearchConstraints
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)  
     */
    public LDAPSearchConstraints getSearchConstraints () {
        return (LDAPSearchConstraints)_defaultConstraints.clone();
    }

    /**
     * Gets the object representing the socket factory used to establish
     * a connection to the LDAP server.
     * <P>
     *
     * @return the object representing the socket factory used to
     * establish a connection to a server.
     * @see org.ietf.ldap.LDAPSocketFactory
     * @see org.ietf.ldap.LDAPSSLSocketFactory
     * @see org.ietf.ldap.LDAPConnection#setSocketFactory(org.ietf.ldap.LDAPSocketFactory)
     */
    public LDAPSocketFactory getSocketFactory () {
        return _factory;
    }

    /**
     * Indicates whether this client has authenticated to the LDAP server
     * (other than anonymously with simple bind)
     *
     * @return <CODE>false</CODE> initially, <CODE>false</CODE> upon a bind
     * request, and <CODE>true</CODE> after successful completion of the last
     * outstanding non-anonymous simple bind
     */
    public boolean isBound() {
        if (_bound) {
            if ((_boundDN == null) || _boundDN.equals("") ||
                (_boundPasswd == null) || (_boundPasswd.length < 1)) {
                return false;
            }
        }
        return _bound;
    }

    /**
     * Indicates if the connection represented by this object
     * is open at this time
     *
     * @return <CODE>true</CODE> if connected to an LDAP server over this
     * connection.
     * If not connected to an LDAP server, returns <CODE>false</CODE>.
     */
    public boolean isConnected() {
        // This is the hack: If the user program calls isConnected() when
        // the thread is about to shut down, the isConnected might get called
        // before the deregisterConnection(). We add the yield() so that 
        // the deregisterConnection() will get called first. 
        // This problem only exists on Solaris.
        Thread.yield();
        return (_thread != null);
    }

    /**
     * Indicates if the connection is currently protected by TLS
     *
     * @return <CODE>true</CODE> if the connection is currently protected
     * by TLS; if not connected to an LDAP server, returns <CODE>false</CODE>.
     */
    public boolean isTLS() {
        return false;
    }

    /**
     * Makes a single change to an existing entry in the directory
     * (for example, changes the value of an attribute, adds a new
     * attribute value, or removes an existing attribute value). <P>
     *
     * Use the <CODE>LDAPModification</CODE> object to specify the change
     * to make and the <CODE>LDAPAttribute</CODE> object
     * to specify the attribute value to change. The
     * <CODE>LDAPModification</CODE> object allows you add an attribute
     * value, change an attibute value, or remove an attribute
     * value. <P>
     *
     * For example, the following section of code changes Barbara Jensen's email
     * address in the directory to babs@aceindustry.com. <P>
     *
     * <PRE>
     * ...
     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     *
     * LDAPAttribute attrEmail = new LDAPAttribute( "mail", "babs@aceindustry.com" );
     * LDAPModification singleChange = new LDAPModification( LDAPModification.REPLACE, attrEmail );
     *
     * myConn.modify( myEntryDN, singleChange );
     * ... </PRE>
     *
     * @param DN the distinguished name of the entry to modify
     * @param mod a single change to make to the entry
     * @exception LDAPException Failed to make the specified change to the
     * directory entry.
     * @see org.ietf.ldap.LDAPModification
     */
    public void modify( String DN, LDAPModification mod ) throws LDAPException {
        modify( DN, mod, _defaultConstraints );
    }

   /**
    * Makes a single change to an existing entry in the directory and
    * allows you to specify preferences for this LDAP modify operation
    * by using an <CODE>LDAPConstraints</CODE> object. For
    * example, you can specify whether or not to follow referrals.
    * You can also apply LDAP v3 controls to the operation.
    * <P>
    *
    * @param DN the distinguished name of the entry to modify
    * @param mod a single change to make to the entry
    * @param cons the set of preferences to apply to this operation
    * @exception LDAPException Failed to make the specified change to the
    * directory entry.
    * @see org.ietf.ldap.LDAPModification
    * @see org.ietf.ldap.LDAPConstraints
    */
    public void modify( String DN, LDAPModification mod,
                        LDAPConstraints cons ) throws LDAPException {
        LDAPModification[] mods = { mod };
        modify( DN, mods, cons );
    }

    /**
     * Makes a set of changes to an existing entry in the directory
     * (for example, changes attribute values, adds new attribute values,
     * or removes existing attribute values). <P>
     *
     * Use an array of <CODE>LDAPModification</CODE> objects to specify the
     * changes to make.  Each change must be specified by
     * an <CODE>LDAPModification</CODE> object, and you must specify each 
     * attribute value to modify, add, or remove by an <CODE>LDAPAttribute</CODE> 
     * object. <P>
     *
     * @param DN the distinguished name of the entry to modify
     * @param mods an array of objects representing the changes to make
     * to the entry
     * @exception LDAPException Failed to make the specified changes to the
     * directory entry.
     * @see org.ietf.ldap.LDAPModification
     */
    public void modify( String DN, LDAPModification[] mods )
        throws LDAPException {
        modify( DN, mods, _defaultConstraints );
    }

    /**
     * Makes a set of changes to an existing entry in the directory and
     * allows you to specify preferences for this LDAP modify operation
     * by using an <CODE>LDAPConstraints</CODE> object. For
     * example, you can specify whether or not to follow referrals.
     * You can also apply LDAP v3 controls to the operation.
     * <P>
     *
     * @param DN the distinguished name of the entry to modify
     * @param mods an array of objects representing the changes to make
     * to the entry
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to make the specified changes to the
     * directory entry.
     * @see org.ietf.ldap.LDAPModification
     * @see org.ietf.ldap.LDAPConstraints
     */
    public void modify( String DN, LDAPModification[] mods,
                        LDAPConstraints cons ) throws LDAPException {
         internalBind (cons);

         LDAPResponseQueue myListener = getResponseListener ();
         LDAPMessage response = null;
         try {
             sendRequest (new JDAPModifyRequest (DN, mods), myListener, cons);
             response = myListener.getResponse();
             checkMsg (response);
         } catch (LDAPReferralException e) {
             performReferrals(e, cons, JDAPProtocolOp.MODIFY_REQUEST,
                              DN, 0, null, null, false, mods, null, null, null);
         } finally {
             releaseResponseListener (myListener);
         }
    }

    /**
     * Makes a single change to an existing entry in the directory. For
     * example, it changes the value of an attribute, adds a new attribute
     * value, or removes an existing attribute value). <BR>
     * The LDAPModification object specifies both the change to make and
     * the LDAPAttribute value to be changed.
     * 
     * @param dn distinguished name of the entry to modify
     * @param mod a single change to make to an entry
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPModification
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue modify( String dn,
                                     LDAPModification mod,
                                     LDAPResponseQueue listener )
        throws LDAPException{

        return modify( dn, mod, listener, _defaultConstraints );
    }
    
    /**
     * Makes a single change to an existing entry in the directory. For
     * example, it changes the value of an attribute, adds a new attribute
     * value, or removes an existing attribute value). <BR>
     * The LDAPModification object specifies both the change to make and
     * the LDAPAttribute value to be changed.
     * 
     * @param dn distinguished name of the entry to modify
     * @param mod a single change to make to an entry
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPModification
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue modify( String dn,
                                     LDAPModification mod,
                                     LDAPResponseQueue listener,
                                     LDAPConstraints cons )
        throws LDAPException{
        if (cons == null) {
            cons = _defaultConstraints;
        }

        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        LDAPModification[] modList = { mod };
        sendRequest (new JDAPModifyRequest (dn, modList), listener, cons);        

        return listener;
    }

    /**
     * Reads the entry for the specified distiguished name (DN) and retrieves
     * all attributes for the entry.
     * <P>
     *
     * For example, the following section of code reads the entry for
     * Barbara Jensen and retrieves all attributes for that entry.
     * <P>
     *
     * <PRE>
     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * LDAPEntry foundEntry = null;
     * try {
     *     foundEntry = myConn.read( findDN );
     * } catch ( LDAPException e ) {
     *     switch( e.getResultCode() ) {
     *         case e.NO_SUCH_OBJECT:
     *             System.out.println( "The specified entry does not exist." );
     *             break;
     *         case e.LDAP_PARTIAL_RESULTS:
     *             System.out.println( "Entry served by a different LDAP server." );
     *             break;
     *         case e.INSUFFICIENT_ACCESS_RIGHTS:
     *             System.out.println( "You do not have the access rights to perform this operation." );
     *             break;
     *         default:
     *             System.out.println( "Error number: " + e.getResultCode() );
     *             System.out.println( "Could not read the specified entry." );
     *             break;
     *     }
     *     return;
     * }
     * System.out.println( "Found the specified entry." );
     * </PRE>
     *
     * @param DN distinguished name of the entry  to retrieve
     * @exception LDAPException Failed to find or read the specified entry
     * from the directory.
     * @return LDAPEntry returns the specified entry or raises an exception
     * if the entry is not found.
     */
    public LDAPEntry read( String DN ) throws LDAPException {
        return read( DN, null, _defaultConstraints );
    }

    /**
     * Reads the entry for the specified distiguished name (DN) and retrieves all
     * attributes for the entry. This method allows the user to specify the
     * preferences for the read operation.
     * <P>
     *
     * For example, the following section of code reads the entry for
     * Barbara Jensen and retrieves all attributes for that entry.
     * <P>
     *
     * <PRE>
     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * LDAPEntry foundEntry = null;
     * try {
     *     foundEntry = myConn.read( findDN );
     * } catch ( LDAPException e ) {
     *     switch( e.getResultCode() ) {
     *         case e.NO_SUCH_OBJECT:
     *             System.out.println( "The specified entry does not exist." );
     *             break;
     *         case e.LDAP_PARTIAL_RESULTS:
     *             System.out.println( "Entry served by a different LDAP server." );
     *             break;
     *         case e.INSUFFICIENT_ACCESS_RIGHTS:
     *             System.out.println( "You do not have the access rights to perform this operation." );
     *             break;
     *         default:
     *             System.out.println( "Error number: " + e.getResultCode() );
     *             System.out.println( "Could not read the specified entry." );
     *             break;
     *     }
     *     return;
     * }
     * System.out.println( "Found the specified entry." );
     * </PRE>
     *
     * @param DN distinguished name of the entry to retrieve
     * @param cons preferences for the read operation
     * @exception LDAPException Failed to find or read the specified entry
     * from the directory.
     * @return LDAPEntry returns the specified entry or raises an exception
     * if the entry is not found.
     */
    public LDAPEntry read( String DN, LDAPSearchConstraints cons )
        throws LDAPException {
        return read( DN, null, cons );
    }

    /**
     * Reads the entry for the specified distinguished name (DN) and
     * retrieves only the specified attributes from the entry.
     * <P>
     *
     * For example, the following section of code reads the entry for
     * Barbara Jensen and retrieves only the <CODE>cn</CODE> and
     * <CODE>sn</CODE> attributes.
     * The example prints out all attributes that have been retrieved
     * (the two specified attributes).
     * <P>
     *
     * <PRE>
     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * LDAPEntry foundEntry = null;
     * String getAttrs[] = { "cn", "sn" };
     * try {
     *      foundEntry = myConn.read( findDN, getAttrs );
     * } catch ( LDAPException e ) {
     *      switch( e.getResultCode() ) {
     *           case e.NO_SUCH_OBJECT:
     *               System.out.println( "The specified entry does not exist." );
     *               break;
     *           case e.LDAP_PARTIAL_RESULTS:
     *               System.out.println( "Entry served by a different LDAP server." );
     *               break;
     *           case e.INSUFFICIENT_ACCESS_RIGHTS:
     *               System.out.println( "You do not have the access " +
     *                                   "rights to perform this operation." );
     *               break;
     *           default:
     *               System.out.println( "Error number: " + e.getResultCode() );
     *               System.out.println( "Could not read the specified entry." );
     *               break;
     *      }
     *      return;
     * }
     *
     * LDAPAttributeSet foundAttrs = foundEntry.getAttributeSet();
     * int size = foundAttrs.size();
     * Iterator enumAttrs = foundAttrs.iterator();
     * System.out.println( "Attributes: " );
     *
     * while ( enumAttrs.hasMore() ) {
     *      LDAPAttribute anAttr = ( LDAPAttribute )enumAttrs.next();
     *      String attrName = anAttr.getName();
     *      System.out.println( "\t" + attrName );
     *      Enumeration enumVals = anAttr.getStringValues();
     *      while ( enumVals.hasMoreElements() ) {
     *           String aVal = ( String )enumVals.nextElement();
     *           System.out.println( "\t\t" + aVal );
     *      }
     * }
     * </PRE>
     *
     * @param DN distinguished name of the entry to retrieve
     * @param attrs names of attributes to retrieve
     * @return LDAPEntry returns the specified entry (or raises an
     * exception if the entry is not found).
     * @exception LDAPException Failed to read the specified entry from
     * the directory.
     */
    public LDAPEntry read( String DN, String attrs[] ) throws LDAPException {
        return read( DN, attrs, _defaultConstraints );
    }

    /**
     * Reads the entry for the specified distinguished name (DN) and
     * retrieves only the specified attributes from the entry.
     * <P>
     *
     * For example, the following section of code reads the entry for
     * Barbara Jensen and retrieves only the <CODE>cn</CODE> and
     * <CODE>sn</CODE> attributes.
     * The example prints out all attributes that have been retrieved
     * (the two specified attributes).
     * <P>
     *
     * <PRE>
     * String findDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * LDAPEntry foundEntry = null;
     * String getAttrs[] = { "cn", "sn" };
     * try {
     *      foundEntry = myConn.read( findDN, getAttrs );
     * } catch ( LDAPException e ) {
     *      switch( e.getResultCode() ) {
     *           case e.NO_SUCH_OBJECT:
     *               System.out.println( "The specified entry does not exist." );
     *               break;
     *           case e.LDAP_PARTIAL_RESULTS:
     *               System.out.println( "Entry served by a different LDAP server." );
     *               break;
     *           case e.INSUFFICIENT_ACCESS_RIGHTS:
     *               System.out.println( "You do not have the access " +
     *                                   "rights to perform this operation." );
     *               break;
     *           default:
     *               System.out.println( "Error number: " + e.getResultCode() );
     *               System.out.println( "Could not read the specified entry." );
     *               break;
     *      }
     *      return;
     * }
     *
     * LDAPAttributeSet foundAttrs = foundEntry.getAttributeSet();
     * int size = foundAttrs.size();
     * Iterator enumAttrs = foundAttrs.iterator();
     * System.out.println( "Attributes: " );
     *
     * while ( enumAttrs.hasMore() ) {
     *      LDAPAttribute anAttr = ( LDAPAttribute )enumAttrs.next();
     *      String attrName = anAttr.getName();
     *      System.out.println( "\t" + attrName );
     *      Enumeration enumVals = anAttr.getStringValues();
     *      while ( enumVals.hasMoreElements() ) {
     *           String aVal = ( String )enumVals.nextElement();
     *           System.out.println( "\t\t" + aVal );
     *      }
     * }
     * </PRE>
     *
     * @param DN distinguished name of the entry to retrieve
     * @param attrs names of attributes to retrieve
     * @param cons preferences for the read operation
     * @return LDAPEntry returns the specified entry (or raises an
     * exception if the entry is not found).
     * @exception LDAPException Failed to read the specified entry from
     * the directory.
     */
    public LDAPEntry read( String DN, String attrs[],
                           LDAPSearchConstraints cons ) throws LDAPException {
        LDAPSearchResults results =
            search (DN, SCOPE_BASE,
                    "(|(objectclass=*)(objectclass=ldapsubentry))",
                    attrs, false, cons);
        if ( results == null ) {
            return null;
        }
        LDAPEntry entry = results.next();
        
        // cleanup required for referral connections
        while( results.hasMore() ) {
            results.next();
        }
        
        return entry;
    }

    /**
     * Reads the entry specified by the LDAP URL. <P>
     *
     * When you call this method, a new connection is created automatically,
     * using the host and port specified in the URL. After finding the entry,
     * the method closes this connection (in other words, it disconnects from
     * the LDAP server). <P>
     *
     * If the URL specifies a filter and scope, these are not used.
     * Of the information specified in the URL, this method only uses
     * the LDAP host name and port number, the base distinguished name (DN),
     * and the list of attributes to return. <P>
     *
     * The method returns the entry specified by the base DN. <P>
     *
     * (Note: If you want to search for more than one entry, use the
     * <CODE>search( LDAPUrl )</CODE> method instead.) <P>
     *
     * For example, the following section of code reads the entry specified
     * by the LDAP URL.
     * <P>
     *
     * <PRE>
     * String flatURL = "ldap://alway.mcom.com:3890/cn=Barbara Jenson,ou=Product Development,o=Ace Industry,c=US?cn,sn,mail";
     * LDAPUrl myURL;
     * try {
     *    myURL = new LDAPUrl( flatURL );
     * } catch ( java.net.MalformedURLException e ) {
     *    System.out.println( "BAD URL!!!  BAD, BAD, BAD URL!!!" );
     *    return;
     * }
     * LDAPEntry myEntry = null;
     * try {
     *    myEntry = myConn.read( myURL );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    switch( errCode ) {
     *        case ( e.NO_SUCH_OBJECT ):
     *            System.out.println( "The specified entry " + myDN +
     *                                " does not exist in the directory." );
     *            return;
     *        default:
     *            System.out.println( "An internal error occurred." );
     *            return;
     *    }
     * }
     * </PRE>
     *
     * @param toGet LDAP URL specifying the entry to read
     * @return LDAPEntry returns the entry specified by the URL (or raises
     * an exception if the entry is not found).
     * @exception LDAPException Failed to read the specified entry from
     * the directory.
     * @see org.ietf.ldap.LDAPUrl
     * @see org.ietf.ldap.LDAPConnection#search(org.ietf.ldap.LDAPUrl)
     */
    public static LDAPEntry read( LDAPUrl toGet ) throws LDAPException {
        return read( toGet, null );
    }

    /**
     * Reads the entry specified by the LDAP URL. <P>
     *
     * When you call this method, a new connection is created automatically,
     * using the host and port specified in the URL. After finding the entry,
     * the method closes this connection (in other words, it disconnects from
     * the LDAP server). <P>
     *
     * If the URL specifies a filter and scope, these are not used.
     * Of the information specified in the URL, this method only uses
     * the LDAP host name and port number, the base distinguished name (DN),
     * and the list of attributes to return. <P>
     *
     * The method returns the entry specified by the base DN. <P>
     *
     * (Note: If you want to search for more than one entry, use the
     * <CODE>search( LDAPUrl )</CODE> method instead.) <P>
     *
     * For example, the following section of code reads the entry specified
     * by the LDAP URL.
     * <P>
     *
     * <PRE>
     * String flatURL = "ldap://alway.mcom.com:3890/cn=Barbara Jenson,ou=Product Development,o=Ace Industry,c=US?cn,sn,mail";
     * LDAPUrl myURL;
     * try {
     *    myURL = new LDAPUrl( flatURL );
     * } catch ( java.net.MalformedURLException e ) {
     *    System.out.println( "BAD URL!!!  BAD, BAD, BAD URL!!!" );
     *    return;
     * }
     * LDAPEntry myEntry = null;
     * try {
     *    myEntry = myConn.read( myURL );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    switch( errCode ) {
     *        case ( e.NO_SUCH_OBJECT ):
     *            System.out.println( "The specified entry " + myDN +
     *                                " does not exist in the directory." );
     *            return;
     *        default:
     *            System.out.println( "An internal error occurred." );
     *            return;
     *    }
     * }
     * </PRE>
     *
     * @param toGet LDAP URL specifying the entry to read
     * @param cons preferences for the read operation
     * @return LDAPEntry returns the entry specified by the URL (or raises
     * an exception if the entry is not found).
     * @exception LDAPException Failed to read the specified entry from
     * the directory.
     * @see org.ietf.ldap.LDAPUrl
     * @see org.ietf.ldap.LDAPConnection#search(org.ietf.ldap.LDAPUrl)
     */
    public static LDAPEntry read( LDAPUrl toGet,
                                  LDAPSearchConstraints cons )
        throws LDAPException {
        if (cons == null) {
            cons = new LDAPSearchConstraints();
        }
        String host = toGet.getHost ();
        int port = toGet.getPort();

        if (host == null) {
            throw new LDAPException ( "no host for connection",
                                    LDAPException.PARAM_ERROR );
        }

        String[] attributes = toGet.getAttributeArray ();
        String DN = toGet.getDN();
        LDAPEntry returnValue;

        LDAPConnection connection = new LDAPConnection ();
        if (toGet.isSecure()) {
            LDAPSocketFactory factory = toGet.getSocketFactory();
            if (factory == null) {
                throw new LDAPException("No socket factory for LDAPUrl",
                                         LDAPException.OTHER);
            }
            connection.setSocketFactory(factory);
        }
        connection.connect (host, port);

        returnValue = connection.read (DN, attributes, cons);
        connection.disconnect ();

        return returnValue;
    }

    /**
     * Disconnect from the server and then reconnect using the current
     * credentials and authentication method
     * @exception LDAPException if not previously connected, or if
     * there is a failure on disconnecting or on connecting 
     */
    public void reconnect() throws LDAPException {
        
        disconnect();
        connect();
        
        if (_saslBinder != null) {
            _saslBinder.bind(this, true);
            _authMethod = "sasl";
        } else {
            internalBind (_protocolVersion, true, _defaultConstraints);
        }
    }

    /**
     * Deregisters an object so that it will no longer be notified on 
     * arrival of an unsolicited message from a server. If the object is 
     * null or was not previously registered for unsolicited notifications, 
     * the method does nothing.
     */
    public void removeUnsolicitedNotificationListener(
        LDAPUnsolicitedNotificationListener listener ) {
    }

    /**
     * Renames an existing entry in the directory. <P>
     *
     * You can specify whether or not the original name of the entry is
     * retained as a value in the entry. For example, suppose you rename
     * the entry "cn=Barbara" to "cn=Babs".  You can keep "cn=Barbara"
     * as a value in the entry so that the cn attribute has two values: <P>
     *
     * <PRE>
     *       cn=Barbara
     *       cn=Babs
     * </PRE>
     * The following example renames an entry.  The old name of the entry
     * is kept as a value in the entry. <P>
     *
     * <PRE>
     * ...
     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * String newRDN = "cn=Babs Jensen";
     * myConn.rename( myEntryDN, newRDN, false );
     * ... </PRE>
     *
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry (for example,
     * "cn=newName")
     * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
     * as an attribute value (for example, the attribute value "cn=oldName" is
     * removed).  If <CODE>false</CODE>, the old name is retained
     * as an attribute value (for example, the entry might now have two values
     * for the cn attribute: "cn=oldName" and "cn=newName").
     * @exception LDAPException Failed to rename the specified entry.
     */
    public void rename( String DN, String newRDN, boolean deleteOldRDN )
        throws LDAPException {
        rename( DN, newRDN, null, deleteOldRDN );
    }

    /**
     * Renames an existing entry in the directory. <P>
     *
     * You can specify whether or not the original name of the entry is
     * retained as a value in the entry. For example, suppose you rename
     * the entry "cn=Barbara" to "cn=Babs".  You can keep "cn=Barbara"
     * as a value in the entry so that the cn attribute has two values: <P>
     *
     * <PRE>
     *       cn=Barbara
     *       cn=Babs
     * </PRE>
     * The following example renames an entry.  The old name of the entry
     * is kept as a value in the entry. <P>
     *
     * <PRE>
     * ...
     * String myEntryDN = "cn=Barbara Jensen,ou=Product Development,o=Ace Industry,c=US";
     * String newRDN = "cn=Babs Jensen";
     * myConn.rename( myEntryDN, newRDN, false );
     * ... </PRE>
     *
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry (for example,
     * "cn=newName")
     * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
     * as an attribute value (for example, the attribute value "cn=oldName" is
     * removed).  If <CODE>false</CODE>, the old name is retained
     * as an attribute value (for example, the entry might now have two values
     * for the cn attribute: "cn=oldName" and "cn=newName").
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to rename the specified entry.
     */
    public void rename( String DN, String newRDN, boolean deleteOldRDN,
                        LDAPConstraints cons )
        throws LDAPException {
        rename( DN, newRDN, null, deleteOldRDN, cons );
    }

    /**
     * Renames an existing entry in the directory and (optionally)
     * changes the location of the entry in the directory tree.<P>
     *
     * <B>NOTE: </B>Netscape Directory Server 3.0 does not support the
     * capability to move an entry to a different location in the
     * directory tree.  If you specify a value for the <CODE>newParentDN</CODE>
     * argument, an <CODE>LDAPException</CODE> will be thrown.
     * <P>
     *
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry (for example,
     * "cn=newName")
     * @param newParentDN if not null, the distinguished name for the
     * entry under which the entry should be moved (for example, to move
     * an entry under the Accounting subtree, specify this argument as
     * "ou=Accounting, o=Ace Industry, c=US")
     * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
     * as an attribute value (for example, the attribute value "cn=oldName" is
     * removed).  If <CODE>false</CODE>, the old name is retained
     * as an attribute value (for example, the entry might now have two values
     * for the cn attribute: "cn=oldName" and "cn=newName").
     * @exception LDAPException Failed to rename the specified entry.
     */
     public void rename( String DN,
                         String newRDN,
                         String newParentDN,
                         boolean deleteOldRDN ) throws LDAPException {
          rename( DN, newRDN, newParentDN, deleteOldRDN, _defaultConstraints );
     }

    /**
     * Renames an existing entry in the directory and (optionally)
     * changes the location of the entry in the directory tree. Also
     * allows you to specify preferences for this LDAP modify DN operation
     * by using an <CODE>LDAPConstraints</CODE> object. For
     * example, you can specify whether or not to follow referrals.
     * You can also apply LDAP v3 controls to the operation.
     * <P>
     *
     * <B>NOTE: </B>Netscape Directory Server 3.0 does not support the
     * capability to move an entry to a different location in the
     * directory tree.  If you specify a value for the <CODE>newParentDN</CODE>
     * argument, an <CODE>LDAPException</CODE> will be thrown.
     * <P>
     *
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry (for example,
     * "cn=newName")
     * @param newParentDN if not null, the distinguished name for the
     * entry under which the entry should be moved (for example, to move
     * an entry under the Accounting subtree, specify this argument as
     * "ou=Accounting, o=Ace Industry, c=US")
     * @param deleteOldRDN if <CODE>true</CODE>, the old name is not retained
     * as an attribute value (for example, the attribute value "cn=oldName" is
     * removed).  If <CODE>false</CODE>, the old name is retained
     * as an attribute value (for example, the entry might now have two values
     * for the cn attribute: "cn=oldName" and "cn=newName").
     * @param cons the set of preferences to apply to this operation
     * @exception LDAPException Failed to rename the specified entry.
     * @see org.ietf.ldap.LDAPConstraints
     */
    public void rename ( String DN,
                         String newRDN,
                         String newParentDN,
                         boolean deleteOldRDN,
                         LDAPConstraints cons )
        throws LDAPException {
        internalBind (cons);

        LDAPResponseQueue myListener = getResponseListener ();
        try {
            JDAPModifyRDNRequest request = null;
            if ( newParentDN != null ) {
                request = new JDAPModifyRDNRequest( DN,
                                                    newRDN,
                                                    deleteOldRDN,
                                                    newParentDN );
            } else {
                request = new JDAPModifyRDNRequest( DN,
                                                    newRDN,
                                                    deleteOldRDN );
            }
            sendRequest (request, myListener, cons);
            LDAPMessage response = myListener.getResponse();
            checkMsg (response);
        } catch (LDAPReferralException e) {
            performReferrals(e, cons, JDAPProtocolOp.MODIFY_RDN_REQUEST,
                             DN, 0, newRDN, null, deleteOldRDN, null, null,
                             null, null);
        } finally {
            releaseResponseListener (myListener);
        }
    }

    /**
     * Renames an existing entry in the directory.
     * 
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry
     * @param deleteOldRDN if true, the old name is not retained as an
     * attribute value
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue rename( String DN,
                                     String newRDN,
                                     boolean deleteOldRDN,
                                     LDAPResponseQueue listener )
        throws LDAPException{
        return rename( DN, newRDN, deleteOldRDN, listener,
                       _defaultConstraints );
    }

    /**
     * Renames an existing entry in the directory.
     * 
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry
     * @param deleteOldRDN if true, the old name is not retained as an attribute
     * value
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to the operation
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     * @see org.ietf.ldap.LDAPConstraints
     */
    public LDAPResponseQueue rename( String DN,
                                     String newRDN,
                                     boolean deleteOldRDN,
                                     LDAPResponseQueue listener,
                                     LDAPConstraints cons )
        throws LDAPException{
        if (cons == null) {
            cons = _defaultConstraints;
        }
        
        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        sendRequest (new JDAPModifyRDNRequest (DN, newRDN, deleteOldRDN),
                     listener, cons);
        
        return listener;
    }
        
    /**
     * Renames an existing entry in the directory.
     * 
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry
     * @param newParentDN if not null, the distinguished name for the
     * entry under which the entry should be moved (for example, to move
     * an entry under the Accounting subtree, specify this argument as
     * "ou=Accounting, o=Ace Industry, c=US")
     * @param deleteOldRDN if true, the old name is not retained as an
     * attribute value
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue rename( String DN,
                                     String newRDN,
                                     String newParentDN,
                                     boolean deleteOldRDN,
                                     LDAPResponseQueue listener )
        throws LDAPException{
        return rename( DN, newRDN, newParentDN, deleteOldRDN, listener,
                       _defaultConstraints );
    }

    /**
     * Renames an existing entry in the directory.
     * 
     * @param DN current distinguished name of the entry
     * @param newRDN new relative distinguished name for the entry
     * @param newParentDN if not null, the distinguished name for the
     * entry under which the entry should be moved (for example, to move
     * an entry under the Accounting subtree, specify this argument as
     * "ou=Accounting, o=Ace Industry, c=US")
     * @param deleteOldRDN if true, the old name is not retained as an
     * attribute value
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPResponseQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPResponseQueue
     */
    public LDAPResponseQueue rename( String DN,
                                     String newRDN,
                                     String newParentDN,
                                     boolean deleteOldRDN,
                                     LDAPResponseQueue listener,
                                     LDAPConstraints cons )
        throws LDAPException{
        if (cons == null) {
            cons = _defaultConstraints;
        }
        
        internalBind (cons);

        if (listener == null) {
            listener = new LDAPResponseQueue(/*asynchOp=*/true);
        }

        JDAPModifyRDNRequest request;
        if ( newParentDN != null ) {
            request = new JDAPModifyRDNRequest( DN,
                                                newRDN,
                                                deleteOldRDN,
                                                newParentDN );
        } else {
            request = new JDAPModifyRDNRequest( DN,
                                                newRDN,
                                                deleteOldRDN );
        }
        sendRequest( request, listener, cons );
        
        return listener;
    }

    /**
     * Performs the search specified by the LDAP URL. <P>
     *
     * For example, the following section of code searches for all entries under
     * the <CODE>ou=Product Development,o=Ace Industry,c=US</CODE> subtree of a
     * directory.  The example gets and prints the mail attribute for each entry
     * found. <P>
     *
     * <PRE>
     * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
     * LDAPUrl myURL;
     * try {
     *    myURL = new LDAPUrl( flatURL );
     * } catch ( java.net.MalformedURLException e ) {
     *    System.out.println( "Incorrect URL syntax." );
     *    return;
     * }
     *
     * LDAPSearchResults myResults = null;
     * try {
     *    myResults = myConn.search( myURL );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    System.out.println( "LDAPException: return code:" + errCode );
     *    return;
     * }
     *
     * while ( myResults.hasMore() ) {
     *    LDAPEntry myEntry = myResults.next();
     *    String nextDN = myEntry.getDN();
     *    System.out.println( nextDN );
     *    LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
     *    Iterator attrsInSet = entryAttrs.iterator();
     *    while ( attrsInSet.hasMore() ) {
     *        LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.next();
     *        String attrName = nextAttr.getName();
     *        System.out.print( "\t" + attrName + ": " );
     *        Enumeration valsInAttr = nextAttr.getStringValues();
     *        while ( valsInAttr.hasMoreElements() ) {
     *            String nextValue = (String)valsInAttr.nextElement();
     *            System.out.println( nextValue );
     *        }
     *    }
     * }
     * </PRE>
     * <P>
     *
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param toGet LDAP URL representing the search to perform
     * @return LDAPSearchResults the results of the search as an enumeration.
     * @exception LDAPException Failed to complete the search specified by
     * the LDAP URL.
     * @see org.ietf.ldap.LDAPUrl
     * @see org.ietf.ldap.LDAPSearchResults
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
     */
    public static LDAPSearchResults search( LDAPUrl toGet )
        throws LDAPException {
        return search( toGet, null );
    }

    /**
     * Performs the search specified by the LDAP URL. This method also
     * allows you to specify constraints for the search (such as the
     * maximum number of entries to find or the
     * maximum time to wait for search results). <P>
     *
     * As part of the search constraints, you can specify whether or not you
     * want the results delivered all at once or in smaller batches.
     * If you specify the results delivered in smaller
     * batches, each iteration blocks until the next batch of results is
     * returned. <P>
     *
     * For example, the following section of code retrieves the first 5
     * matching entries for the search specified by the LDAP URL.  The
     * example accomplishes this by creating a new set of search
     * constraints where the maximum number of search results is 5. <P>
     *
     * <PRE>
     * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
     * mySearchConstraints.setMaxResults( 5 );
     * String flatURL = "ldap://alway.mcom.com:3890/ou=Product Development,o=Ace Industry,c=US?mail?sub?objectclass=*";
     * LDAPUrl myURL;
     * try {
     *    myURL = new LDAPUrl( flatURL );
     * } catch ( java.net.MalformedURLException e ) {
     *    System.out.println( "Incorrect URL syntax." );
     *    return;
     * }
     * LDAPSearchResults myResults = null;
     * try {
     *    myResults = myConn.search( myURL, mySearchConstraints );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    System.out.println( "LDAPException: return code:" + errCode );
     *    return;
     * }
     * </PRE>
     * <P>
     *
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param toGet LDAP URL representing the search to run
     * @param cons constraints specific to the search
     * @return LDAPSearchResults the results of the search as an enumeration.
     * @exception LDAPException Failed to complete the search specified
     * by the LDAP URL.
     * @see org.ietf.ldap.LDAPUrl
     * @see org.ietf.ldap.LDAPSearchResults
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
     */
    public static LDAPSearchResults search( LDAPUrl toGet,
                                            LDAPSearchConstraints cons )
        throws LDAPException {
        String host = toGet.getHost ();
        int port = toGet.getPort();

        if (host == null) {
            throw new LDAPException ( "no host for connection",
                                    LDAPException.PARAM_ERROR );
        }

        String[] attributes = toGet.getAttributeArray ();
        String DN = toGet.getDN();
        String filter = toGet.getFilter();
        if (filter == null) {
            filter = defaultFilter;
        }
        int scope = toGet.getScope ();

        LDAPConnection connection = new LDAPConnection ();
        if (toGet.isSecure()) {
            LDAPSocketFactory factory = toGet.getSocketFactory();
            if (factory == null) {
                throw new LDAPException("No socket factory for LDAPUrl",
                                         LDAPException.OTHER);
            }
            connection.setSocketFactory(factory);
        }        
        connection.connect (host, port);

        LDAPSearchResults results;
        if (cons != null) {
            results = connection.search (DN, scope, filter, attributes, false, cons);
        } else {
            results = connection.search (DN, scope, filter, attributes, false);
        }

        results.closeOnCompletion(connection);

        return results;
    }

    /**
     * Performs the search specified by the criteria that you enter. <P>
     *
     * For example, the following section of code searches for all entries under
     * the <CODE>ou=Product Development,o=Ace Industry,c=US</CODE> subtree of a
     * directory.  The example gets and prints the mail attribute for each entry
     * found. <P>
     *
     * <PRE>
     * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
     * String myFilter="(objectclass=*)";
     * String[] myAttrs = { "mail" };
     *
     * LDAPSearchResults myResults = null;
     * try {
     *    myResults = myConn.search( myBaseDN, LDAPConnection.SCOPE_SUB, myFilter, myAttrs, false );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    System.out.println( "LDAPException: return code:" + errCode );
     *    return;
     * }
     *
     * while ( myResults.hasMore() ) {
     *    LDAPEntry myEntry = myResults.next();
     *    String nextDN = myEntry.getDN();
     *    System.out.println( nextDN );
     *    LDAPAttributeSet entryAttrs = myEntry.getAttributeSet();
     *    Iterator attrsInSet = entryAttrs.iterator();
     *    while ( attrsInSet.hasMore() ) {
     *        LDAPAttribute nextAttr = (LDAPAttribute)attrsInSet.next();
     *        String attrName = nextAttr.getName();
     *        System.out.println( "\t" + attrName + ":" );
     *        Enumeration valsInAttr = nextAttr.getStringValues();
     *        while ( valsInAttr.hasMoreElements() ) {
     *            String nextValue = (String)valsInAttr.nextElement();
     *            System.out.println( "\t\t" + nextValue );
     *        }
     *    }
     * }
     * </PRE>
     * <P>
     *
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param base the base distinguished name from which to search
     * @param scope the scope of the entries to search.  You can specify one
     * of the following: <P>
     * <UL>
     * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
     * (search only entries under the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
     * (search the base DN and all entries within its subtree) <P>
     * </UL>
     * <P>
     * @param filter search filter specifying the search criteria
     * @param attrs list of attributes that you want returned in the
     * search results
     * @param attrsOnly if true, returns the names but not the values of the
     * attributes found.  If false, returns the names and values for
     * attributes found
     * @return LDAPSearchResults the results of the search as an enumeration.
     * @exception LDAPException Failed to complete the specified search.
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
     */
    public LDAPSearchResults search( String base,
                                     int scope,
                                     String filter,
                                     String[] attrs,
                                     boolean attrsOnly ) throws LDAPException {
        return search( base, scope, filter, attrs, attrsOnly,
                       _defaultConstraints );
    }

    /**
     * Performs the search specified by the criteria that you enter.
     * This method also allows you to specify constraints for the search
     * (such as the maximum number of entries to find or the
     * maximum time to wait for search results). <P>
     *
     * As part of the search constraints, you can specify whether or not
     * you want the
     * results delivered all at once or in smaller batches.  If you
     * specify that you want the results delivered in smaller batches,
     * each iteration blocks until the
     * next batch of results is returned. <P>
     *
     * For example, the following section of code retrieves the first 5 entries
     * matching the specified search criteria.  The example accomplishes
     * this by creating a new set of search constraints where the maximum
     * number of search results is 5. <P>
     *
     * <PRE>
     * String myBaseDN = "ou=Product Development,o=Ace Industry,c=US";
     * String myFilter="(objectclass=*)";
     * String[] myAttrs = { "mail" };
     * LDAPSearchConstraints mySearchConstraints = myConn.getSearchConstraints();
     * mySearchConstraints.setMaxResults( 5 );
     *
     * LDAPSearchResults myResults = null;
     * try {
     *    myResults = myConn.search( myBaseDN, LDAPConnection.SCOPE_SUB, myFilter, myAttrs, false, mySearchConstraints );
     * } catch ( LDAPException e ) {
     *    int errCode = e.getResultCode();
     *    System.out.println( "LDAPException: return code:" + errCode );
     *    return;
     * }
     * </PRE>
     * <P>
     *
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param base the base distinguished name from which to search
     * @param scope the scope of the entries to search.  You can specify one
     * of the following: <P>
     * <UL>
     * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
     * (search only entries under the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
     * (search the base DN and all entries within its subtree) <P>
     * </UL>
     * <P>
     * @param filter search filter specifying the search criteria
     * @param attrs list of attributes to return in the search
     * results
     * @param cons constraints specific to this search (for example, the
     * maximum number of entries to return)
     * @param attrsOnly if true, returns the names but not the values of the
     * attributes found.  If false, returns the names and  values for
     * attributes found
     * @return LDAPSearchResults the results of the search as an enumeration.
     * @exception LDAPException Failed to complete the specified search.
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchResults)
     */
    public LDAPSearchResults search( String base,
                                     int scope,
                                     String filter,
                                     String[] attrs,
                                     boolean attrsOnly,
                                     LDAPSearchConstraints cons )
        throws LDAPException {
        if (cons == null) {
            cons = _defaultConstraints;
        }

        LDAPSearchResults returnValue =
            new LDAPSearchResults( this, cons, base, scope, filter,
                                   attrs, attrsOnly );
        Vector cacheValue = null;
        Long key = null;
        boolean isKeyValid = true;

        try {
            // get entry from cache which is a vector of JDAPMessages
            if ( _cache != null ) {
                // create key for cache entry using search arguments
                key = _cache.createKey( getHost(), getPort(),base, filter,
                                        scope, attrs, _boundDN, cons );

                cacheValue = (Vector)_cache.getEntry(key);

                if ( cacheValue != null ) {
                    return new LDAPSearchResults(
                        cacheValue, this, cons, base, scope,
                        filter, attrs, attrsOnly );
                }
            }
        } catch ( LDAPException e ) {
            isKeyValid = false;
            printDebug("Exception: "+e);
        }

        internalBind( cons );

        LDAPSearchQueue myListener = getSearchListener( cons );
        int deref = cons.getDereference();

        JDAPSearchRequest request = null;        
        try {
            request = new JDAPSearchRequest( base, scope, deref,
                                             cons.getMaxResults(),
                                             cons.getServerTimeLimit(),
                                             attrsOnly, filter, attrs );
        } catch ( IllegalArgumentException e ) {
            throw new LDAPException(e.getMessage(), LDAPException.PARAM_ERROR);
        }

        // if using cache, then we need to set the key of the search listener
        if ( (_cache != null) && isKeyValid ) {
            myListener.setKey( key );
        }
        
        try {
            sendRequest( request, myListener, cons );
        }
        catch ( LDAPException e ) {
            releaseSearchListener( myListener );
            throw e;                    
        }

        /* Is this a persistent search? */
        boolean isPersistentSearch = false;
        LDAPControl[] controls =
            (LDAPControl[])getOption( SERVERCONTROLS, cons );
        for ( int i = 0; (controls != null) && (i < controls.length); i++ ) {
            if ( controls[i] instanceof
                 org.ietf.ldap.controls.LDAPPersistSearchControl ) {
                isPersistentSearch = true;
                break;
            }
        }

        /* For a persistent search, don't wait for a first result, because
           there may be none at this time if changesOnly was specified in
           the control.
        */
        if ( isPersistentSearch ) {
            returnValue.associatePersistentSearch (myListener);

        } else if ( cons.getBatchSize() == 0 ) {
            /* Synchronous search if all requested at once */
            try {
                /* Block until all results are in */
                LDAPMessage response = myListener.completeRequest();
                Iterator results = myListener.getAllMessages().iterator();

                checkSearchMsg(returnValue, response, cons, base, scope,
                               filter, attrs, attrsOnly);

                while ( results.hasNext() ) {
                    LDAPMessage msg = (LDAPMessage)results.next();
                    checkSearchMsg( returnValue, msg, cons, base, scope,
                                    filter, attrs, attrsOnly );
                }
            } finally {
                releaseSearchListener( myListener );
            }
        } else {
            /*
            * Asynchronous to retrieve one at a time, check to make sure
            * the search didn't fail
            */
            LDAPMessage firstResult = myListener.getResponse();
            if ( firstResult instanceof LDAPResponse ) {
                try {
                    checkSearchMsg( returnValue, firstResult, cons, base,
                                    scope, filter, attrs, attrsOnly );
                } finally {
                    releaseSearchListener( myListener );
                }
            } else {
                try {
                    checkSearchMsg( returnValue, firstResult, cons, base,
                                    scope, filter, attrs, attrsOnly );
                } catch ( LDAPException ex ) {
                    releaseSearchListener( myListener );
                    throw ex;
                }

                /* we let this listener get garbage collected.. */
                returnValue.associate( myListener );
            }
        }
        return returnValue;
    }

    /**
     * Performs the search specified by the criteria that you enter. <P>
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param base the base distinguished name from which to search
     * @param scope the scope of the entries to search.  You can specify one
     * of the following: <P>
     * <UL>
     * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
     * (search only entries under the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
     * (search the base DN and all entries within its subtree) <P>
     * </UL>
     * <P>
     * @param filter search filter specifying the search criteria
     * @param attrs list of attributes that you want returned in the
     * search results
     * @param typesOnly if true, returns the names but not the values of the
     * attributes found.  If false, returns the names and values for
     * attributes found
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @return LDAPSearchQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchQueue)
     */
    public LDAPSearchQueue search( String base,
                                   int scope,
                                   String filter,
                                   String attrs[],
                                   boolean typesOnly,
                                   LDAPSearchQueue listener )
        throws LDAPException {
        
        return search( base, scope, filter, attrs, typesOnly,
                       listener, _defaultConstraints );
    }

    /**
     * Performs the search specified by the criteria that you enter.
     * This method also allows you to specify constraints for the search
     * (such as the maximum number of entries to find or the
     * maximum time to wait for search results). <P>
     * To abandon the search, use the <CODE>abandon</CODE> method.
     *
     * @param base the base distinguished name from which to search
     * @param scope the scope of the entries to search.  You can specify one
     * of the following: <P>
     * <UL>
     * <LI><CODE>LDAPConnection.SCOPE_BASE</CODE> (search only the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_ONE</CODE>
     * (search only entries under the base DN) <P>
     * <LI><CODE>LDAPConnection.SCOPE_SUB</CODE>
     * (search the base DN and all entries within its subtree) <P>
     * </UL>
     * <P>
     * @param filter search filter specifying the search criteria
     * @param attrs list of attributes that you want returned in the search
     * results
     * @param typesOnly if true, returns the names but not the values of the
     * attributes found.  If false, returns the names and  values for
     * attributes found.
     * @param listener handler for messages returned from a server in response
     * to this request. If it is null, a listener object is created internally.
     * @param cons constraints specific to this search (for example, the
     * maximum number of entries to return)
     * @return LDAPSearchQueue handler for messages returned from a server
     * in response to this request.
     * @exception LDAPException Failed to send request.
     * @see org.ietf.ldap.LDAPConnection#abandon(org.ietf.ldap.LDAPSearchQueue)
     */
    public LDAPSearchQueue search( String base,
                                   int scope,
                                   String filter,
                                   String attrs[],
                                   boolean typesOnly,
                                   LDAPSearchQueue listener,
                                   LDAPSearchConstraints cons )
        throws LDAPException {
        if ( cons == null ) {
            cons = _defaultConstraints;
        }

        internalBind( cons );
        
        if ( listener == null ) {
            listener = new LDAPSearchQueue( /*asynchOp=*/true, cons );
        }
        
        JDAPSearchRequest request = null;        
        try {
            request = new JDAPSearchRequest( base, scope,
                                             cons.getDereference(),
                                             cons.getMaxResults(),
                                             cons.getServerTimeLimit(),
                                             typesOnly, filter, attrs );
        }
        catch ( IllegalArgumentException e ) {
            throw new LDAPException( e.getMessage(),
                                     LDAPException.PARAM_ERROR );
        }

        sendRequest( request, listener, cons );
        return listener;
        
    }
    
    /**
     *  Sets the specified <CODE>LDAPCache</CODE> object as the
     *  cache for the <CODE>LDAPConnection</CODE> object.
     *  <P>
     *
     *  @param cache the <CODE>LDAPCache</CODE> object representing
     *  the cache that the current connection should use
     *  @see org.ietf.ldap.LDAPCache
     *  @see org.ietf.ldap.LDAPConnection#getCache
     */
    public void setCache( LDAPCache cache ) {
        if ( _cache != null ) {
            _cache.removeReference();
        }
        if ( cache != null ) {
            cache.addReference();
        }
        _cache = cache;
        if ( _thread != null ) {
            _thread.setCache( cache );
        }
    }

    /**
     * Specifies the maximum time to wait for the connection to be established.
     * If the value is 0, the time is not limited.
     * @param timeout the maximum connect time in seconds or 0 (unlimited)
     */
    public void setConnectTimeout (int timeout) {
        if ( timeout < 0 ) {
            throw new IllegalArgumentException(
                "Timeout value can not be negative" );
        }
        _connectTimeout = timeout;
        if ( _connMgr != null ) {
            _connMgr.setConnectTimeout( _connectTimeout );
        }
    }
        
    /**
     * Specifies the delay in seconds when making concurrent connection attempts to
     * multiple servers.
     * <P>Effectively, selects the connection setup policy when a list of hosts is passed
     * to the <CODE>connect</CODE> method.
     * 
     * <br>If the serial policy is selected, the default one, an attempt is made to
     * connect to the first host in the list. The next entry in
     * the list is tried only if the attempt to connect to the current host fails.
     * This might cause your application to block for unacceptably long time if a host is down.
     *
     * <br>If the parallel policy is selected, multiple connection attempts may run
     * concurrently on a separate thread. A new connection attempt to the next entry
     * in the list can be started with or without delay.
     * <P>You must set the <CODE>ConnSetupDelay</CODE> before making the call to the 
     * <CODE>connect</CODE> method.
     * 
     * @param delay the delay in seconds between connection attempts. Possible values are:<br>
     * <CODE>NODELAY_SERIAL</CODE> Use the serial connection setup policy.<br>
     * <CODE>NODELAY_PARALLEL</CODE> Use the parallel connection setup policy with no delay.
     * Start all connection setup threads immediately.<br>
     * <CODE>delay > 0</CODE> Use the parallel connection setup policy with delay.
     * Start another connection setup thread after <CODE>delay</CODE> seconds.<br>
     * @see org.ietf.ldap.LDAPConnection#NODELAY_SERIAL
     * @see org.ietf.ldap.LDAPConnection#NODELAY_PARALLEL
     * @see org.ietf.ldap.LDAPConnection#connect(java.lang.String, int)
     */
    public void setConnSetupDelay( int delay ) {
        _connSetupDelay = delay;
        if ( _connMgr != null ) {
            _connMgr.setConnSetupDelay( delay );
        }
    }

    /**
     * Set the default constraint set for all operations. 
     * @param cons <CODE>LDAPConstraints</CODE> object to use as the default
     * constraint set
     * @see org.ietf.ldap.LDAPConnection#getConstraints
     * @see org.ietf.ldap.LDAPConstraints
     */
    public void setConstraints( LDAPConstraints cons ) {
        _defaultConstraints.setHopLimit( cons.getHopLimit() );
        _defaultConstraints.setReferralFollowing( cons.getReferralFollowing() );
        _defaultConstraints.setTimeLimit( cons.getTimeLimit() );
        _defaultConstraints.setReferralHandler( cons.getReferralHandler() );

        LDAPControl[] tServerControls = cons.getControls();
        LDAPControl[] oServerControls = null;
        if ( (tServerControls != null) && 
             (tServerControls.length > 0) ) {
            oServerControls =
                new LDAPControl[tServerControls.length];
            for( int i = 0; i < tServerControls.length; i++ ) {
                oServerControls[i] = (LDAPControl)tServerControls[i].clone();
            }
        }
        _defaultConstraints.setControls( oServerControls );

        if ( cons instanceof LDAPSearchConstraints ) {
            LDAPSearchConstraints scons = (LDAPSearchConstraints)cons;
            _defaultConstraints.setServerTimeLimit( scons.getServerTimeLimit() );
            _defaultConstraints.setDereference( scons.getDereference() );
            _defaultConstraints.setMaxResults( scons.getMaxResults() );
            _defaultConstraints.setBatchSize( scons.getBatchSize() );
            _defaultConstraints.setMaxBacklog( scons.getMaxBacklog() );
        }
    }
    
    /**
     * Sets the stream for reading from the listener socket if
     * there is one
     *
     * @param is the stream for reading from the listener socket
     */
    public void setInputStream( InputStream is ) {
        if ( _thread != null ) {
            _thread.setInputStream( is );
        }
    }

    /**
     * Sets the stream for writing to the socket
     *
     * @param os the stream for writing to the socket, if there is one
     */
    public void setOutputStream( OutputStream os ) {
        if ( _thread != null ) {
            _thread.setOutputStream( os );
        }
    }

    /**
     * Sets a global property of the connection.
     * The following properties are defined:<BR> 
     * com.org.ietf.ldap.schema.quoting - "standard" or "NetscapeBug"<BR> 
     * Note: if this property is not set, the SDK will query the server 
     * to determine if attribute syntax values and objectclass superior 
     * values must be quoted when adding schema.<BR>
     * com.org.ietf.ldap.saslpackage - the default is "com.netscape.sasl"<BR> 
     * <P>
     *
     * @param name name of the property to set
     * @param val value to set
     * @exception LDAPException Unable to set the value of the specified
     * property.
     */
    public void setProperty( String name, Object val ) throws LDAPException {
        if ( name.equalsIgnoreCase( SCHEMA_BUG_PROPERTY ) ) { 
            _properties.put( SCHEMA_BUG_PROPERTY, val ); 
        } else if ( name.equalsIgnoreCase( SASL_PACKAGE_PROPERTY ) ) {
            _properties.put( SASL_PACKAGE_PROPERTY, val ); 
        } else if ( name.equalsIgnoreCase( "debug" ) ) {
            debug = ((String)val).equalsIgnoreCase( "true" ); 

        } else if ( name.equalsIgnoreCase( TRACE_PROPERTY ) ) {

            Object traceOutput = null;
            if (val == null) {
                _properties.remove(TRACE_PROPERTY);
            } else {
                if ( _thread != null ) {
                    traceOutput = createTraceOutput( val );
                }
                _properties.put( TRACE_PROPERTY, val ); 
            }

            if ( _thread != null ) {
                _thread.setTraceOutput( traceOutput );
            }

        // This is used only by the ldapjdk test cases to simulate a
        // server problem and to test fail-over and rebind            
        } else if ( name.equalsIgnoreCase( "breakConnection" ) ) {
            _connMgr.breakConnection();

        } else {
            throw new LDAPException( "Unknown property: " + name );
        }
    }

    /**
     * Set the default constraint set for all search operations. 
     * @param cons <CODE>LDAPSearchConstraints</CODE> object to use as the
     * default constraint set
     * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
     * @see org.ietf.ldap.LDAPSearchConstraints
     */
    public void setSearchConstraints( LDAPSearchConstraints cons ) {
        _defaultConstraints = (LDAPSearchConstraints)cons.clone();
    }

    /**
     * Specifies the object representing the socket factory that you
     * want to use to establish a connection to a server.
     * <P>
     *
     * @param factory the object representing the socket factory that
     * you want to use to establish a connection to a server
     * @see org.ietf.ldap.LDAPSocketFactory
     * @see org.ietf.ldap.LDAPSSLSocketFactory
     * @see org.ietf.ldap.LDAPConnection#getSocketFactory
     */
    public void setSocketFactory( LDAPSocketFactory factory ) {
        _factory = factory;
    }

    /**
     * Begin using the Transport Layer Security (TLS) protocol for session 
     * privacy [TLS][LDAPTLS]. If the socket factory of the connection is 
     * not capable of initiating a TLS session, an LDAPException is thrown 
     * with the error code TLS_NOT_SUPPORTED. If the server does not support 
     * the transition to a TLS session, an LDAPException is thrown with the 
     * error code returned by the server. If there are outstanding LDAP 
     * operations on the connection, an LDAPException is thrown.
     */
    public void startTLS() throws LDAPException {
    }

    /**
     * Stop using the Transport Layer Security (TLS) protocol for session 
     * privacy [LDAPTLS]. If the server does not support the termination of 
     * a TLS session, an LDAPException is thrown with the error code 
     * returned by the server. If there are outstanding LDAP operations on 
     * the connection, an LDAPException is thrown.
     */
    public void stopTLS() throws LDAPException {
    }

    /**
     * Returns the value of the specified option for this
     * <CODE>LDAPConnection</CODE> object. <P>
     *
     * These options represent the constraints for the current connection.
     * To get all constraints for the current connection, call the
     * <CODE>getSearchConstraints</CODE> method.
     * <P>
     *
     * By default, the constraints apply to all operations performed
     * through the current connection.  You can change these constraints:
     * <P>
     *
     * <UL>
     * <LI> If you want to set a constraint only for a particular operation, 
     * create an <CODE>LDAPConstraints</CODE> object (or a 
     * <CODE>LDAPSearchConstraints</CODE> object for a search or find operation)
     * with your new constraints
     * and pass it to the <CODE>LDAPConnection</CODE> method that performs the
     * operation.
     * <P>
     *
     * <LI>If you want to override these constraints for all operations
     * performed under the current connection, call the
     * <CODE>setOption</CODE> method to change the constraint.
     * <P>
     *
     * </UL>
     * <P>
     *
     * For example, the following section of code gets and prints the
     * maximum number of search results that are returned for searches
     * performed through this connection.  (This applies to all searches
     * unless a different set of search constraints is specified in an
     * <CODE>LDAPSearchConstraints</CODE> object.)
     * <P>
     *
     * <PRE>
     * LDAPConnection ld = new LDAPConnection();
     * int sizeLimit = ( (Integer)ld.getOption( LDAPConnection.SIZELIMIT ) ).intValue();
     * System.out.println( "Maximum number of results: " + sizeLimit );
     * </PRE>
     *
     * @param option you can specify one of the following options:
     * <TABLE CELLPADDING=5>
     * <TR VALIGN=BASELINE ALIGN=LEFT>
     * <TH>Option</TH><TH>Data Type</TH><TH>Description</TH></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.PROTOCOL_VERSION</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the version of the LDAP protocol used by the
     * client.
     * <P>By default, the value of this option is 2.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.DEREF</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies when your client dereferences aliases.
     *<PRE>
     * Legal values for this option are:
     *
     * DEREF_NEVER       Aliases are never dereferenced.
     *
     * DEREF_FINDING     Aliases are dereferenced when find-
     *                   ing the starting point for the
     *                   search (but not when searching
     *                   under that starting entry).
     *
     * DEREF_SEARCHING   Aliases are dereferenced when
     *                   searching the entries beneath the
     *                   starting point of the search (but
     *                   not when finding the starting
     *                   entry).
     *
     * DEREF_ALWAYS      Aliases are always dereferenced.
     *</PRE>
     * <P>By default, the value of this option is
     * <CODE>DEREF_NEVER</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.SIZELIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of search results to return.
     * If this option is set to 0, there is no maximum limit.
     * <P>By default, the value of this option is 1000.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.TIMELIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of milliseconds to wait for results
     * before timing out. If this option is set to 0, there is no maximum
     * time limit.
     * <P>By default, the value of this option is 0.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS</CODE></TD>
     * <TD><CODE>Boolean</CODE></TD>
     * <TD>Specifies whether or not your client follows referrals automatically.
     * If <CODE>true</CODE>, your client follows referrals automatically.
     * If <CODE>false</CODE>, an <CODE>LDAPReferralException</CODE> is raised
     * when referral is detected.
     * <P>By default, the value of this option is <CODE>false</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE></TD>
     * <TD><CODE>LDAPAuthHandler</CODE></TD>
     * <TD>Specifies an object with a class that implements the
     * <CODE>LDAPAuthHandler</CODE> interface.  You must define this class and
     * the <CODE>getAuthProvider</CODE> method that will be used to
     * get the distinguished name and password to use for authentication.
     * Modifying this option sets the <CODE>LDAPConnection.BIND</CODE> option to null.
     * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.BIND</CODE></TD>
     * <TD><CODE>LDAPBind</CODE></TD>
     * <TD>Specifies an object with a class that implements the
     * <CODE>LDAPBind</CODE>
     * interface.  You must define this class and the
     * <CODE>bind</CODE> method that will be used to authenticate
     * to the server on referrals. Modifying this option sets the 
     * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE> to null.
     * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS_HOP_LIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of referrals in a sequence that
     * your client will follow.  (For example, if REFERRALS_HOP_LIMIT is 5,
     * your client will follow no more than 5 referrals in a row when resolving
     * a single LDAP request.)
     * <P>By default, the value of this option is 10.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.BATCHSIZE</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the number of search results to return at a time.
     * (For example, if BATCHSIZE is 1, results are returned one at a time.)
     * <P>By default, the value of this option is 1.</TD></TR>
     * <TD><CODE>LDAPControl[]</CODE></TD>
     * <TD>Specifies the client controls that may affect the handling of LDAP
     * operations in the LDAP classes. These controls are used by the client
     * and are not passed to the LDAP server. At this time, no client controls
     * are defined for clients built with the Netscape LDAP classes. </TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.SERVERCONTROLS</CODE></TD>
     * <TD><CODE>LDAPControl[]</CODE></TD>
     * <TD>Specifies the server controls that are passed to the LDAP
     * server on each LDAP operation. Not all servers support server
     * controls; a particular server may or may not support a given
     * server control.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>MAXBACKLOG</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of search results to accumulate in an
     * LDAPSearchResults before suspending the reading of input from the server.
     * <P>By default, the value of this option is 100. The value 0 means there
     *  is no limit.</TD></TR>
     * </TABLE><P>
     * @return the value for the option wrapped in an object.  (You
     * need to cast the returned value as its appropriate type. For
     * example, when getting the SIZELIMIT option, cast the returned
     * value as an <CODE>Integer</CODE>.)
     * @exception LDAPException Failed to get the specified option.
     * @see org.ietf.ldap.LDAPAuthHandler
     * @see org.ietf.ldap.LDAPConstraints
     * @see org.ietf.ldap.LDAPSearchConstraints
     * @see org.ietf.ldap.LDAPReferralException
     * @see org.ietf.ldap.LDAPControl
     * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
     */
    public Object getOption( int option ) throws LDAPException {
        if (option == LDAPConnection.PROTOCOL_VERSION) {
            return new Integer(_protocolVersion);
        }

        return getOption(option, _defaultConstraints);
    }

    private static Object getOption( int option, LDAPSearchConstraints cons )
        throws LDAPException {
        switch (option) {
            case LDAPConnection.DEREF:
              return new Integer (cons.getDereference());
            case LDAPConnection.SIZELIMIT:
              return new Integer (cons.getMaxResults());
            case LDAPConnection.TIMELIMIT:
              return new Integer (cons.getServerTimeLimit());
            case LDAPConnection.REFERRALS:
              return new Boolean (cons.getReferralFollowing());
            case LDAPConnection.REFERRALS_REBIND_PROC:
              return cons.getReferralHandler();
            case LDAPConnection.REFERRALS_HOP_LIMIT:
              return new Integer (cons.getHopLimit());
            case LDAPConnection.BATCHSIZE:
              return new Integer (cons.getBatchSize());
            case LDAPConnection.SERVERCONTROLS:
              return cons.getControls();
            case MAXBACKLOG:
              return new Integer (cons.getMaxBacklog());
            default:
              throw new LDAPException ( "invalid option",
                                        LDAPException.PARAM_ERROR );
        }
    }
    
    /**
     * Sets the value of the specified option for this
     * <CODE>LDAPConnection</CODE> object. <P>
     *
     * These options represent the constraints for the current
     * connection.
     * To get all constraints for the current connection, call the
     * <CODE>getSearchConstraints</CODE> method. 
     * <P>
     *
     * By default, the option that you set applies to all subsequent
     * operations performed through the current connection. If you want to
     * set a constraint only for a particular operation, create an
     * <CODE>LDAPConstraints</CODE> object (or a 
     * <CODE>LDAPSearchConstraints</CODE> object for a search or find operation)
     * with your new constraints
     * and pass it to the <CODE>LDAPConnection</CODE> method that performs the
     * operation.
     * <P>
     *
     * For example, the following section of code changes the constraint for
     * the maximum number of search results that are returned for searches
     * performed through this connection.  (This applies to all searches
     * unless a different set of search constraints is specified in an
     * <CODE>LDAPSearchConstraints</CODE> object.)
     * <P>
     *
     * <PRE>
     * LDAPConnection ld = new LDAPConnection();
     * Integer newLimit = new Integer( 20 );
     * ld.setOption( LDAPConnection.SIZELIMIT, newLimit );
     * System.out.println( "Changed the maximum number of results to " + newLimit.intValue() );
     * </PRE>
     *
     * @param option you can specify one of the following options:
     * <TABLE CELLPADDING=5>
     * <TR VALIGN=BASELINE ALIGN=LEFT>
     * <TH>Option</TH><TH>Data Type</TH><TH>Description</TH></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.PROTOCOL_VERSION</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the version of the LDAP protocol used by the
     * client.
     * <P>By default, the value of this option is 2.  If you want
     * to use LDAP v3 features (such as extended operations or
     * controls), you need to set this value to 3. </TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.DEREF</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies when your client dereferences aliases.
     *<PRE>
     * Legal values for this option are:
     *
     * DEREF_NEVER       Aliases are never dereferenced.
     *
     * DEREF_FINDING     Aliases are dereferenced when find-
     *                   ing the starting point for the
     *                   search (but not when searching
     *                   under that starting entry).
     *
     * DEREF_SEARCHING   Aliases are dereferenced when
     *                   searching the entries beneath the
     *                   starting point of the search (but
     *                   not when finding the starting
     *                   entry).
     *
     * DEREF_ALWAYS      Aliases are always dereferenced.
     *</PRE>
     * <P>By default, the value of this option is
     * <CODE>DEREF_NEVER</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.SIZELIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of search results to return.
     * If this option is set to 0, there is no maximum limit.
     * <P>By default, the value of this option is 1000.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.TIMELIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of milliseconds to wait for results
     * before timing out. If this option is set to 0, there is no maximum
     * time limit.
     * <P>By default, the value of this option is 0.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS</CODE></TD>
     * <TD><CODE>Boolean</CODE></TD>
     * <TD>Specifies whether or not your client follows referrals automatically.
     * If <CODE>true</CODE>, your client follows referrals automatically.
     * If <CODE>false</CODE>, an <CODE>LDAPReferralException</CODE> is
     * raised when a referral is detected.
     * <P>By default, the value of this option is <CODE>false</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE></TD>
     * <TD><CODE>LDAPAuthHandler</CODE></TD>
     * <TD>Specifies an object with a class that implements the
     * <CODE>LDAPAuthHandler</CODE>
     * interface.  You must define this class and the
     * <CODE>getAuthProvider</CODE> method that will be used to get
     * the distinguished name and password to use for authentication. 
     * Modifying this option sets the <CODE>LDAPConnection.BIND</CODE> option to null.
     * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.BIND</CODE></TD>
     * <TD><CODE>LDAPBind</CODE></TD>
     * <TD>Specifies an object with a class that implements the
     * <CODE>LDAPBind</CODE>
     * interface.  You must define this class and the
     * <CODE>bind</CODE> method that will be used to autheniticate
     * to the server on referrals. Modifying this option sets the 
     * <CODE>LDAPConnection.REFERRALS_REBIND_PROC</CODE> to null.
     * <P>By default, the value of this option is <CODE>null</CODE>.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.REFERRALS_HOP_LIMIT</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of referrals in a sequence that
     * your client will follow.  (For example, if REFERRALS_HOP_LIMIT is 5,
     * your client will follow no more than 5 referrals in a row when resolving
     * a single LDAP request.)
     * <P>By default, the value of this option is 10.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.BATCHSIZE</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the number of search results to return at a time.
     * (For example, if BATCHSIZE is 1, results are returned one at a time.)
     * <P>By default, the value of this option is 1.</TD></TR>
     * <TD><CODE>LDAPControl[]</CODE></TD>
     * <TD>Specifies the client controls that may affect handling of LDAP
     * operations in the LDAP classes. These controls are used by the client
     * and are not passed to the server. At this time, no client controls
     * are defined for clients built with the Netscape LDAP classes. </TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>LDAPConnection.SERVERCONTROLS</CODE></TD>
     * <TD><CODE>LDAPControl[]</CODE></TD>
     * <TD>Specifies the server controls that are passed to the LDAP
     * server on each LDAP operation. Not all servers support server
     * controls; a particular server may or may not support a particular
     * control.</TD></TR>
     * <TR VALIGN=BASELINE><TD>
     * <CODE>MAXBACKLOG</CODE></TD>
     * <TD><CODE>Integer</CODE></TD>
     * <TD>Specifies the maximum number of search results to accumulate in an
     * LDAPSearchResults before suspending the reading of input from the server.
     * <P>By default, the value of this option is 100. The value 0 means there
     *  is no limit.</TD></TR>
     * </TABLE><P>
     * @param value the value to assign to the option.  The value must be
     * the java.lang object wrapper for the appropriate parameter
     * (e.g. boolean->Boolean,
     *   integer->Integer)
     * @exception LDAPException Failed to set the specified option.
     * @see org.ietf.ldap.LDAPAuthHandler
     * @see org.ietf.ldap.LDAPConstraints
     * @see org.ietf.ldap.LDAPSearchConstraints
     * @see org.ietf.ldap.LDAPReferralException
     * @see org.ietf.ldap.LDAPControl
     * @see org.ietf.ldap.LDAPConnection#getSearchConstraints
     * @see org.ietf.ldap.LDAPConnection#search(java.lang.String, int, java.lang.String, java.lang.String[], boolean, org.ietf.ldap.LDAPSearchConstraints)
     */
    public void setOption( int option, Object value ) throws LDAPException {
        if (option == LDAPConnection.PROTOCOL_VERSION) {
            setProtocolVersion(((Integer)value).intValue());
            return;
        }
        setOption(option, value, _defaultConstraints);
    }

    private static void setOption( int option,
                                   Object value,
                                   LDAPSearchConstraints cons )
        throws LDAPException {
      try {
        switch (option) {
        case LDAPConnection.DEREF:
          cons.setDereference(((Integer)value).intValue());
          return;
        case LDAPConnection.SIZELIMIT:
          cons.setMaxResults(((Integer)value).intValue());
          return;
        case LDAPConnection.TIMELIMIT:
          cons.setTimeLimit(((Integer)value).intValue());
          return;
        case LDAPConnection.SERVER_TIMELIMIT:
          cons.setServerTimeLimit(((Integer)value).intValue());
          return;
        case LDAPConnection.REFERRALS:
          cons.setReferralFollowing(((Boolean)value).booleanValue());
          return;
        case LDAPConnection.REFERRALS_REBIND_PROC:
          cons.setReferralHandler((LDAPReferralHandler)value);
          return;
        case LDAPConnection.REFERRALS_HOP_LIMIT:
          cons.setHopLimit(((Integer)value).intValue());
          return;
        case LDAPConnection.BATCHSIZE:
          cons.setBatchSize(((Integer)value).intValue());
          return;
        case LDAPConnection.SERVERCONTROLS:
          if ( value == null )
            cons.setControls( (LDAPControl[]) null );
          else if ( value instanceof LDAPControl )
            cons.setControls( (LDAPControl) value );
          else if ( value instanceof LDAPControl[] )
            cons.setControls( (LDAPControl[])value );
          else
            throw new LDAPException ( "invalid LDAPControl",
                                      LDAPException.PARAM_ERROR );
          return;
        case MAXBACKLOG:
          cons.setMaxBacklog( ((Integer)value).intValue() );
          return;
        default:
          throw new LDAPException ( "invalid option",
                                    LDAPException.PARAM_ERROR );
        }
      } catch ( ClassCastException cc ) {
          throw new LDAPException ( "invalid option value",
                                    LDAPException.PARAM_ERROR );
      }
    }

    /**
     * Send a request to the server
     */
    void sendRequest( JDAPProtocolOp oper, LDAPMessageQueue myListener,
                      LDAPConstraints cons ) throws LDAPException {

        // retry three times if we get a nullPointer exception.
        // Don't remove this. The following situation might happen:
        // Before sendRequest gets invoked, it is possible that the
        // LDAPConnThread encountered a network error and called
        // deregisterConnection which set the thread reference to null.
        boolean requestSent = false;
        for ( int i = 0; !requestSent && (i < 3); i++ ) {
            try {
                _thread.sendRequest( this, oper, myListener, cons );
                requestSent = true;
            } catch( NullPointerException ne ) {
                // do nothing
            } catch (IllegalArgumentException e) {
                throw new LDAPException(e.getMessage(),
                                        LDAPException.PARAM_ERROR);
            }
            
        }
        if ( !isConnected() ) {
            throw new LDAPException( "The connection is not available",
                                     LDAPException.OTHER );
        }
        if ( !requestSent ) {
            throw new LDAPException( "Failed to send request",
                                     LDAPException.OTHER );
        }
    }

    /**
     * Internal routine. Binds to the LDAP server.
     * This method is used by the "smart failover" feature. If a server
     * or network error has occurred, an attempt is made to automatically
     * restore the connection on the next ldap operation request
     * @exception LDAPException failed to bind or the user has disconncted
     */
    private void internalBind( LDAPConstraints cons ) throws LDAPException {
        
        // If the user has invoked disconnect() no attempt is made
        // to restore the connection
        if ( (_connMgr != null) && _connMgr.isUserDisconnected() ) {
            throw new LDAPException( "not connected", LDAPException.OTHER );
        }

        if ( _saslBinder != null ) {
            if ( !isConnected() ) {
                connect();
            }
            _saslBinder.bind( this, false );
            _authMethod = "sasl";
        } else {
            //Rebind using _rebindConstraints
            if ( _rebindConstraints == null ) {
                _rebindConstraints = _defaultConstraints;
            }
            internalBind ( _protocolVersion, false, _rebindConstraints );
        }
    }

    void checkSearchMsg( LDAPSearchResults value, LDAPMessage msg,
                         LDAPSearchConstraints cons, String dn,
                         int scope, String filter,
                         String attrs[], boolean attrsOnly)
        throws LDAPException {

        value.setMsgID( msg.getMessageID() );

        try {
            checkMsg( msg );
            // not the JDAPResult
            if ( msg.getProtocolOp().getType() !=
                 JDAPProtocolOp.SEARCH_RESULT ) {
                value.add( msg );
            }
        } catch ( LDAPReferralException e ) {
            Vector res = new Vector();
            
            try {
                performReferrals( e, cons, JDAPProtocolOp.SEARCH_REQUEST, dn,
                                  scope, filter, attrs, attrsOnly, null, null,
                                  null, res );
            }
            catch ( LDAPException ex ) {
                if ( msg.getProtocolOp() instanceof
                     JDAPSearchResultReference ) {
                   /*
                      Don't want to miss all remaining results, so continue.
                      This is very ugly (using println). We should have a 
                      configurable parameter (probably in LDAPSearchConstraints)
                      whether to ignore failed search references or throw an
                      exception.
                    */
                    System.err.println( "LDAPConnection.checkSearchMsg: " +
                                        "ignoring bad referral" );
                    return;
                }
                throw ex;
            }

            // The size of the vector can be more than 1 because it is possible
            // to visit more than one referral url to retrieve the entries
            for ( int i = 0; i < res.size(); i++ ) {
                value.addReferralEntries( (LDAPSearchResults)res.elementAt(i) );
            }

            res = null;
        } catch ( LDAPException e ) {
            if ( (e.getResultCode() == LDAPException.ADMIN_LIMIT_EXCEEDED) ||
                 (e.getResultCode() == LDAPException.TIME_LIMIT_EXCEEDED) ||
                 (e.getResultCode() == LDAPException.SIZE_LIMIT_EXCEEDED) ) {
                value.add(e);
            } else {
                throw e;
            }
        }
    }

    
    /**
     * Internal routine. Binds to the LDAP server.
     * @param version protocol version to request from server
     * @param rebind true if the bind/authenticate operation is requested,
     * false if the method is invoked by the "smart failover" feature
     * @exception LDAPException failed to bind
     */
    private void internalBind( int version, boolean rebind,
                               LDAPConstraints cons ) throws LDAPException {
        _saslBinder = null;

        if ( !isConnected() ) {
            _bound = false;
            _authMethod = "none";
            connect();
            // special case: the connection currently is not bound, and now
            // there is a bind request. The connection needs to reconnect if
            // the thread has more than one LDAPConnection.
        } else if ( !_bound && rebind && (_thread.getClientCount() > 1) ) {
            disconnect();
            connect();
        }

        // if the connection is still intact and no rebind request
        if ( _bound && !rebind ) {
            return;
        }

        // if the connection was lost and did not have any kind of bind
        // operation and the current one does not request any bind operation (ie,
        // no authenticate has been called)
        if ( !_anonymousBound &&
             ((_boundDN == null) || (_boundPasswd == null)) &&
             !rebind ) {
            return;
        }

        if ( _bound && rebind ) {
            if ( _protocolVersion == version ) {
                if ( _anonymousBound &&
                     ((_boundDN == null) || (_boundPasswd == null)) ) {
                    return;
                }

                if ( !_anonymousBound &&
                     (_boundDN != null) &&
                     (_boundPasswd != null) &&
                     _boundDN.equals(_prevBoundDN) &&
                     equalsBytes(_boundPasswd, _prevBoundPasswd) ) {
                    return;
                }
            }

            // if we got this far, we need to rebind since previous and
            // current credentials are not the same.
            // if the current connection is the only connection of the thread,
            // then reuse this current connection. otherwise, disconnect the
            // current one (ie, detach from the current thread) and reconnect
            // again (ie, get a new thread).
            if ( _thread.getClientCount() > 1 ) {
                disconnect();
                connect();
            }
        }

        _protocolVersion = version;

        LDAPResponseQueue myListener = getResponseListener();
        try {
            if ( (_referralConnection != null) &&
                 _referralConnection.isConnected() ) {
                _referralConnection.disconnect();
            }
            _referralConnection = null;
            _bound = false;
            sendRequest( new JDAPBindRequest( _protocolVersion, _boundDN,
                                              _boundPasswd),
                         myListener, cons );
            checkMsg( myListener.getResponse() );
            markConnAsBound();
            _rebindConstraints = (LDAPConstraints)cons.clone();
            _authMethod = "simple";
        } catch (LDAPReferralException e) {
            _referralConnection = createReferralConnection( e, cons );
        } finally {
            releaseResponseListener( myListener );
        }
    }

    private static boolean equalsBytes( byte[] b1, byte[] b2 ) {
        if ( b1 == null ) {
            return ( b2 == null );
        } else if ( b2 == null ) {
            return true;
        }
        if ( b1.length != b2.length ) {
            return false;
        }
        for( int i = 0; i < b1.length; i++ ) {
            if ( b1[i] != b2[1] ) {
                return false;
            }
        }
        return true;
    }

    /**
     * Mark this connection as bound in the thread connection table
     */
    void markConnAsBound() {
        synchronized (_threadConnTable) {
            if (_threadConnTable.containsKey(_thread)) {
                Vector v = (Vector)_threadConnTable.get(_thread);
                for (int i=0, n=v.size(); i<n; i++) {
                    LDAPConnection conn = (LDAPConnection)v.elementAt(i);
                    conn._bound = true;
                }
            } else {
                printDebug( "Thread table does not contain the thread of " +
                            "this object" );
            }
        }
    }


    /**
     * Evaluate the TRACE_PROPERTY value and create output stream.
     * The value can be of type String, OutputStream or LDAPTraceWriter.
     * The String value represents output file name. If the name is an empty
     * string, the output is sent to System.err. If the file name is
     * prefixed with a '+' character, the file is opened in append mode.
     *
     * @param out Trace output specifier. A file name, an output stream 
     * or an instance of LDAPTraceWriter
     * @return An output stream or an LDAPTraceWriter instance
     */
    Object createTraceOutput( Object out ) throws LDAPException {
                
        if ( out instanceof String ) { // trace file name
            OutputStream os = null;
            String file = (String)out;
            if ( file.length() == 0 ) {
                os = System.err;
            } else {
                try {
                    boolean appendMode = (file.charAt(0) == '+');
                    if ( appendMode ) {
                        file = file.substring(1);
                    }                        
                    FileOutputStream fos =
                        new FileOutputStream( file, appendMode );
                    os = new BufferedOutputStream( fos );
                }
                catch ( IOException e ) {
                    throw new LDAPException(
                        "Can not open output trace file " + file + " " + e );
                }
            }
            return os;
        }        
        else if ( out instanceof OutputStream )  {
            return out;
        }       
        else if ( out instanceof LDAPTraceWriter )  {
            return out;
        } else {
            throw new LDAPException( TRACE_PROPERTY +
                                     " must be an OutputStream, a file " +
                                     "name or an instance of LDAPTraceWriter" );
        }

    }
    
    /**
     * Sets the LDAP protocol version that your client prefers to use when
     * connecting to the LDAP server.
     * <P>
     *
     * @param version the LDAP protocol version that your client uses
     */
    private void setProtocolVersion( int version ) {
        _protocolVersion = version;
    }

    /**
     * Remove this connection from the thread connection table
     */
    private void deleteThreadConnEntry() {
        synchronized ( _threadConnTable ) {
            Vector connVector = (Vector)_threadConnTable.get( _thread );
            if ( connVector == null ) {
                printDebug( "Thread table does not contain the thread of " +
                            "this object" );
                return;
            }
            Enumeration enumv = connVector.elements();
            while ( enumv.hasMoreElements() ) {
                LDAPConnection c = (LDAPConnection)enumv.nextElement();
                if ( c.equals( this ) ) {
                    connVector.removeElement( c );
                    if ( connVector.size() == 0 ) {
                        _threadConnTable.remove( _thread );
                    }
                    return;
                }
            }
        }
    }

    /**
     * Remove the association between this object and the connection thread
     */
    synchronized void deregisterConnection() {
        if ( (_thread != null) && _thread.isRunning() ) {
            _thread.deregister( this );
        }
        _thread = null;
        _bound = false;
    }

    /**
     * Returns the trace output object if set by the user
     */
    Object getTraceOutput() throws LDAPException {
        
        // Check first if trace output has been set using setProperty()
        Object traceOut = _properties.get( TRACE_PROPERTY );
        if ( traceOut != null ) {
            return createTraceOutput( traceOut );
        }
        
        // Check if the property has been set with java
        // -Dcom.org.ietf.ldap.trace
        // If the property does not have a value, send the trace to the
        // System.err, otherwise use the value as the output file name
        try {
            traceOut = System.getProperty( TRACE_PROPERTY );
            if ( traceOut != null ) {
                return createTraceOutput( traceOut );
            }
        }
        catch ( Exception e ) {
            ;// In browser, access to property might not be allowed
        }
        return null;
    }        
        
        
    private synchronized LDAPConnThread getNewThread(LDAPConnSetupMgr connMgr,
                                                     LDAPCache cache)
        throws LDAPException {

        LDAPConnThread newThread = null;
        Vector v = null;

        synchronized( _threadConnTable ) {

            Enumeration keys = _threadConnTable.keys();
            boolean connExists = false;

            // transverse each thread
            while ( keys.hasMoreElements() ) {
                LDAPConnThread connThread = (LDAPConnThread)keys.nextElement();
                Vector connVector = (Vector)_threadConnTable.get( connThread );
                Enumeration enumv = connVector.elements();

                // traverse each LDAPConnection under the same thread
                while ( enumv.hasMoreElements() ) {
                    LDAPConnection conn = (LDAPConnection)enumv.nextElement();

                    // this is not a brand new connection
                    if ( conn.equals( this ) ) {
                        connExists = true;

                        if ( !connThread.isAlive() ) {
                            // need to move all the LDAPConnections from the dead thread
                            // to the new thread
                            try {
                                newThread =
                                    new LDAPConnThread( connMgr, cache,
                                                        getTraceOutput() );
                                v = (Vector)_threadConnTable.remove(
                                    connThread );
                                break;
                            } catch ( Exception e ) {
                                throw new LDAPException(
                                    "unable to establish connection",
                                    LDAPException.UNAVAILABLE );
                            }
                        }
                        break;
                    }
                }

                if ( connExists ) {
                    break;
                }
            }

            // if this connection is new or the corresponding thread for
            // the current connection is dead
            if ( !connExists ) {
                try {
                    newThread = new LDAPConnThread( connMgr, cache,
                                                    getTraceOutput() );
                    v = new Vector();
                    v.addElement( this );
                } catch ( Exception e ) {
                    throw new LDAPException( "unable to establish connection",
                                             LDAPException.UNAVAILABLE );
                }
            }

            // add new thread to the table
            if ( newThread != null ) {
                _threadConnTable.put( newThread, v );
                for ( int i = 0, n = v.size(); i < n; i++ ) {
                    LDAPConnection c = (LDAPConnection)v.elementAt( i );
                    newThread.register( c );
                    c._thread = newThread;
                }
            }
        }

        return newThread;
    }

    /**
     * Performs certificate-based authentication if client authentication was
     * specified at construction time.
     * @exception LDAPException if certificate-based authentication fails.
     */
    private void authenticateSSLConnection() throws LDAPException {

        // if this is SSL
        if ( (_factory != null) &&
             (_factory instanceof LDAPSSLSocketFactoryExt) ) {

            if ( ((LDAPSSLSocketFactoryExt)_factory).isClientAuth() ) {
                bind( null, null, new String[] {EXTERNAL_MECHANISM},
                      EXTERNAL_MECHANISM_PACKAGE, null, null, null );
            }
        }
    }

    /**
     * Gets a new listening agent from the internal buffer of available agents.
     * These objects are used to make the asynchronous LDAP operations
     * synchronous.
     *
     * @return response listener object
     */
    synchronized LDAPResponseQueue getResponseListener() {
        if ( _responseListeners == null ) {
            _responseListeners = new Vector( 5 );
        }

        LDAPResponseQueue l;
        if ( _responseListeners.size() < 1 ) {
            l = new LDAPResponseQueue ( /*asynchOp=*/false );
        }
        else {
            l = (LDAPResponseQueue)_responseListeners.elementAt( 0 );
            _responseListeners.removeElementAt( 0 );
        }
        return l;
    }

    /**
     * Get a new search listening agent from the internal buffer of available
     * agents. These objects are used to make the asynchronous LDAP operations
     * synchronous.
     * @return a search response listener object
     */
    private synchronized LDAPSearchQueue getSearchListener (
        LDAPSearchConstraints cons ) {
        if ( _searchListeners == null ) {
            _searchListeners = new Vector( 5 );
        }

        LDAPSearchQueue l;
        if ( _searchListeners.size() < 1 ) {
            l = new LDAPSearchQueue ( /*asynchOp=*/false, cons );
        }
        else {
            l = (LDAPSearchQueue)_searchListeners.elementAt( 0 );
            _searchListeners.removeElementAt( 0 );
            l.setSearchConstraints( cons );
        }
        return l;
    }

    /**
     * Put a listening agent into the internal buffer of available agents.
     * These objects are used to make the asynchronous LDAP operations
     * synchronous.
     * @param l listener to buffer
     */
    synchronized void releaseResponseListener( LDAPResponseQueue l ) {
        if ( _responseListeners == null ) {
            _responseListeners = new Vector( 5 );
        }

        l.reset();
        _responseListeners.addElement( l );
    }

    /**
     * Put a search listening agent into the internal buffer of available
     * agents. These objects are used to make the asynchronous LDAP
     * operations synchronous.
     * @param l listener to buffer
     */
    synchronized void releaseSearchListener( LDAPSearchQueue l ) {
        if ( _searchListeners == null ) {
            _searchListeners = new Vector( 5 );
        }

        l.reset();
        _searchListeners.addElement( l );
    }

    /**
     * Checks the message (assumed to be a return value).  If the resultCode
     * is anything other than SUCCESS, it throws an LDAPException describing
     * the server's (error) response.
     * @param m server response to validate
     * @exception LDAPException failed to check message
     */
    void checkMsg( LDAPMessage m ) throws LDAPException {
      if ( m.getProtocolOp() instanceof JDAPResult ) {
          JDAPResult response = (JDAPResult)m.getProtocolOp();
          int resultCode = response.getResultCode();

          if ( resultCode == JDAPResult.SUCCESS ) {
              return;
          }

          if ( resultCode == JDAPResult.REFERRAL ) {
              throw new LDAPReferralException ( "referral", resultCode,
                                                response.getReferrals() );
          }

          if ( resultCode == JDAPResult.LDAP_PARTIAL_RESULTS ) {
              throw new LDAPReferralException ( "referral", resultCode,
                                                response.getErrorMessage() );
          } else {
              throw new LDAPException ( "error result", resultCode,
                                        response.getErrorMessage(),
                                        response.getMatchedDN() );
          }

      } else if ( m.getProtocolOp() instanceof JDAPSearchResultReference ) {
          String[] referrals =
            ((JDAPSearchResultReference)m.getProtocolOp()).getUrls();
          throw new LDAPReferralException ( "referral",
                                            JDAPResult.SUCCESS, referrals );
      } else {
          return;
      }
    }

    /**
     * Set response controls for the current connection for a particular 
     * thread. Get the oldest returned controls and remove them from the 
     * queue. If the connection is executing a persistent search, there may
     * be more than one set of controls in the queue. For any other 
     * operation, there will only ever be at most one set of controls 
     * (controls from any earlier operation are replaced by controls 
     * received on the latest operation on this connection by this thread).
     * @param current the target thread
     * @param con the server response controls
     */
    void setResponseControls( LDAPConnThread current,
                              LDAPResponseControl con ) {
        synchronized(_responseControlTable) {
            Vector v = (Vector)_responseControlTable.get( current );

            // if the current thread already contains response controls from
            // a previous operation
            if ( (v != null) && (v.size() > 0) ) {

                // look at each response control
                for ( int i = v.size() - 1; i >= 0; i-- ) {
                    LDAPResponseControl response = 
                      (LDAPResponseControl)v.elementAt( i );
    
                    // if this response control belongs to this connection
                    if ( response.getConnection().equals( this ) ) {
 
                        // if the given control is null or 
                        // the given control is not null and the current 
                        // control does not correspond to the new LDAPMessage
                        if ( (con == null) || 
                             (con.getMsgID() != response.getMsgID()) ) {
                            v.removeElement( response );
                        }

                        // For the same connection, if the message id from the 
                        // given control is the same as the one in the queue,
                        // those controls in the queue will not get removed
                        // since they come from the persistent search control
                        // which allows more than one control response for
                        // one persistent search operation.
                    }
                }
            } else {
                if ( con != null ) {
                    v = new Vector();
                }
            }          

            if ( con != null ) {
                v.addElement( con );
                _responseControlTable.put( current, v );
            }

            /* Do some garbage collection: check if any attached threads have
               exited */
            /* Now check all threads in the list */
            Enumeration e = _attachedList.elements();
            while( e.hasMoreElements() ) {
                LDAPConnThread aThread = (LDAPConnThread)e.nextElement();
                if ( !aThread.isAlive() ) {
                    _responseControlTable.remove( aThread );
                    _attachedList.removeElement( aThread );
                }
            }
        }
        /* Make sure we're registered */
        if ( _attachedList.indexOf( current ) < 0 ) {
            _attachedList.addElement( current );
        }
    }

    /**
     * Set up connection for referral.
     * @param u referral URL
     * @param cons search constraints
     * @return new LDAPConnection, already connected and authenticated
     */
    private LDAPConnection prepareReferral( String connectList,
                                            LDAPConstraints cons )
        throws LDAPException {
        LDAPConnection connection =
            new LDAPConnection( this.getSocketFactory() );
        
        // Set the same connection setup failover policy as for this connection
        connection.setConnSetupDelay( getConnSetupDelay() );
        
        connection.setOption( REFERRALS, new Boolean(true) );
        connection.setOption( REFERRALS_REBIND_PROC,
                              cons.getReferralHandler() );
  
        // need to set the protocol version which gets passed to connection
        connection.setOption( PROTOCOL_VERSION,
                              new Integer(_protocolVersion) );

        connection.setOption( REFERRALS_HOP_LIMIT,
                              new Integer(cons.getHopLimit()-1) );

        try { 
            connection.connect( connectList, connection.DEFAULT_PORT );
        }
        catch ( LDAPException e ) {
            throw new LDAPException( "Referral connect failed: " +
                                     e.getMessage(),
                                     e.getResultCode() );
        }
        return connection;
    }

    private void referralRebind( LDAPConnection ldc, LDAPConstraints cons )
        throws LDAPException{
        try {
            LDAPReferralHandler handler = cons.getReferralHandler();
            if ( handler == null ) {
                ldc.bind ( _protocolVersion, null, null );
            } else if ( handler instanceof LDAPAuthHandler ) {
                LDAPAuthProvider auth =
                  ((LDAPAuthHandler)handler).getAuthProvider(
                      ldc.getHost(),
                      ldc.getPort());
                ldc.bind( _protocolVersion,
                          auth.getDN(),
                          auth.getPassword() );
            } else if ( handler instanceof LDAPBindHandler ) {
                String[] urls = { "ldap://" + ldc.getHost() + ':' +
                                  ldc.getPort() + '/' };
                ((LDAPBindHandler)handler).bind( urls, ldc);
            }
        }
        catch ( LDAPException e ) {
            throw new LDAPException( "Referral bind failed: " + e.getMessage(),
                                     e.getResultCode() );
        }            
    }
    
    
    private String createReferralConnectList( String[] urls ) {
        String connectList = "";
        String host = null;
        int port = 0;
        
        for ( int i=0; urls != null && i < urls.length; i++ ) {
            try {
                LDAPUrl url = new LDAPUrl( urls[i] );
                host = url.getHost();
                port = url.getPort();
                if ( (host == null) ||
                     (host.length() < 1) ) {
                    // If no host:port was specified, use the latest
                    // (hop-wise) parameters
                    host = getHost();
                    port = getPort();
                }
            } catch ( Exception e ) {
                host = getHost();
                port = getPort();
            }
            connectList += (i==0 ? "" : " ") + host+":"+port;
        }
        
        return (connectList.length() == 0) ? null : connectList;
    }

    private LDAPUrl findReferralURL( LDAPConnection ldc, String[] urls ) {
        String connHost = ldc.getHost();
        int    connPort = ldc.getPort();
        for ( int i = 0; i < urls.length; i++ ) {
            try {
                LDAPUrl url = new LDAPUrl( urls[i] );
                String host = url.getHost();
                int port = url.getPort();
                if ( host == null ||
                     host.length() < 1 ) {
                    // No host:port specified, compare with the latest
                    // (hop-wise) parameters 
                    if ( connHost.equals( getHost() ) &&
                         connPort == getPort() ) {
                        return url;
                    }
                } else if ( connHost.equals( host ) &&
                            connPort == port ) {
                    return url;
                }
            } catch ( Exception e ) {
            }
        }
        return null;
    }
    
    /**
     * Establish the LDAPConnection to the referred server. This one is used
     * for bind operation only since we need to keep this new connection for
     * the subsequent operations. This new connection will be destroyed in
     * two circumstances: disconnect gets called or the client binds as
     * someone else.
     * @return the new LDAPConnection to the referred server
     */
    LDAPConnection createReferralConnection( LDAPReferralException e,
                                             LDAPConstraints cons )
        throws LDAPException {
        if ( cons.getHopLimit() <= 0 ) {
            throw new LDAPException( "exceed hop limit",
                                     e.getResultCode(),
                                     e.getLDAPErrorMessage() );
        }
        if ( !cons.getReferralFollowing() ) {
            throw e;
        }

        String connectList = 
            createReferralConnectList( e.getReferrals() );
        // If there are no referrals (because the server isn't set up for
        // them), give up here
        if ( connectList == null ) {
            throw new LDAPException( "No target URL in referral",
                                     LDAPException.NO_RESULTS_RETURNED );
        }

        LDAPConnection connection = null;
        connection = prepareReferral( connectList, cons );
        try {
            connection.bind( _protocolVersion, _boundDN, _boundPasswd );
        } catch ( LDAPException authEx ) {
            // Disconnect needed to terminate the LDAPConnThread
            try  {                
                connection.disconnect();
            } catch ( LDAPException ignore ) {
            }
            throw authEx;
        }
        return connection;
    }

    /**
     * Follows a referral
     *
     * @param e referral exception
     * @param cons search constraints
     */
    void performReferrals( LDAPReferralException e,
                           LDAPConstraints cons, int ops,
                           /* unions of different operation parameters */
                           String dn, int scope, String filter, String types[],
                           boolean attrsOnly, LDAPModification mods[],
                           LDAPEntry entry,
                           LDAPAttribute attr,
                           /* result */
                           Vector results )
        throws LDAPException {

        if ( cons.getHopLimit() <= 0 ) {
            throw new LDAPException( "exceed hop limit",
                                     e.getResultCode(),
                                     e.getLDAPErrorMessage() );
        }
        if ( !cons.getReferralFollowing() ) {
            if ( ops == JDAPProtocolOp.SEARCH_REQUEST ) {
                LDAPSearchResults res = new LDAPSearchResults();
                res.add( e );
                results.addElement( res );
                return;
            } else {
                throw e;
            }
        }

        String[] urls = e.getReferrals();
        // If there are no referrals (because the server isn't configured to
        // return one), give up here
        if ( (urls == null) || (urls.length == 0) ) {
            return;
        }

        LDAPUrl referralURL = null;
        LDAPConnection connection = null;

        if ( (_referralConnection != null) &&
             _referralConnection.isConnected() ) {
            referralURL = findReferralURL( _referralConnection, urls );
        }
        if ( referralURL != null ) {
            connection = _referralConnection;
        }
        else {
            String connectList = createReferralConnectList( urls );
            connection = prepareReferral( connectList, cons );
                
            // which one did we connect to...
            referralURL = findReferralURL( connection, urls );
                
            // Authenticate
            referralRebind( connection, cons );
        }

        String newDN = referralURL.getDN();
        String DN = null;
        if ( (newDN == null) || newDN.equals("") ) {
            DN = dn;
        } else {
            DN = newDN;
        }
        // If this was a one-level search, and a direct subordinate
        // has a referral, there will be a "?base" in the URL, and
        // we have to rewrite the scope from one to base
        if ( referralURL.toString().indexOf("?base") > -1 ) {
            scope = SCOPE_BASE;
        }

        LDAPSearchConstraints newcons = (LDAPSearchConstraints)cons.clone();
        newcons.setHopLimit( cons.getHopLimit()-1 );

        performReferrals( connection, newcons, ops, DN, scope, filter,
                          types, attrsOnly, mods, entry, attr, results );
    }

    void performReferrals( LDAPConnection connection, 
                           LDAPConstraints cons, int ops, String dn, int scope,
                           String filter, String types[], boolean attrsOnly,
                           LDAPModification mods[], LDAPEntry entry,
                           LDAPAttribute attr,
                           Vector results ) throws LDAPException {
 
        LDAPSearchResults res = null;
        try {
            switch ( ops ) {
                case JDAPProtocolOp.SEARCH_REQUEST:

                    res = connection.search( dn, scope, filter,
                                             types, attrsOnly, 
                                             (LDAPSearchConstraints)cons );
                    if ( res != null ) {
                        res.closeOnCompletion( connection );
                        results.addElement( res );
                    } else {
                        if ( (_referralConnection == null) ||
                             !connection.equals(_referralConnection) ) {
                            connection.disconnect();
                        }
                    }
                    break;
                case JDAPProtocolOp.MODIFY_REQUEST:
                    connection.modify( dn, mods, cons );
                    break;
                case JDAPProtocolOp.ADD_REQUEST:
                    if ( (dn != null) && !dn.equals("") )
                         entry.setDN( dn );
                    connection.add( entry, cons );
                    break;
                case JDAPProtocolOp.DEL_REQUEST:
                    connection.delete( dn, cons );
                    break;
                case JDAPProtocolOp.MODIFY_RDN_REQUEST:
                    connection.rename( dn, filter /* newRDN */, 
                                       attrsOnly /* deleteOld */, cons );
                    break;
                case JDAPProtocolOp.COMPARE_REQUEST:
                    boolean bool = connection.compare( dn, attr, cons );
                    results.addElement( new Boolean(bool) );
                    break;
                default:
                    /* impossible */
                    break;
            }
        } catch ( LDAPException ee ) {
            throw ee;
        } finally {
            if ( (connection != null) && 
                 ((ops != JDAPProtocolOp.SEARCH_REQUEST) || (res == null)) &&
                 ((_referralConnection == null) || 
                  !connection.equals(_referralConnection)) ) {
                connection.disconnect();
            }
        }
    }

    /**
     * Follows a referral for an extended operation
     *
     * @param e referral exception
     * @param cons search constraints
     */
    private LDAPExtendedOperation performExtendedReferrals(
        LDAPReferralException e,
        LDAPConstraints cons, LDAPExtendedOperation op )
        throws LDAPException {

        if ( cons.getHopLimit() <= 0 ) {
            throw new LDAPException( "exceed hop limit",
                                     e.getResultCode(),
                                     e.getLDAPErrorMessage() );
        }
        if ( !cons.getReferralFollowing() ) {
            throw e;
        }

        String[] u = e.getReferrals();
        // If there are no referrals (because the server isn't configured to
        // return one), give up here
        if ( (u == null) || (u.length == 0) ) {
            return null;
        }

        String connectList = createReferralConnectList( u );
        LDAPConnection connection = prepareReferral( connectList, cons );
        referralRebind( connection, cons );
        LDAPExtendedOperation results =
            connection.extendedOperation( op );
        connection.disconnect();
        return results; /* return right away if operation is successful */
        
    }

    /**
     * Sets up basic connection privileges for Communicator.
     * @return true if in Communicator and connections okay.
     */
    private static boolean checkCommunicator() {
        try {
            java.lang.reflect.Method m = LDAPCheckComm.getMethod(
                "netscape.security.PrivilegeManager", "enablePrivilege" );
            if ( m == null ) {
                printDebug( "Method is null" );
                return false;
            }

            Object[] args = new Object[1];
            args[0] = new String( "UniversalConnect" );
            m.invoke( null, args);
            printDebug( "UniversalConnect enabled" );
            args[0] = new String( "UniversalPropertyRead" );
            m.invoke( null, args);
            printDebug( "UniversalPropertyRead enabled" );
            return true;
        } catch ( LDAPException e ) {
            printDebug( "Exception: " + e.toString() );
        } catch ( Exception ie ) {
            printDebug( "Exception on invoking " + "enablePrivilege: " +
                        ie.toString() );
        }
        return false;
    }

    /**
     * Reports if the class is running in a Netscape browser.
     * @return <CODE>true</CODE> if the class is running in a Netscape browser.
     */
    public static boolean isNetscape() {
        return isCommunicator;
    }

    static void printDebug( String msg ) {
        if ( debug ) {
            System.out.println( msg );
        }
    }

    /**
     * Returns the string representation for this <CODE>LDAPConnection</CODE>.
     * <P>
     * For example:
     *
     * <PRE>LDAPConnection {ldap://dilly:389 (2) ldapVersion:3 bindDN:
     * "uid=admin,o=iplanet.com"}</PRE>
     * 
     * For cloned connections, the number of LDAPConnection instances sharing
     * the same physical connection is shown in parenthesis following the ldap
     * url. 
     * If an LDAPConnection objectis not cloned, this number is omitted from
     * the string representation.
     *
     * @return string representation of the connection
     * @see org.ietf.ldap.LDAPConnection#clone
     */    
    public String toString() {
        int cloneCnt = (_thread == null) ? 0 : _thread.getClientCount();
        StringBuffer sb = new StringBuffer( "LDAPConnection {" );
        //url
//        sb.append( (isSecure() ? "ldaps" : "ldap") );
        sb.append( "ldap" );
        sb.append( "://" );
        sb.append( getHost() );
        sb.append( ":" );
        sb.append( getPort() );
        // clone count
        if ( cloneCnt > 1 ) {
            sb.append( " (" );
            sb.append( cloneCnt );
            sb.append( ")" );
        }
        // ldap version
        sb.append( " ldapVersion:" );
        sb.append( _protocolVersion );
        // bind DN
        sb.append( " bindDN:\"" );
        if ( getAuthenticationDN() != null ) {
            sb.append( getAuthenticationDN() );
        }
        sb.append( "\"}" );
        
        return sb.toString();
    }
                                                                     
    /**
     * Prints out the LDAP Java SDK version and the highest LDAP
     * protocol version supported by the SDK. To view this
     * information, open a terminal window, and enter:
     * <PRE>java org.ietf.ldap.LDAPConnection
     * </PRE>
     * @param args not currently used
     */
    public static void main(String[] args) {
        System.out.println( "LDAP SDK Version is " + SdkVersion );
        System.out.println( "LDAP Protocol Version is " + ProtocolVersion );
    }

    /**
     * Option specifying the maximum number of unread results to be cached in
     * any LDAPSearchResults without suspending reading from the server
     * @see org.ietf.ldap.LDAPConnection#getOption
     * @see org.ietf.ldap.LDAPConnection#setOption
     */
    public static final int MAXBACKLOG = 30;

    private static boolean isCommunicator = checkCommunicator();
    private static boolean debug = false;
}