API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.management.remote.rmi. RMIConnector View Javadoc
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

/*
 * @(#)RMIConnector.java	1.129 06/01/26
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package javax.management.remote.rmi;

import com.sun.jmx.remote.internal.ClientCommunicatorAdmin;
import com.sun.jmx.remote.internal.ClientListenerInfo;
import com.sun.jmx.remote.internal.ClientNotifForwarder;
import com.sun.jmx.remote.internal.ProxyInputStream;
import com.sun.jmx.remote.internal.ProxyRef;
import com.sun.jmx.remote.util.ClassLogger;
import com.sun.jmx.remote.util.EnvHelp;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InvalidObjectException;
import java.io.NotSerializableException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.Serializable;
import java.io.WriteAbortedException;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.rmi.MarshalException;
import java.rmi.MarshalledObject;
import java.rmi.NoSuchObjectException;
import java.rmi.Remote;
import java.rmi.ServerException;
import java.rmi.UnmarshalException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RemoteObject;
import java.rmi.server.RemoteObjectInvocationHandler;
import java.rmi.server.RemoteRef;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.security.ProtectionDomain;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.WeakHashMap;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationFilterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnectionNotification;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.NotificationResult;
import javax.management.remote.JMXAddressable;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.CORBA.Stub;
import javax.rmi.PortableRemoteObject;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import javax.security.auth.Subject;
import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.ORB;
import sun.rmi.server.UnicastRef2;
import sun.rmi.transport.LiveRef;

/**
 * <p>A connection to a remote RMI connector.  Usually, such
 * connections are made using {@link
 * javax.management.remote.JMXConnectorFactory JMXConnectorFactory}.
 * However, specialized applications can use this class directly, for
 * example with an {@link RMIServer} stub obtained without going
 * through JNDI.</p>
 *
 * @since 1.5
 * @since.unbundled 1.0
 */
public class RMIConnector implements JMXConnector, Serializable, JMXAddressable {

    private static final ClassLogger logger =
	new ClassLogger("javax.management.remote.rmi", "RMIConnector");

    private static final long serialVersionUID = 817323035842634473L;

    private RMIConnector(RMIServer rmiServer, JMXServiceURL address,
                         Map environment) {
        if (rmiServer == null && address == null) throw new
          IllegalArgumentException("rmiServer and jmxServiceURL both null");

	initTransients();

	this.rmiServer = rmiServer;
        this.jmxServiceURL = address;
        if (environment == null) {
            this.env = Collections.EMPTY_MAP;
        } else {
            EnvHelp.checkAttributes(environment);
            this.env = Collections.unmodifiableMap(environment);
        }
    }

    /**
     * <p>Constructs an <code>RMIConnector</code> that will connect
     * the RMI connector server with the given address.</p>
     *
     * <p>The address can refer directly to the connector server,
     * using one of the following syntaxes:</p>
     *
     * <pre>
     * service:jmx:rmi://<em>[host[:port]]</em>/stub/<em>encoded-stub</em>
     * service:jmx:iiop://<em>[host[:port]]</em>/ior/<em>encoded-IOR</em>
     * </pre>
     *
     * <p>(Here, the square brackets <code>[]</code> are not part of the
     * address but indicate that the host and port are optional.)</p>
     *
     * <p>The address can instead indicate where to find an RMI stub
     * through JNDI, using one of the following syntaxes:</p>
     *
     * <pre>
     * service:jmx:rmi://<em>[host[:port]]</em>/jndi/<em>jndi-name</em>
     * service:jmx:iiop://<em>[host[:port]]</em>/jndi/<em>jndi-name</em>
     * </pre>
     *
     * <p>An implementation may also recognize additional address
     * syntaxes, for example:</p>
     *
     * <pre>
     * service:jmx:iiop://<em>[host[:port]]</em>/stub/<em>encoded-stub</em>
     * </pre>
     *
     * @param url the address of the RMI connector server.
     *
     * @param environment additional attributes specifying how to make
     * the connection.  For JNDI-based addresses, these attributes can
     * usefully include JNDI attributes recognized by {@link
     * InitialContext#InitialContext(Hashtable) InitialContext}.  This
     * parameter can be null, which is equivalent to an empty Map.
     *
     * @exception IllegalArgumentException if <code>url</code>
     * is null.
     */
    public RMIConnector(JMXServiceURL url, Map<String,?> environment) {
        this(null, url, environment);
    }

    /**
     * <p>Constructs an <code>RMIConnector</code> using the given RMI stub.
     *
     * @param rmiServer an RMI stub representing the RMI connector server.
     * @param environment additional attributes specifying how to make
     * the connection.  This parameter can be null, which is
     * equivalent to an empty Map.
     *
     * @exception IllegalArgumentException if <code>rmiServer</code>
     * is null.
     */
    public RMIConnector(RMIServer rmiServer, Map<String,?> environment) {
        this(rmiServer, null, environment);
    }

    /**
     * <p>Returns a string representation of this object.  In general,
     * the <code>toString</code> method returns a string that
     * "textually represents" this object. The result should be a
     * concise but informative representation that is easy for a
     * person to read.</p>
     *
     * @return a String representation of this object.
     **/
    public String toString() {
        final StringBuffer b = new StringBuffer(this.getClass().getName());
        b.append(":");
        if (rmiServer != null) {
            b.append(" rmiServer=").append(rmiServer.toString());
        }
        if (jmxServiceURL != null) {
            if (rmiServer!=null) b.append(",");
            b.append(" jmxServiceURL=").append(jmxServiceURL.toString());
        }
        return b.toString();
    }

    /**
     * <p>The address of this connector.</p>
     *
     * @return the address of this connector, or null if it
     * does not have one.
     *
     * @since 1.6
     */ 
    public JMXServiceURL getAddress() {
	return jmxServiceURL;
    }

    //--------------------------------------------------------------------
    // implements JMXConnector interface
    //--------------------------------------------------------------------
    public void connect() throws IOException {
	connect(null);
    }

    public synchronized void connect(Map<String,?> environment)
	    throws IOException {
	final boolean tracing = logger.traceOn();
	String        idstr   = (tracing?"["+this.toString()+"]":null);

        if (terminated) {
	    logger.trace("connect",idstr + " already closed.");
	    throw new IOException("Connector closed");
	}
        if (connected) {
	    logger.trace("connect",idstr + " already connected.");
            return;
	}

        try {
	    if (tracing) logger.trace("connect",idstr + " connecting...");

            final Map usemap =
		new HashMap((this.env==null)?Collections.EMPTY_MAP:this.env);

            if (environment != null) {
		EnvHelp.checkAttributes(environment);
                usemap.putAll(environment);
            }

            // Get RMIServer stub from directory or URL encoding if needed.
	    if (tracing) logger.trace("connect",idstr + " finding stub...");
            RMIServer stub = (rmiServer!=null)?rmiServer:
                findRMIServer(jmxServiceURL, usemap);

            // Check for secure RMIServer stub if the corresponding
            // client-side environment property is set to "true".
            //
            boolean checkStub = EnvHelp.computeBooleanFromString(
                usemap,
                "jmx.remote.x.check.stub");
            if (checkStub) checkStub(stub, rmiServerImplStubClass);

            // Connect IIOP Stub if needed.
	    if (tracing) logger.trace("connect",idstr + " connecting stub...");
            stub = connectStub(stub,usemap);
	    idstr = (tracing?"["+this.toString()+"]":null);

            // Calling newClient on the RMIServer stub.
	    if (tracing) 
		logger.trace("connect",idstr + " getting connection...");
	    Object credentials = usemap.get(CREDENTIALS);
            connection = getConnection(stub, credentials, checkStub);

            // Always use one of:
            //   ClassLoader provided in Map at connect time,
            //   or contextClassLoader at connect time.
	    if (tracing) 
		logger.trace("connect",idstr + " getting class loader...");
            defaultClassLoader = EnvHelp.resolveClientClassLoader(usemap);

            usemap.put(JMXConnectorFactory.DEFAULT_CLASS_LOADER,
                       defaultClassLoader);

	    rmiNotifClient = new RMINotifClient(defaultClassLoader, usemap);

	    env = usemap;
	    final long checkPeriod = EnvHelp.getConnectionCheckPeriod(usemap);
	    communicatorAdmin = new RMIClientCommunicatorAdmin(checkPeriod);

            connected = true;

	    // The connectionId variable is used in doStart(), when 
	    // reconnecting, to identify the "old" connection.
	    //
	    connectionId = getConnectionId();

	    Notification connectedNotif =
		new JMXConnectionNotification(JMXConnectionNotification.OPENED,
					      this,
					      connectionId,
					      clientNotifSeqNo++,
					      "Successful connection",
					      null);
	    sendNotification(connectedNotif);

	    if (tracing) logger.trace("connect",idstr + " done...");
        } catch (IOException e) {
	    if (tracing) 
		logger.trace("connect",idstr + " failed to connect: " + e);
            throw e;
        } catch (RuntimeException e) {
	    if (tracing) 
		logger.trace("connect",idstr + " failed to connect: " + e);
            throw e;
        } catch (NamingException e) {
            final String msg = "Failed to retrieve RMIServer stub: " + e;
	    if (tracing) logger.trace("connect",idstr + " " + msg);
            throw EnvHelp.initCause(new IOException(msg),e);
        }
    }

    public synchronized String getConnectionId() throws IOException {
        if (terminated || !connected) {
	    if (logger.traceOn())
		logger.trace("getConnectionId","["+this.toString()+
		      "] not connected.");

            throw new IOException("Not connected");
	}

	// we do a remote call to have an IOException if the connection is broken.
	// see the bug 4939578
	return connection.getConnectionId();
    }

    public synchronized MBeanServerConnection getMBeanServerConnection()
	    throws IOException {
	return getMBeanServerConnection(null);
    }

    public synchronized MBeanServerConnection
	getMBeanServerConnection(Subject delegationSubject)
	    throws IOException {

        if (terminated) {
	    if (logger.traceOn())
		logger.trace("getMBeanServerConnection","[" + this.toString() +
		      "] already closed.");
	    throw new IOException("Connection closed");
	} else if (!connected) {
	    if (logger.traceOn())
		logger.trace("getMBeanServerConnection","[" + this.toString() +
		      "] is not connected.");
	    throw new IOException("Not connected");
	}

	MBeanServerConnection mbsc =
	    (MBeanServerConnection) rmbscMap.get(delegationSubject);
	if (mbsc != null)
	    return mbsc;

	mbsc = new RemoteMBeanServerConnection(delegationSubject);
	rmbscMap.put(delegationSubject, mbsc);
	return mbsc;
    }

    public void
	addConnectionNotificationListener(NotificationListener listener,
					  NotificationFilter filter,
					  Object handback) {	
	if (listener == null) 
	    throw new NullPointerException("listener");
	connectionBroadcaster.addNotificationListener(listener, filter,
						      handback);
    }

    public void
	removeConnectionNotificationListener(NotificationListener listener)
	    throws ListenerNotFoundException {
	if (listener == null) 
	    throw new NullPointerException("listener");
	connectionBroadcaster.removeNotificationListener(listener);
    }

    public void
	removeConnectionNotificationListener(NotificationListener listener,
					     NotificationFilter filter,
					     Object handback)
	    throws ListenerNotFoundException {
	if (listener == null) 
	    throw new NullPointerException("listener");
	connectionBroadcaster.removeNotificationListener(listener, filter,
							 handback);
    }

    private void sendNotification(Notification n) {
	connectionBroadcaster.sendNotification(n);
    }

    public synchronized void close() throws IOException {
	close(false);
    }

    // allows to do close after setting the flag "terminated" to true.
    // It is necessary to avoid a deadlock, see 6296324
    private synchronized void close(boolean intern) throws IOException {			   
	final boolean tracing = logger.traceOn();
	final boolean debug   = logger.debugOn();
	final String  idstr   = (tracing?"["+this.toString()+"]":null);

	if (!intern) {
	    // Return if already cleanly closed.
	    //
	    if (terminated) {
		if (closeException == null) {
		    if (tracing) logger.trace("close",idstr + " already closed.");
		    return;
		}
	    } else {
		terminated = true;
	    }
	}

	if (closeException != null && tracing) {
	    // Already closed, but not cleanly. Attempt again.
	    //
	    if (tracing) {
		logger.trace("close",idstr + " had failed: " + closeException);
		logger.trace("close",idstr + " attempting to close again.");
	    }
	}

        String savedConnectionId = null;
	if (connected) {
	    savedConnectionId = connectionId;
	}

	closeException = null;

	if (tracing) logger.trace("close",idstr + " closing.");

	if (communicatorAdmin != null) {
	    communicatorAdmin.terminate();
	}

	if (rmiNotifClient != null) {
	    try {
		rmiNotifClient.terminate();
		if (tracing) logger.trace("close",idstr +
				    " RMI Notification client terminated.");
	    } catch (RuntimeException x) {
		closeException = x;
		if (tracing) logger.trace("close",idstr +
			 " Failed to terminate RMI Notification client: " + x);
		if (debug) logger.debug("close",x);
	    }
	}

	if (connection != null) {
	    try {
		connection.close();
		if (tracing) logger.trace("close",idstr + " closed.");
	    } catch (NoSuchObjectException nse) {
		// OK, the server maybe closed itself.
	    } catch (IOException e) {
		closeException = e;
		if (tracing) logger.trace("close",idstr +
					  " Failed to close RMIServer: " + e);
		if (debug) logger.debug("close",e);
	    }
	}

	// Clean up MBeanServerConnection table
	//
	rmbscMap.clear();

	/* Send notification of closure.  We don't do this if the user
	 * never called connect() on the connector, because there's no
	 * connection id in that case.  */

	if (savedConnectionId != null) {
	    Notification closedNotif =
		new JMXConnectionNotification(JMXConnectionNotification.CLOSED,
					      this,
					      savedConnectionId,
					      clientNotifSeqNo++,
					      "Client has been closed",
					      null);
	    sendNotification(closedNotif);
	}

	// throw exception if needed
	//
	if (closeException != null) {
	    if (tracing) logger.trace("close",idstr + " failed to close: " +
			       closeException);
	    if (closeException instanceof IOException)
		throw (IOException) closeException;
	    if (closeException instanceof RuntimeException)
		throw (RuntimeException) closeException;
	    final IOException x =
		new IOException("Failed to close: " + closeException);
	    throw EnvHelp.initCause(x,closeException);
	}
    }

    // added for re-connection
    private Integer addListenerWithSubject(ObjectName name,
					   MarshalledObject filter,
					   Subject delegationSubject,
					   boolean reconnect)
	throws InstanceNotFoundException, IOException {
	    
	final boolean debug = logger.debugOn();
	if (debug)
	    logger.debug("addListenerWithSubject",
			 "(ObjectName,MarshalledObject,Subject)");	
	    
	final ObjectName[] names = new ObjectName[] {name};
	final MarshalledObject[] filters = new MarshalledObject[] {filter};
	final Subject[] delegationSubjects = new Subject[] {
	    delegationSubject
	};

	final Integer[] listenerIDs =
	    addListenersWithSubjects(names,filters,delegationSubjects,
					  reconnect);
	    
	if (debug) logger.debug("addListenerWithSubject","listenerID="
				+ listenerIDs[0]);
	return listenerIDs[0];
    }

    // added for re-connection
    private Integer[] addListenersWithSubjects(ObjectName[]       names,
			     MarshalledObject[] filters,
			     Subject[]          delegationSubjects,
			     boolean            reconnect) 
	throws InstanceNotFoundException, IOException {

	final boolean debug = logger.debugOn();
	if (debug)
	logger.debug("addListenersWithSubjects",
			 "(ObjectName[],MarshalledObject[],Subject[])");

	final ClassLoader old = pushDefaultClassLoader();
	Integer[] listenerIDs = null;

	try {
	    listenerIDs = connection.addNotificationListeners(names,
							      filters,
							  delegationSubjects);
	} catch (NoSuchObjectException noe) {
	    // maybe reconnect
	    if (reconnect) {
		communicatorAdmin.gotIOException(noe);
		
		listenerIDs = connection.addNotificationListeners(names,
						       filters,
						       delegationSubjects);
	    } else {
		throw noe;
	    }
	} catch (IOException ioe) {
	    // send a failed notif if necessary
	    communicatorAdmin.gotIOException(ioe);
	} finally {
	    popDefaultClassLoader(old);
	}
	    
	if (debug) logger.debug("addListenersWithSubjects","registered "
				+ listenerIDs.length + " listener(s)");
	return listenerIDs;
    }

    //--------------------------------------------------------------------
    // Implementation of MBeanServerConnection
    //--------------------------------------------------------------------
    private class RemoteMBeanServerConnection
        implements MBeanServerConnection {

	private Subject delegationSubject;

	public RemoteMBeanServerConnection() {
	    this(null);
	}

	public RemoteMBeanServerConnection(Subject delegationSubject) {
	    this.delegationSubject = delegationSubject;
	}

        public ObjectInstance createMBean(String className,
                                          ObjectName name)
                throws ReflectionException,
                       InstanceAlreadyExistsException,
                       MBeanRegistrationException,
                       MBeanException,
                       NotCompliantMBeanException,
                       IOException {
	    if (logger.debugOn()) 
		logger.debug("createMBean(String,ObjectName)",
			     "className=" + className + ", name=" +
			     name);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.createMBean(className,
					     name,
					     delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.createMBean(className,
					     name,
					     delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public ObjectInstance createMBean(String className,
                                          ObjectName name,
                                          ObjectName loaderName)
            throws ReflectionException,
                       InstanceAlreadyExistsException,
                       MBeanRegistrationException,
                       MBeanException,
                       NotCompliantMBeanException,
                       InstanceNotFoundException,
                       IOException {

	    if (logger.debugOn())
		logger.debug("createMBean(String,ObjectName,ObjectName)",
		      "className=" + className + ", name="
		      + name + ", loaderName="
		      + loaderName + ")");

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.createMBean(className,
					     name,
					     loaderName,
					     delegationSubject);

	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.createMBean(className,
					     name,
					     loaderName,
					     delegationSubject);

            } finally {
                popDefaultClassLoader(old);
            }
        }

        public ObjectInstance createMBean(String className,
                                          ObjectName name,
                                          Object params[],
                                          String signature[])
                throws ReflectionException,
                       InstanceAlreadyExistsException,
                       MBeanRegistrationException,
                       MBeanException,
                       NotCompliantMBeanException,
                       IOException {
	    if (logger.debugOn())
	       logger.debug("createMBean(String,ObjectName,Object[],String[])",
		      "className=" + className + ", name="
		      + name + ", params="
		      + objects(params) + ", signature="
		      + strings(signature));

            final MarshalledObject sParams = new MarshalledObject(params);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.createMBean(className,
					     name,
					     sParams,
					     signature,
					     delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.createMBean(className,
					     name,
					     sParams,
					     signature,
					     delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public ObjectInstance createMBean(String className,
                                          ObjectName name,
                                          ObjectName loaderName,
                                          Object params[],
                                          String signature[])
                throws ReflectionException,
                       InstanceAlreadyExistsException,
                       MBeanRegistrationException,
                       MBeanException,
                       NotCompliantMBeanException,
                       InstanceNotFoundException,
                       IOException {
	    if (logger.debugOn()) logger.debug(
		"createMBean(String,ObjectName,ObjectName,Object[],String[])",
		"className=" + className + ", name=" + name + ", loaderName=" 
		+ loaderName + ", params=" + objects(params)
		+ ", signature=" + strings(signature));

            final MarshalledObject sParams = new MarshalledObject(params);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.createMBean(className,
					     name,
					     loaderName,
					     sParams,
					     signature,
					     delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.createMBean(className,
					     name,
					     loaderName,
					     sParams,
					     signature,
					     delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public void unregisterMBean(ObjectName name)
                throws InstanceNotFoundException,
                       MBeanRegistrationException,
                       IOException {
	    if (logger.debugOn()) 
		logger.debug("unregisterMBean", "name=" + name);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.unregisterMBean(name, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.unregisterMBean(name, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public ObjectInstance getObjectInstance(ObjectName name)
                throws InstanceNotFoundException,
                       IOException {
	    if (logger.debugOn()) 
		logger.debug("getObjectInstance", "name=" + name);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getObjectInstance(name, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getObjectInstance(name, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public Set queryMBeans(ObjectName name,
                               QueryExp query)
            throws IOException {
	    if (logger.debugOn()) logger.debug("queryMBeans",
				   "name=" + name + ", query=" + query);

            final MarshalledObject sQuery = new MarshalledObject(query);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.queryMBeans(name, sQuery, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.queryMBeans(name, sQuery, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public Set queryNames(ObjectName name,
                              QueryExp query)
                throws IOException {
	    if (logger.debugOn()) logger.debug("queryNames",
				   "name=" + name + ", query=" + query);

            final MarshalledObject sQuery = new MarshalledObject(query);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.queryNames(name, sQuery, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.queryNames(name, sQuery, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public boolean isRegistered(ObjectName name)
                throws IOException {
	    if (logger.debugOn()) 
		logger.debug("isRegistered", "name=" + name);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.isRegistered(name, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.isRegistered(name, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public Integer getMBeanCount()
                throws IOException {
	    if (logger.debugOn()) logger.debug("getMBeanCount", "");

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getMBeanCount(delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getMBeanCount(delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public Object getAttribute(ObjectName name,
                                   String attribute)
                throws MBeanException,
                       AttributeNotFoundException,
                       InstanceNotFoundException,
                       ReflectionException,
                       IOException {
	    if (logger.debugOn()) logger.debug("getAttribute",
				   "name=" + name + ", attribute="
				   + attribute);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getAttribute(name,
					      attribute,
					      delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getAttribute(name,
					      attribute,
					      delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public AttributeList getAttributes(ObjectName name,
                                           String[] attributes)
                throws InstanceNotFoundException,
                       ReflectionException,
                       IOException {
	    if (logger.debugOn()) logger.debug("getAttributes",
				   "name=" + name + ", attributes="
				   + strings(attributes));

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getAttributes(name,
					       attributes,
					       delegationSubject);

	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getAttributes(name,
					       attributes,
					       delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }


        public void setAttribute(ObjectName name,
                                 Attribute attribute)
            throws InstanceNotFoundException,
                   AttributeNotFoundException,
                   InvalidAttributeValueException,
                   MBeanException,
                   ReflectionException,
                   IOException {

	    if (logger.debugOn()) logger.debug("setAttribute",
				   "name=" + name + ", attribute="
				   + attribute);

            final MarshalledObject sAttribute =
		new MarshalledObject(attribute);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.setAttribute(name, sAttribute, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.setAttribute(name, sAttribute, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public AttributeList setAttributes(ObjectName name,
                                           AttributeList attributes)
            throws InstanceNotFoundException,
                   ReflectionException,
                   IOException {

	    if (logger.debugOn()) logger.debug("setAttributes",
				   "name=" + name + ", attributes="
				   + attributes);

            final MarshalledObject sAttributes =
                new MarshalledObject(attributes);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.setAttributes(name,
					       sAttributes,
					       delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.setAttributes(name,
					       sAttributes,
					       delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }


        public Object invoke(ObjectName name,
                             String operationName,
                             Object params[],
                             String signature[])
                throws InstanceNotFoundException,
                       MBeanException,
                       ReflectionException,
                       IOException {

	    if (logger.debugOn()) logger.debug("invoke",
				   "name=" + name
				   + ", operationName=" + operationName
				   + ", params=" + objects(params)
				   + ", signature=" + strings(signature));

            final MarshalledObject sParams = new MarshalledObject(params);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.invoke(name,
					operationName,
					sParams,
                                        signature,
					delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.invoke(name,
					operationName,
					sParams,
                                        signature,
					delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }


        public String getDefaultDomain()
                throws IOException {
	    if (logger.debugOn()) logger.debug("getDefaultDomain", "");

            final ClassLoader old = pushDefaultClassLoader();
            try {
		return connection.getDefaultDomain(delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

		return connection.getDefaultDomain(delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public String[] getDomains() throws IOException {
	    if (logger.debugOn()) logger.debug("getDomains", "");

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getDomains(delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getDomains(delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public MBeanInfo getMBeanInfo(ObjectName name)
                throws InstanceNotFoundException,
                       IntrospectionException,
                       ReflectionException,
                       IOException {

	    if (logger.debugOn()) logger.debug("getMBeanInfo", "name=" + name);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.getMBeanInfo(name, delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.getMBeanInfo(name, delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }


        public boolean isInstanceOf(ObjectName name,
                                    String className)
                throws InstanceNotFoundException,
                       IOException {
	    if (logger.debugOn()) 
		logger.debug("isInstanceOf", "name=" + name + 
			     ", className=" + className);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                return connection.isInstanceOf(name,
					      className,
					      delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                return connection.isInstanceOf(name,
					      className,
					      delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public void addNotificationListener(ObjectName name,
                                            ObjectName listener,
                                            NotificationFilter filter,
                                            Object handback)
                throws InstanceNotFoundException,
                       IOException {

	    if (logger.debugOn()) 
		logger.debug("addNotificationListener" +
		       "(ObjectName,ObjectName,NotificationFilter,Object)",
		       "name=" + name + ", listener=" + listener 
		       + ", filter=" + filter + ", handback=" + handback);

            final MarshalledObject sFilter = new MarshalledObject(filter);
            final MarshalledObject sHandback = new MarshalledObject(handback);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.addNotificationListener(name,
						  listener,
						  sFilter,
						  sHandback,
						  delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.addNotificationListener(name,
						  listener,
						  sFilter,
						  sHandback,
						  delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public void removeNotificationListener(ObjectName name,
                                               ObjectName listener)
                throws InstanceNotFoundException,
                       ListenerNotFoundException,
                       IOException {

	    if (logger.debugOn()) logger.debug("removeNotificationListener" +
				   "(ObjectName,ObjectName)",
				   "name=" + name
				   + ", listener=" + listener);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.removeNotificationListener(name,
						     listener,
						     delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.removeNotificationListener(name,
						     listener,
						     delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        public void removeNotificationListener(ObjectName name,
                                               ObjectName listener,
                                               NotificationFilter filter,
                                               Object handback)
                throws InstanceNotFoundException,
                       ListenerNotFoundException,
                       IOException {
	    if (logger.debugOn())
		logger.debug("removeNotificationListener" +
		      "(ObjectName,ObjectName,NotificationFilter,Object)",
		      "name=" + name
		      + ", listener=" + listener
		      + ", filter=" + filter
		      + ", handback=" + handback);

            final MarshalledObject sFilter = new MarshalledObject(filter);
            final MarshalledObject sHandback = new MarshalledObject(handback);
            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.removeNotificationListener(name,
						     listener,
                                                     sFilter,
						     sHandback,
						     delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.removeNotificationListener(name,
						     listener,
                                                     sFilter,
						     sHandback,
						     delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }
        }

        // Specific Notification Handle ----------------------------------

        public void addNotificationListener(ObjectName name,
                                            NotificationListener listener,
                                            NotificationFilter filter,
                                            Object handback)
                throws InstanceNotFoundException,
                       IOException {

	    final boolean debug = logger.debugOn();
	    if (debug)
		logger.debug("addNotificationListener" +
			     "(ObjectName,NotificationListener,"+
			     "NotificationFilter,Object)",
			     "name=" + name
			     + ", listener=" + listener
			     + ", filter=" + filter
			     + ", handback=" + handback);

	    final Integer listenerID = 
		addListenerWithSubject(name, new MarshalledObject(filter), 
				       delegationSubject,true);
	    rmiNotifClient.addNotificationListener(listenerID, name, listener,
						   filter, handback, 
						   delegationSubject);
	}

        public void removeNotificationListener(ObjectName name,
                                               NotificationListener listener)
                throws InstanceNotFoundException,
                       ListenerNotFoundException,
                       IOException {
	    final boolean debug = logger.debugOn();

	    if (debug) logger.debug("removeNotificationListener"+
			     "(ObjectName,NotificationListener)",
			     "name=" + name
			     + ", listener=" + listener);

            final Integer[] ret =
                rmiNotifClient.removeNotificationListener(name, listener);

	    if (debug) logger.debug("removeNotificationListener",
			     "listenerIDs=" + objects(ret));

            final ClassLoader old = pushDefaultClassLoader();

            try {
                connection.removeNotificationListeners(name,
						       ret,
						       delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.removeNotificationListeners(name,
						       ret,
						       delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }

        }

        public void removeNotificationListener(ObjectName name,
                                           NotificationListener listener,
                                           NotificationFilter filter,
                                           Object handback)
            throws InstanceNotFoundException,
                   ListenerNotFoundException,
                   IOException {
	    final boolean debug = logger.debugOn();

	    if (debug)
		logger.debug("removeNotificationListener"+
		      "(ObjectName,NotificationListener,"+
		      "NotificationFilter,Object)",
		      "name=" + name
		      + ", listener=" + listener
		      + ", filter=" + filter
		      + ", handback=" + handback);

            final Integer ret =
                rmiNotifClient.removeNotificationListener(name, listener,
                                                         filter, handback);

	    if (debug) logger.debug("removeNotificationListener",
			     "listenerID=" + ret);

            final ClassLoader old = pushDefaultClassLoader();
            try {
                connection.removeNotificationListeners(name,
						       new Integer[] {ret},
						       delegationSubject);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

                connection.removeNotificationListeners(name,
						       new Integer[] {ret},
						       delegationSubject);
            } finally {
                popDefaultClassLoader(old);
            }

        }
    }

    //--------------------------------------------------------------------
    private class RMINotifClient extends ClientNotifForwarder {
	public RMINotifClient(ClassLoader cl, Map env) {
	    super(cl, env);
	}

	protected NotificationResult fetchNotifs(long clientSequenceNumber,
						 int maxNotifications,
						 long timeout)
		throws IOException, ClassNotFoundException {
	    IOException org;

	    while (true) { // used for a successful re-connection
		try {
		    return connection.fetchNotifications(clientSequenceNumber,
							 maxNotifications,
							 timeout);
		} catch (IOException ioe) {
		    org = ioe;
		    
		    // inform of IOException
		    try {
			communicatorAdmin.gotIOException(ioe);
			
			// The connection should be re-established.
			continue;
		    } catch (IOException ee) {
			// No more fetch, the Exception will be re-thrown.
			break;
		    } // never reached
		} // never reached
	    }

	    // specially treating for an UnmarshalException 
	    if (org instanceof UnmarshalException) {
		UnmarshalException ume = (UnmarshalException)org;
		
		if (ume.detail instanceof ClassNotFoundException)
		    throw (ClassNotFoundException) ume.detail;
		
		/* In Sun's RMI implementation, if a method return
		   contains an unserializable object, then we get
		   UnmarshalException wrapping WriteAbortedException
		   wrapping NotSerializableException.  In that case we
		   extract the NotSerializableException so that our
		   caller can realize it should try to skip past the
		   notification that presumably caused it.  It's not
		   certain that every other RMI implementation will
		   generate this exact exception sequence.  If not, we
		   will not detect that the problem is due to an
		   unserializable object, and we will stop trying to
		   receive notifications from the server.  It's not
		   clear we can do much better.  */
		if (ume.detail instanceof WriteAbortedException) {
		    WriteAbortedException wae =
			(WriteAbortedException) ume.detail;
		    if (wae.detail instanceof IOException)
			throw (IOException) wae.detail;
		}
	    } else if (org instanceof MarshalException) {
		// IIOP will throw MarshalException wrapping a NotSerializableException
		// when a server fails to serialize a response.
		MarshalException me = (MarshalException)org;
		if (me.detail instanceof NotSerializableException) {
		    throw (NotSerializableException)me.detail;
		}
	    }

	    // Not serialization problem, simply re-throw the orginal exception
	    throw org;
	}

	protected Integer addListenerForMBeanRemovedNotif()
		throws IOException, InstanceNotFoundException {
	    MarshalledObject sFilter = null;
	    NotificationFilterSupport clientFilter =
		new NotificationFilterSupport();
	    clientFilter.enableType(
		MBeanServerNotification.UNREGISTRATION_NOTIFICATION);
	    sFilter = new MarshalledObject(clientFilter);

	    Integer[] listenerIDs;
	    final ObjectName[] names =
                new ObjectName[] {MBeanServerDelegate.DELEGATE_NAME};
	    final MarshalledObject[] filters =
		new MarshalledObject[] {sFilter};
	    final Subject[] subjects = new Subject[] {null};
	    try {
		listenerIDs =
		    connection.addNotificationListeners(names,
							filters,
							subjects);

	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

		listenerIDs =
		    connection.addNotificationListeners(names,
							filters,
							subjects);
	    }
	    return listenerIDs[0];
	}

	protected void removeListenerForMBeanRemovedNotif(Integer id)
		throws IOException, InstanceNotFoundException,
		       ListenerNotFoundException {
	    try {
		connection.removeNotificationListeners(
                                             MBeanServerDelegate.DELEGATE_NAME,
					     new Integer[] {id},
					     null);
	    } catch (IOException ioe) {
		communicatorAdmin.gotIOException(ioe);

		connection.removeNotificationListeners(
                                             MBeanServerDelegate.DELEGATE_NAME,
					     new Integer[] {id},
					     null);
	    }

	}

	protected void lostNotifs(String message, long number) {
	    final String notifType = JMXConnectionNotification.NOTIFS_LOST;

	    final JMXConnectionNotification n =
		new JMXConnectionNotification(notifType,
					      RMIConnector.this,
					      connectionId,
					      clientNotifCounter++,
					      message,
					      new Long(number));
	    sendNotification(n);
	}
    }

    private class RMIClientCommunicatorAdmin extends ClientCommunicatorAdmin {
	public RMIClientCommunicatorAdmin(long period) {
	    super(period);
	}

	public void gotIOException (IOException ioe) throws IOException {
	    if (ioe instanceof NoSuchObjectException) {
		// need to restart
		super.gotIOException(ioe);

		return;
	    }

	    // check if the connection is broken
            try {
		connection.getDefaultDomain(null);
	    } catch (IOException ioexc) {
	        boolean toClose = false;

		synchronized(this) {
		    if (!terminated) {
			terminated = true;

			toClose = true;
		    }	
		}    	    
 
		if (toClose) {
		    // we should close the connection,
		    // but send a failed notif at first
		    final Notification failedNotif =
			new JMXConnectionNotification(
			    JMXConnectionNotification.FAILED,
			    this,
			    connectionId,
			    clientNotifSeqNo++,
			    "Failed to communicate with the server: "+ioe.toString(),
			    ioe);

		    sendNotification(failedNotif);

		    try {
			close(true);
		    } catch (Exception e) {
			// OK.
			// We are closing
		    }
		}
	    }

	    // forward the exception
	    if (ioe instanceof ServerException) {
		/* Need to unwrap the exception.
		   Some user-thrown exception at server side will be wrapped by
		   rmi into a ServerException.
		   For example, a RMIConnnectorServer will wrap a
		   ClassNotFoundException into a UnmarshalException, and rmi
		   will throw a ServerException at client side which wraps this
		   UnmarshalException.
		   No failed notif here.
		*/
		Throwable tt = ((ServerException)ioe).detail;

		if (tt instanceof IOException) {
		    throw (IOException)tt;
		} else if (tt instanceof RuntimeException) {
		    throw (RuntimeException)tt;
		}
	    }

	    throw ioe;
	}

	public void reconnectNotificationListeners(ClientListenerInfo[] old) throws IOException {
	    final int len  = old.length;
	    int i;

	    ClientListenerInfo[] clis = new ClientListenerInfo[len];

	    final Subject[] subjects = new Subject[len];
	    final ObjectName[] names = new ObjectName[len];
	    final NotificationListener[] listeners = new NotificationListener[len];
	    final NotificationFilter[] filters = new NotificationFilter[len];
	    final MarshalledObject[] mFilters = new MarshalledObject[len];
	    final Object[] handbacks = new Object[len];
	   
	    for (i=0;i<len;i++) {
		subjects[i]  = old[i].getDelegationSubject();
		names[i]     = old[i].getObjectName();
		listeners[i] = old[i].getListener();
		filters[i]   = old[i].getNotificationFilter();
		mFilters[i]  = new MarshalledObject(filters[i]);
		handbacks[i] = old[i].getHandback();
	    }

	    try {
		Integer[] ids = addListenersWithSubjects(names,mFilters,subjects,false);

		for (i=0;i<len;i++) {
		    clis[i] = new ClientListenerInfo(ids[i],
						     names[i],
						     listeners[i],
						     filters[i],
						     handbacks[i],
						     subjects[i]);
		}

		rmiNotifClient.postReconnection(clis);

		return;
	    } catch (InstanceNotFoundException infe) {
		// OK, we will do one by one
	    }

	    int j = 0;
	    for (i=0;i<len;i++) {
		try {
		    Integer id = addListenerWithSubject(names[i],
					   new MarshalledObject(filters[i]),
					   subjects[i],
					   false);

		    clis[j++] = new ClientListenerInfo(id,
						       names[i],
						       listeners[i],
						       filters[i],
						       handbacks[i],
						       subjects[i]);
		} catch (InstanceNotFoundException infe) {
		    logger.warning("reconnectNotificationListeners",
				   "Can't reconnect listener for " +
				   names[i]);
		}
	    }

	    if (j != len) {
		ClientListenerInfo[] tmp = clis;
		clis = new ClientListenerInfo[j];
		System.arraycopy(tmp, 0, clis, 0, j);
	    }

	    rmiNotifClient.postReconnection(clis);
	}

	protected void checkConnection() throws IOException {
	    if (logger.debugOn()) 
		logger.debug("RMIClientCommunicatorAdmin-checkConnection", 
			     "Calling the method getDefaultDomain.");

	    connection.getDefaultDomain(null);
	}

	protected void doStart() throws IOException {
            // Get RMIServer stub from directory or URL encoding if needed.
	    RMIServer stub = null;
	    try {
	        stub = (rmiServer!=null)?rmiServer:
		    findRMIServer(jmxServiceURL, env);
	    } catch (NamingException ne) {
		throw new IOException("Failed to get a RMI stub: "+ne);
	    }

            // Connect IIOP Stub if needed.
            stub = connectStub(stub,env);

            // Calling newClient on the RMIServer stub.
	    Object credentials = env.get(CREDENTIALS);
            connection = stub.newClient(credentials);

	    // notif issues
	    final ClientListenerInfo[] old = rmiNotifClient.preReconnection();

	    reconnectNotificationListeners(old);

	    connectionId = getConnectionId();

	    Notification reconnectedNotif =
		new JMXConnectionNotification(JMXConnectionNotification.OPENED,
					      this,
					      connectionId,
					      clientNotifSeqNo++,
					      "Reconnected to server",
					      null);
	    sendNotification(reconnectedNotif);

	}

	protected void doStop() {
	    try {
		close();
	    } catch (IOException ioe) {
		logger.warning("RMIClientCommunicatorAdmin-doStop",
			       "Failed to call the method close():" + ioe);
		logger.debug("RMIClientCommunicatorAdmin-doStop",ioe);
	    }
	}
    }

    //--------------------------------------------------------------------
    // Private stuff - Serialization
    //--------------------------------------------------------------------
    /**
     * <p>In order to be usable, an IIOP stub must be connected to an ORB.
     * The stub is automatically connected to the ORB if:
     * <ul>
     *     <li> It was returned by the COS naming</li>
     *     <li> Its server counterpart has been registered in COS naming
     *          through JNDI.</li>
     * </ul>
     * Otherwise, it is not connected. A stub which is deserialized
     * from Jini is not connected. A stub which is obtained from a
     * non registered RMIIIOPServerImpl is not a connected.<br>
     * A stub which is not connected can't be serialized, and thus
     * can't be registered in Jini. A stub which is not connected can't
     * be used to invoke methods on the server.
     * <p>
     * In order to palliate this, this method will connect the
     * given stub if it is not yet connected. If the given
     * <var>RMIServer</var> is not an instance of
     * {@link javax.rmi.CORBA.Stub javax.rmi.CORBA.Stub}, then the
     * method do nothing and simply returns that stub. Otherwise,
     * this method will attempt to connect the stub to an ORB as
     * follows:
     * <ul>
     * <p>This method looks in the provided <var>environment</var> for
     * the "java.naming.corba.orb" property. If it is found, the
     * referenced object (an {@link org.omg.CORBA.ORB ORB}) is used to
     * connect the stub. Otherwise, a new org.omg.CORBA.ORB is created
     * by calling {@link
     * org.omg.CORBA.ORB#init(String[], Properties)
     * org.omg.CORBA.ORB.init((String[])null,(Properties)null)}
     * <p>The new created ORB is kept in a static
     * {@link WeakReference} and can be reused for connecting other
     * stubs. However, no reference is ever kept on the ORB provided
     * in the <var>environment</var> map, if any.
     * </ul>
     * @param rmiServer A RMI Server Stub.
     * @param environment An environment map, possibly containing an ORB.
     * @return the given stub.
     * @exception IllegalArgumentException if the
     *      <tt>java.naming.corba.orb</tt> property is specified and
     *      does not point to an {@link org.omg.CORBA.ORB ORB}.
     * @exception IOException if the connection to the ORB failed.
     **/
    static RMIServer connectStub(RMIServer rmiServer,
                                 Map environment)
        throws IOException {
        if (rmiServer instanceof javax.rmi.CORBA.Stub) {
            javax.rmi.CORBA.Stub stub = (javax.rmi.CORBA.Stub) rmiServer;
            try {
                stub._orb();
            } catch (BAD_OPERATION x) {
                stub.connect(resolveOrb(environment));
            }
        }
        return rmiServer;
    }

    /**
     * Get the ORB specified by <var>environment</var>, or create a
     * new one.
     * <p>This method looks in the provided <var>environment</var> for
     * the "java.naming.corba.orb" property. If it is found, the
     * referenced object (an {@link org.omg.CORBA.ORB ORB}) is
     * returned. Otherwise, a new org.omg.CORBA.ORB is created
     * by calling {@link
     * org.omg.CORBA.ORB#init(String[], java.util.Properties)
     * org.omg.CORBA.ORB.init((String[])null,(Properties)null)}
     * <p>The new created ORB is kept in a static
     * {@link WeakReference} and can be reused for connecting other
     * stubs. However, no reference is ever kept on the ORB provided
     * in the <var>environment</var> map, if any.
     * @param environment An environment map, possibly containing an ORB.
     * @return An ORB.
     * @exception IllegalArgumentException if the
     *      <tt>java.naming.corba.orb</tt> property is specified and
     *      does not point to an {@link org.omg.CORBA.ORB ORB}.
     * @exception IOException if the ORB initialization failed.
     **/
    static ORB resolveOrb(Map environment)
        throws IOException {
        if (environment != null) {
            final Object orb = environment.get(EnvHelp.DEFAULT_ORB);
            if (orb != null && !(orb instanceof  ORB))
                throw new IllegalArgumentException(EnvHelp.DEFAULT_ORB +
                          " must be an instance of org.omg.CORBA.ORB.");
            if (orb != null) return (ORB)orb;
        }
        final ORB orb =
            (RMIConnector.orb==null)?null:RMIConnector.orb.get();
        if (orb != null) return orb;

        final ORB newOrb =
            ORB.init((String[])null, (Properties)null);
        RMIConnector.orb = new WeakReference(newOrb);
        return newOrb;
    }
    
    /**
     * Read RMIConnector fields from an {@link java.io.ObjectInputStream
     * ObjectInputStream}.
     * Calls <code>s.defaultReadObject()</code> and then initializes
     * all transient variables that need initializing.
     * @param s The ObjectInputStream to read from.
     * @exception InvalidObjectException if none of <var>rmiServer</var> stub
     *    or <var>jmxServiceURL</var> are set.
     * @see #RMIConnector(JMXServiceURL,Map)
     * @see #RMIConnector(RMIServer,Map)
     **/
    private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException  {
        s.defaultReadObject();

        if (rmiServer == null && jmxServiceURL == null) throw new
          InvalidObjectException("rmiServer and jmxServiceURL both null");

	initTransients();
    }

    /**
     * Writes the RMIConnector fields to an {@link java.io.ObjectOutputStream
     * ObjectOutputStream}.
     * <p>Connects the underlying RMIServer stub to an ORB, if needed,
     * before serializing it. This is done using the environment
     * map that was provided to the constructor, if any, and as documented
     * in {@link javax.management.remote.rmi}.</p>
     * <p>This method then calls <code>s.defaultWriteObject()</code>.
     * Usually, <var>rmiServer</var> is null if this object
     * was constructed with a JMXServiceURL, and <var>jmxServiceURL</var>
     * is null if this object is constructed with a RMIServer stub.
     * <p>Note that the environment Map is not serialized, since the objects
     * it contains are assumed to be contextual and relevant only
     * with respect to the local environment (class loader, ORB, etc...).</p>
     * <p>After an RMIConnector is deserialized, it is assumed that the
     * user will call {@link #connect(Map)}, providing a new Map that
     * can contain values which are contextually relevant to the new
     * local environment.</p>
     * <p>Since connection to the ORB is needed prior to serializing, and
     * since the ORB to connect to is one of those contextual parameters,
     * it is not recommended to re-serialize a just de-serialized object -
     * as the de-serialized object has no map. Thus, when an RMIConnector
     * object is needed for serialization or transmission to a remote
     * application, it is recommended to obtain a new RMIConnector stub
     * by calling {@link RMIConnectorServer#toJMXConnector(Map)}.</p>
     * @param s The ObjectOutputStream to write to.
     * @exception InvalidObjectException if none of <var>rmiServer</var> stub
     *    or <var>jmxServiceURL</var> are set.
     * @see #RMIConnector(JMXServiceURL,Map)
     * @see #RMIConnector(RMIServer,Map)
     **/
    private void writeObject(java.io.ObjectOutputStream s)
        throws IOException {
        if (rmiServer == null && jmxServiceURL == null) throw new
          InvalidObjectException("rmiServer and jmxServiceURL both null.");
        connectStub(this.rmiServer,env);
        s.defaultWriteObject();
    }

    // Initialization of transient variables.
    private void initTransients() {
	rmbscMap = new WeakHashMap();
        connected = false;
        terminated = false;

	connectionBroadcaster = new NotificationBroadcasterSupport();
    }

    //--------------------------------------------------------------------
    // Private stuff - Check if stub can be trusted.
    //--------------------------------------------------------------------

    private static void checkStub(Remote stub,
                                  Class<? extends Remote> stubClass) {

        // Check remote stub is from the expected class.
        //
        if (stub.getClass() != stubClass) {
            if (!Proxy.isProxyClass(stub.getClass())) {
                throw new SecurityException(
                          "Expecting a " + stubClass.getName() + " stub!");
            } else {
                InvocationHandler handler = Proxy.getInvocationHandler(stub);
                if (handler.getClass() != RemoteObjectInvocationHandler.class)
                    throw new SecurityException(
                              "Expecting a dynamic proxy instance with a " +
                              RemoteObjectInvocationHandler.class.getName() +
                              " invocation handler!");
                else
                    stub = (Remote) handler;
            }
        }

        // Check RemoteRef in stub is from the expected class
        // "sun.rmi.server.UnicastRef2".
        //
        RemoteRef ref = ((RemoteObject)stub).getRef();
        if (ref.getClass() != UnicastRef2.class)
            throw new SecurityException(
                      "Expecting a " + UnicastRef2.class.getName() +
                      " remote reference in stub!");

        // Check RMIClientSocketFactory in stub is from the expected class
        // "javax.rmi.ssl.SslRMIClientSocketFactory".
        //
        LiveRef liveRef = ((UnicastRef2)ref).getLiveRef();
        RMIClientSocketFactory csf = liveRef.getClientSocketFactory();
        if (csf == null || csf.getClass() != SslRMIClientSocketFactory.class)
            throw new SecurityException(
                  "Expecting a " + SslRMIClientSocketFactory.class.getName() +
                  " RMI client socket factory in stub!");
    }

    //--------------------------------------------------------------------
    // Private stuff - RMIServer creation
    //--------------------------------------------------------------------

    private RMIServer findRMIServer(JMXServiceURL directoryURL,
				    Map environment)
        throws NamingException, IOException {
        final boolean isIiop = RMIConnectorServer.isIiopURL(directoryURL,true);
        if (isIiop) {
            // Make sure java.naming.corba.orb is in the Map.
            environment.put(EnvHelp.DEFAULT_ORB,resolveOrb(environment));
        }

	String path = directoryURL.getURLPath();
	if (path.startsWith("/jndi/"))
	    return findRMIServerJNDI(path.substring(6), environment, isIiop);
	else if (path.startsWith("/stub/"))
	    return findRMIServerJRMP(path.substring(6), environment, isIiop);
	else if (path.startsWith("/ior/"))
	    return findRMIServerIIOP(path.substring(5), environment, isIiop);
	else {
	    final String msg = "URL path must begin with /jndi/ or /stub/ " +
		"or /ior/: " + path;
	    throw new MalformedURLException(msg);
	}
    }

    /**
     * Lookup the RMIServer stub in a directory.
     * @param jndiURL A JNDI URL indicating the location of the Stub
     *                (see {@link javax.management.remote.rmi}), e.g.:
     *   <ul><li><tt>rmi://registry-host:port/rmi-stub-name</tt></li>
     *       <li>or <tt>iiop://cosnaming-host:port/iiop-stub-name</tt></li>
     *       <li>or <tt>ldap://ldap-host:port/java-container-dn</tt></li>
     *   </ul>
     * @param env the environment Map passed to the connector.
     * @param isIiop true if the stub is expected to be an IIOP stub.
     * @return The retrieved RMIServer stub.
     * @exception NamingException if the stub couldn't be found.
     **/
    private RMIServer findRMIServerJNDI(String jndiURL, Map env, boolean isIiop)
	throws NamingException {

	InitialContext ctx = new InitialContext(EnvHelp.mapToHashtable(env));

	Object objref = ctx.lookup(jndiURL);
	ctx.close();

	if (isIiop)
	    return narrowIIOPServer(objref);
	else
	    return narrowJRMPServer(objref);
    }

    private static RMIServer narrowJRMPServer(Object objref) {

        return (RMIServer) objref;
    }

    private static RMIServer narrowIIOPServer(Object objref) {
        try {
            return (RMIServer)
                PortableRemoteObject.narrow(objref, RMIServer.class);
        } catch (ClassCastException e) {
            if (logger.traceOn())
		logger.trace("narrowIIOPServer","Failed to narrow objref=" +
		      objref + ": " + e);
	    if (logger.debugOn()) logger.debug("narrowIIOPServer",e);
            return null;
        }
    }

    private RMIServer findRMIServerIIOP(String ior, Map env, boolean isIiop) {
	// could forbid "rmi:" URL here -- but do we need to?
	final ORB orb = (ORB)
	    env.get(EnvHelp.DEFAULT_ORB);
	final Object stub = orb.string_to_object(ior);
	return (RMIServer) PortableRemoteObject.narrow(stub, RMIServer.class);
    }

    private RMIServer findRMIServerJRMP(String base64, Map env, boolean isIiop)
	throws IOException {
	// could forbid "iiop:" URL here -- but do we need to?
	final byte[] serialized;
	try {
	    serialized = base64ToByteArray(base64);
	} catch (IllegalArgumentException e) {
	    throw new MalformedURLException("Bad BASE64 encoding: " +
					    e.getMessage());
	}
	final ByteArrayInputStream bin = new ByteArrayInputStream(serialized);

	final ClassLoader loader = EnvHelp.resolveClientClassLoader(env);
	final ObjectInputStream oin =
	    (loader == null) ?
		new ObjectInputStream(bin) :
		new ObjectInputStreamWithLoader(bin, loader);
	final Object stub;
	try {
	    stub = oin.readObject();
	} catch (ClassNotFoundException e) {
	    throw new MalformedURLException("Class not found: " + e);
	}
	return (RMIServer) PortableRemoteObject.narrow(stub, RMIServer.class);
    }

    private static final class ObjectInputStreamWithLoader
	    extends ObjectInputStream {
	ObjectInputStreamWithLoader(InputStream in, ClassLoader cl)
		throws IOException {
	    super(in);
	    this.loader = cl;
	}

	protected Class resolveClass(ObjectStreamClass classDesc)
		throws IOException, ClassNotFoundException {
	    return Class.forName(classDesc.getName(), false, loader);
	}

	private final ClassLoader loader;
    }

    /*
       The following section of code avoids a class loading problem
       with RMI.  The problem is that an RMI stub, when deserializing
       a remote method return value or exception, will first of all
       consult the first non-bootstrap class loader it finds in the
       call stack.  This can lead to behavior that is not portable
       between implementations of the JMX Remote API.  Notably, an
       implementation on J2SE 1.4 will find the RMI stub's loader on
       the stack.  But in J2SE 5, this stub is loaded by the
       bootstrap loader, so RMI will find the loader of the user code
       that called an MBeanServerConnection method.

       To avoid this problem, we take advantage of what the RMI stub
       is doing internally.  Each remote call will end up calling
       ref.invoke(...), where ref is the RemoteRef parameter given to
       the RMI stub's constructor.  It is within this call that the
       deserialization will happen.  So we fabricate our own RemoteRef
       that delegates everything to the "real" one but that is loaded
       by a class loader that knows no other classes.  The class
       loader NoCallStackClassLoader does this: the RemoteRef is an
       instance of the class named by proxyRefClassName, which is
       fabricated by the class loader using byte code that is defined
       by the string below.

       The call stack when the deserialization happens is thus this:
       MBeanServerConnection.getAttribute (or whatever)
       -> RMIConnectionImpl_Stub.getAttribute
          -> ProxyRef.invoke(...getAttribute...)
             -> UnicastRef.invoke(...getAttribute...)
                -> internal RMI stuff

       Here UnicastRef is the RemoteRef created when the stub was
       deserialized (which is of some RMI internal class).  It and the
       "internal RMI stuff" are loaded by the bootstrap loader, so are
       transparent to the stack search.  The first non-bootstrap
       loader found is our ProxyRefLoader, as required.

       In a future version of this code as integrated into J2SE 5,
       this workaround could be replaced by direct access to the
       internals of RMI.  For now, we use the same code base for J2SE
       and for the standalone Reference Implementation.

       The byte code below encodes the following class, compiled using
       J2SE 1.4.2 with the -g:none option.

	package com.sun.jmx.remote.internal;

	import java.lang.reflect.Method;
	import java.rmi.Remote;
	import java.rmi.server.RemoteRef;
	import com.sun.jmx.remote.internal.ProxyRef;

	public class PRef extends ProxyRef {
	    public PRef(RemoteRef ref) {
		super(ref);
	    }

	    public Object invoke(Remote obj, Method method,
				 Object[] params, long opnum)
		    throws Exception {
		return ref.invoke(obj, method, params, opnum);
	    }
	}
     */

    private static final String rmiServerImplStubClassName =
        RMIServer.class.getName() + "Impl_Stub";
    private static final Class rmiServerImplStubClass;
    private static final String rmiConnectionImplStubClassName =
	RMIConnection.class.getName() + "Impl_Stub";
    private static final Class rmiConnectionImplStubClass;
    private static final String pRefClassName =
	"com.sun.jmx.remote.internal.PRef";
    private static final Constructor proxyRefConstructor;
    static {
	final String pRefByteCodeString =
	    "\312\376\272\276\0\0\0.\0\27\12\0\5\0\15\11\0\4\0\16\13\0\17\0"+
	    "\20\7\0\21\7\0\22\1\0\6<init>\1\0\36(Ljava/rmi/server/RemoteRef;"+
	    ")V\1\0\4Code\1\0\6invoke\1\0S(Ljava/rmi/Remote;Ljava/lang/reflec"+
	    "t/Method;[Ljava/lang/Object;J)Ljava/lang/Object;\1\0\12Exception"+
	    "s\7\0\23\14\0\6\0\7\14\0\24\0\25\7\0\26\14\0\11\0\12\1\0\40com/"+
	    "sun/jmx/remote/internal/PRef\1\0$com/sun/jmx/remote/internal/Pr"+
	    "oxyRef\1\0\23java/lang/Exception\1\0\3ref\1\0\33Ljava/rmi/serve"+
	    "r/RemoteRef;\1\0\31java/rmi/server/RemoteRef\0!\0\4\0\5\0\0\0\0"+
	    "\0\2\0\1\0\6\0\7\0\1\0\10\0\0\0\22\0\2\0\2\0\0\0\6*+\267\0\1\261"+
	    "\0\0\0\0\0\1\0\11\0\12\0\2\0\10\0\0\0\33\0\6\0\6\0\0\0\17*\264\0"+
	    "\2+,-\26\4\271\0\3\6\0\260\0\0\0\0\0\13\0\0\0\4\0\1\0\14\0\0";
	final byte[] pRefByteCode =
	    NoCallStackClassLoader.stringToBytes(pRefByteCodeString);
	PrivilegedExceptionAction action = new PrivilegedExceptionAction() {
	    public Object run() throws Exception {
		Class thisClass = RMIConnector.class;
		ClassLoader thisLoader = thisClass.getClassLoader();
		ProtectionDomain thisProtectionDomain =
		    thisClass.getProtectionDomain();
		String[] otherClassNames = {ProxyRef.class.getName()};
		ClassLoader cl =
		    new NoCallStackClassLoader(pRefClassName,
					       pRefByteCode,
					       otherClassNames,
					       thisLoader,
					       thisProtectionDomain);
		Class c = cl.loadClass(pRefClassName);
		return c.getConstructor(new Class[] {RemoteRef.class});
	    }
	};

        Class serverStubClass;
        try {
            serverStubClass = Class.forName(rmiServerImplStubClassName);
        } catch (Exception e) {
            logger.error("<clinit>",
                         "Failed to instantiate " +
                         rmiServerImplStubClassName + ": " + e);
            logger.debug("<clinit>",e);
            serverStubClass = null;
        }
        rmiServerImplStubClass = serverStubClass;

	Class stubClass;
	Constructor constr;
	try {
	    stubClass = Class.forName(rmiConnectionImplStubClassName);
	    constr = (Constructor) AccessController.doPrivileged(action);
	} catch (Exception e) {
	    logger.error("<clinit>", 
			 "Failed to initialize proxy reference constructor "+
			 "for " + rmiConnectionImplStubClassName + ": " + e);
	    logger.debug("<clinit>",e);
	    stubClass = null;
	    constr = null;
	}
	rmiConnectionImplStubClass = stubClass;
	proxyRefConstructor = constr;
    }

    private static RMIConnection shadowJrmpStub(RemoteObject stub)
	    throws InstantiationException, IllegalAccessException,
		   InvocationTargetException, ClassNotFoundException,
		   NoSuchMethodException {
	RemoteRef ref = stub.getRef();
	RemoteRef proxyRef = (RemoteRef)
	    proxyRefConstructor.newInstance(new Object[] {ref});
	final Class[] constrTypes = {RemoteRef.class};
	final Constructor rmiConnectionImplStubConstructor =
	    rmiConnectionImplStubClass.getConstructor(constrTypes);
	Object[] args = {proxyRef};
	RMIConnection proxyStub = (RMIConnection)
	    rmiConnectionImplStubConstructor.newInstance(args);
	return proxyStub;
    }

    /*
       The following code performs a similar trick for RMI/IIOP to the
       one described above for RMI/JRMP.  Unlike JRMP, though, we
       can't easily insert an object between the RMIConnection stub
       and the RMI/IIOP deserialization code, as explained below.

       A method in an RMI/IIOP stub does the following.  It makes an
       org.omg.CORBA_2_3.portable.OutputStream for each request, and
       writes the parameters to it.  Then it calls
       _invoke(OutputStream) which it inherits from CORBA's
       ObjectImpl.  That returns an
       org.omg.CORBA_2_3.portable.InputStream.  The return value is
       read from this InputStream.  So the stack during
       deserialization looks like this:

       MBeanServerConnection.getAttribute (or whatever)
       -> _RMIConnection_Stub.getAttribute
          -> Util.readAny (a CORBA method)
             -> InputStream.read_any
                -> internal CORBA stuff

       What we would have *liked* to have done would be the same thing
       as for RMI/JRMP.  We create a "ProxyDelegate" that is an
       org.omg.CORBA.portable.Delegate that simply forwards every
       operation to the real original Delegate from the RMIConnection
       stub, except that the InputStream returned by _invoke is
       wrapped by a "ProxyInputStream" that is loaded by our
       NoCallStackClassLoader.

       Unfortunately, this doesn't work, at least with Sun's J2SE
       1.4.2, because the CORBA code is not designed to allow you to
       change Delegates arbitrarily.  You get a ClassCastException
       from code that expects the Delegate to implement an internal
       interface.

       So instead we do the following.  We create a subclass of the
       stub that overrides the _invoke method so as to wrap the
       returned InputStream in a ProxyInputStream.  We create a
       subclass of ProxyInputStream using the NoCallStackClassLoader
       and override its read_any and read_value(Class) methods.
       (These are the only methods called during deserialization of
       MBeanServerConnection return values.)  We extract the Delegate
       from the original stub and insert it into our subclass stub,
       and away we go.  The state of a stub consists solely of its
       Delegate.

       We also need to catch ApplicationException, which will encode
       any exceptions declared in the throws clause of the called
       method.  Its InputStream needs to be wrapped in a
       ProxyInputSteam too.

       We override _releaseReply in the stub subclass so that it
       replaces a ProxyInputStream argument with the original
       InputStream.  This avoids problems if the implementation of
       _releaseReply ends up casting this InputStream to an
       implementation-specific interface (which in Sun's J2SE 5 it
       does).

       It is not strictly necessary for the stub subclass to be loaded
       by a NoCallStackClassLoader, since the call-stack search stops
       at the ProxyInputStream subclass.  However, it is convenient
       for two reasons.  One is that it means that the
       ProxyInputStream subclass can be accessed directly, without
       using reflection.  The other is that it avoids build problems,
       since usually stubs are created after other classes are
       compiled, so we can't access them from this class without,
       again, using reflection.

       The strings below encode the following two Java classes,
       compiled using J2SE 1.4.2 with javac -g:none.

	package com.sun.jmx.remote.internal;

	import org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub;

	import org.omg.CORBA.portable.ApplicationException;
	import org.omg.CORBA.portable.InputStream;
	import org.omg.CORBA.portable.OutputStream;
	import org.omg.CORBA.portable.RemarshalException;

	public class ProxyStub extends _RMIConnection_Stub {
	    public InputStream _invoke(OutputStream out)
		    throws ApplicationException, RemarshalException {
    	    	try {
		    return new PInputStream(super._invoke(out));
    	    	} catch (ApplicationException e) {
    	    	    InputStream pis = new PInputStream(e.getInputStream());
    	    	    throw new ApplicationException(e.getId(), pis);
    	    	}
	    }

	    public void _releaseReply(InputStream in) {
		PInputStream pis = (PInputStream) in;
		super._releaseReply(pis.getProxiedInputStream());
	    }
	}

	package com.sun.jmx.remote.internal;

	public class PInputStream extends ProxyInputStream {
	    public PInputStream(org.omg.CORBA.portable.InputStream in) {
		super(in);
	    }

	    public org.omg.CORBA.Any read_any() {
		return in.read_any();
	    }

	    public java.io.Serializable read_value(Class clz) {
		return narrow().read_value(clz);
	    }
	}


     */
    private static final String iiopConnectionStubClassName =
	"org.omg.stub.javax.management.remote.rmi._RMIConnection_Stub";
    private static final String proxyStubClassName =
	"com.sun.jmx.remote.internal.ProxyStub";
    private static final String pInputStreamClassName =
	"com.sun.jmx.remote.internal.PInputStream";
    private static final Class proxyStubClass;
    static {
	final String proxyStubByteCodeString =
	    "\312\376\272\276\0\0\0.\0)\12\0\14\0\26\7\0\27\12\0\14\0\30\12"+
	    "\0\2\0\31\7\0\32\12\0\5\0\33\12\0\5\0\34\12\0\5\0\35\12\0\2\0"+
	    "\36\12\0\14\0\37\7\0\40\7\0!\1\0\6<init>\1\0\3()V\1\0\4Code\1"+
	    "\0\7_invoke\1\0K(Lorg/omg/CORBA/portable/OutputStream;)Lorg/o"+
	    "mg/CORBA/portable/InputStream;\1\0\12Exceptions\7\0\"\1\0\15_"+
	    "releaseReply\1\0'(Lorg/omg/CORBA/portable/InputStream;)V\14\0"+
	    "\15\0\16\1\0(com/sun/jmx/remote/internal/PInputStream\14\0\20"+
	    "\0\21\14\0\15\0\25\1\0+org/omg/CORBA/portable/ApplicationExce"+
	    "ption\14\0#\0$\14\0%\0&\14\0\15\0'\14\0(\0$\14\0\24\0\25\1\0%"+
	    "com/sun/jmx/remote/internal/ProxyStub\1\0<org/omg/stub/javax/"+
	    "management/remote/rmi/_RMIConnection_Stub\1\0)org/omg/CORBA/p"+
	    "ortable/RemarshalException\1\0\16getInputStream\1\0&()Lorg/om"+
	    "g/CORBA/portable/InputStream;\1\0\5getId\1\0\24()Ljava/lang/S"+
	    "tring;\1\09(Ljava/lang/String;Lorg/omg/CORBA/portable/InputSt"+
	    "ream;)V\1\0\25getProxiedInputStream\0!\0\13\0\14\0\0\0\0\0\3\0"+
	    "\1\0\15\0\16\0\1\0\17\0\0\0\21\0\1\0\1\0\0\0\5*\267\0\1\261\0"+
	    "\0\0\0\0\1\0\20\0\21\0\2\0\17\0\0\0;\0\4\0\4\0\0\0'\273\0\2Y*"+
	    "+\267\0\3\267\0\4\260M\273\0\2Y,\266\0\6\267\0\4N\273\0\5Y,\266"+
	    "\0\7-\267\0\10\277\0\1\0\0\0\14\0\15\0\5\0\0\0\22\0\0\0\6\0\2"+
	    "\0\5\0\23\0\1\0\24\0\25\0\1\0\17\0\0\0\36\0\2\0\2\0\0\0\22+\306"+
	    "\0\13+\300\0\2\266\0\11L*+\267\0\12\261\0\0\0\0\0\0";
	final String pInputStreamByteCodeString =
	    "\312\376\272\276\0\0\0.\0\36\12\0\7\0\17\11\0\6\0\20\12\0\21\0"+
	    "\22\12\0\6\0\23\12\0\24\0\25\7\0\26\7\0\27\1\0\6<init>\1\0'(L"+
	    "org/omg/CORBA/portable/InputStream;)V\1\0\4Code\1\0\10read_an"+
	    "y\1\0\25()Lorg/omg/CORBA/Any;\1\0\12read_value\1\0)(Ljava/lan"+
	    "g/Class;)Ljava/io/Serializable;\14\0\10\0\11\14\0\30\0\31\7\0"+
	    "\32\14\0\13\0\14\14\0\33\0\34\7\0\35\14\0\15\0\16\1\0(com/sun"+
	    "/jmx/remote/internal/PInputStream\1\0,com/sun/jmx/remote/inte"+
	    "rnal/ProxyInputStream\1\0\2in\1\0$Lorg/omg/CORBA/portable/Inp"+
	    "utStream;\1\0\"org/omg/CORBA/portable/InputStream\1\0\6narrow"+
	    "\1\0*()Lorg/omg/CORBA_2_3/portable/InputStream;\1\0&org/omg/C"+
	    "ORBA_2_3/portable/InputStream\0!\0\6\0\7\0\0\0\0\0\3\0\1\0\10"+
	    "\0\11\0\1\0\12\0\0\0\22\0\2\0\2\0\0\0\6*+\267\0\1\261\0\0\0\0"+
	    "\0\1\0\13\0\14\0\1\0\12\0\0\0\24\0\1\0\1\0\0\0\10*\264\0\2\266"+
	    "\0\3\260\0\0\0\0\0\1\0\15\0\16\0\1\0\12\0\0\0\25\0\2\0\2\0\0\0"+
	    "\11*\266\0\4+\266\0\5\260\0\0\0\0\0\0";
	final byte[] proxyStubByteCode =
	    NoCallStackClassLoader.stringToBytes(proxyStubByteCodeString);
	final byte[] pInputStreamByteCode =
	    NoCallStackClassLoader.stringToBytes(pInputStreamByteCodeString);
	final String[] classNames={proxyStubClassName, pInputStreamClassName};
	final byte[][] byteCodes = {proxyStubByteCode, pInputStreamByteCode};
	final String[] otherClassNames = {
	    iiopConnectionStubClassName,
	    ProxyInputStream.class.getName(),
	};
	PrivilegedExceptionAction action = new PrivilegedExceptionAction() {
	    public Object run() throws Exception {
		Class thisClass = RMIConnector.class;
		ClassLoader thisLoader = thisClass.getClassLoader();
		ProtectionDomain thisProtectionDomain =
		    thisClass.getProtectionDomain();
		ClassLoader cl =
		    new NoCallStackClassLoader(classNames,
					       byteCodes,
					       otherClassNames,
					       thisLoader,
					       thisProtectionDomain);
		return cl.loadClass(proxyStubClassName);
	    }
	};
	Class stubClass;
	try {
	    stubClass = (Class) AccessController.doPrivileged(action);
	} catch (Exception e) {
	    logger.error("<clinit>",
		   "Unexpected exception making shadow IIOP stub class: "+e);
	    logger.debug("<clinit>",e);
	    stubClass = null;
	}
	proxyStubClass = stubClass;
    }

    private static RMIConnection shadowIiopStub(Stub stub)
	    throws InstantiationException, IllegalAccessException {
	Stub proxyStub = (Stub) proxyStubClass.newInstance();
	proxyStub._set_delegate(stub._get_delegate());
	return (RMIConnection) proxyStub;
    }

    private static RMIConnection getConnection(RMIServer server,
                                               Object credentials,
                                               boolean checkStub)
	    throws IOException {
	RMIConnection c = server.newClient(credentials);
        if (checkStub) checkStub(c, rmiConnectionImplStubClass);
	try {
	    if (c.getClass() == rmiConnectionImplStubClass)
		return shadowJrmpStub((RemoteObject) c);
	    if (c.getClass().getName().equals(iiopConnectionStubClassName))
		return shadowIiopStub((Stub) c);
	    logger.trace("getConnection",
			 "Did not wrap " + c.getClass() + " to foil " +
			 "stack search for classes: class loading semantics " +
			 "may be incorrect");
	} catch (Exception e) {
	    logger.error("getConnection",
			 "Could not wrap " + c.getClass() + " to foil " +
			 "stack search for classes: class loading semantics " +
			 "may be incorrect: " + e);
	    logger.debug("getConnection",e);
	    // so just return the original stub, which will work for all
	    // but the most exotic class loading situations
	}
	return c;
    }

    private static byte[] base64ToByteArray(String s) {
        int sLen = s.length();
        int numGroups = sLen/4;
        if (4*numGroups != sLen)
            throw new IllegalArgumentException(
                "String length must be a multiple of four.");
        int missingBytesInLastGroup = 0;
        int numFullGroups = numGroups;
        if (sLen != 0) {
            if (s.charAt(sLen-1) == '=') {
                missingBytesInLastGroup++;
                numFullGroups--;
            }
            if (s.charAt(sLen-2) == '=')
                missingBytesInLastGroup++;
        }
        byte[] result = new byte[3*numGroups - missingBytesInLastGroup];

        // Translate all full groups from base64 to byte array elements
        int inCursor = 0, outCursor = 0;
        for (int i=0; i<numFullGroups; i++) {
            int ch0 = base64toInt(s.charAt(inCursor++));
            int ch1 = base64toInt(s.charAt(inCursor++));
            int ch2 = base64toInt(s.charAt(inCursor++));
            int ch3 = base64toInt(s.charAt(inCursor++));
            result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));
            result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
            result[outCursor++] = (byte) ((ch2 << 6) | ch3);
        }

        // Translate partial group, if present
        if (missingBytesInLastGroup != 0) {
            int ch0 = base64toInt(s.charAt(inCursor++));
            int ch1 = base64toInt(s.charAt(inCursor++));
            result[outCursor++] = (byte) ((ch0 << 2) | (ch1 >> 4));

            if (missingBytesInLastGroup == 1) {
                int ch2 = base64toInt(s.charAt(inCursor++));
                result[outCursor++] = (byte) ((ch1 << 4) | (ch2 >> 2));
            }
        }
        // assert inCursor == s.length()-missingBytesInLastGroup;
        // assert outCursor == result.length;
        return result;
    }

    /**
     * Translates the specified character, which is assumed to be in the
     * "Base 64 Alphabet" into its equivalent 6-bit positive integer.
     *
     * @throw IllegalArgumentException if
     *        c is not in the Base64 Alphabet.
     */
    private static int base64toInt(char c) {
	int result;

	if (c >= base64ToInt.length)
	    result = -1;
        else
	    result = base64ToInt[c];

        if (result < 0)
            throw new IllegalArgumentException("Illegal character " + c);
        return result;
    }

    /**
     * This array is a lookup table that translates unicode characters
     * drawn from the "Base64 Alphabet" (as specified in Table 1 of RFC 2045)
     * into their 6-bit positive integer equivalents.  Characters that
     * are not in the Base64 alphabet but fall within the bounds of the
     * array are translated to -1.
     */
    private static final byte base64ToInt[] = {
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
        -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54,
        55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 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, -1, -1, -1, -1, -1, -1, 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
    };

    //--------------------------------------------------------------------
    // Private stuff - Find / Set default class loader
    //--------------------------------------------------------------------
    private ClassLoader pushDefaultClassLoader() {
	final Thread t = Thread.currentThread();
        final ClassLoader old =  t.getContextClassLoader();
        if (defaultClassLoader != null)
	    AccessController.doPrivileged(new PrivilegedAction() {
		    public Object run() {
			t.setContextClassLoader(defaultClassLoader);
			return null;
		    }
		});
        return old;
    }

    private void popDefaultClassLoader(final ClassLoader old) {
	AccessController.doPrivileged(new PrivilegedAction() {
		public Object run() {
		    Thread.currentThread().setContextClassLoader(old);
		    return null;
		}
	    });
    }

    //--------------------------------------------------------------------
    // Private variables
    //--------------------------------------------------------------------
    /**
     * @serial The RMIServer stub of the RMI JMX Connector server to
     * which this client connector is (or will be) connected. This
     * field can be null when <var>jmxServiceURL</var> is not
     * null. This includes the case where <var>jmxServiceURL</var>
     * contains a serialized RMIServer stub. If both
     * <var>rmiServer</var> and <var>jmxServiceURL</var> are null then
     * serialization will fail.
     *
     * @see #RMIConnector(RMIServer,Map)
     **/
    private final RMIServer rmiServer;

    /**
     * @serial The JMXServiceURL of the RMI JMX Connector server to
     * which this client connector will be connected. This field can
     * be null when <var>rmiServer</var> is not null. If both
     * <var>rmiServer</var> and <var>jmxServiceURL</var> are null then
     * serialization will fail.
     *
     * @see #RMIConnector(JMXServiceURL,Map)
     **/
    private final JMXServiceURL jmxServiceURL;

    // ---------------------------------------------------------
    // WARNING - WARNING - WARNING - WARNING - WARNING - WARNING
    // ---------------------------------------------------------
    // Any transient variable which needs to be initialized should
    // be initialized in the method initTransient()
    private transient Map env;
    private transient ClassLoader defaultClassLoader;
    private transient RMIConnection connection;
    private transient String connectionId;

    private transient long clientNotifSeqNo = 0;

    private transient WeakHashMap rmbscMap;

    private transient RMINotifClient rmiNotifClient;
    // = new RMINotifClient(new Integer(0));

    private transient long clientNotifCounter = 0;

    private transient boolean connected;
    // = false;
    private transient boolean terminated;
    // = false;

    private transient Exception closeException;

    private transient NotificationBroadcasterSupport connectionBroadcaster;

    private transient ClientCommunicatorAdmin communicatorAdmin;
    
    /**
     * A static WeakReference to an {@link org.omg.CORBA.ORB ORB} to
     * connect unconnected stubs.
     **/
    private static WeakReference<ORB> orb = null;

    // TRACES & DEBUG
    //---------------
    private static String objects(final Object[] objs) {
	if (objs == null)
	    return "null";
	else
	    return Arrays.asList(objs).toString();
    }

    private static String strings(final String[] strs) {
	return objects(strs);
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar