aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/com/sun/jmx/interceptor/DefaultMBeanServerInterceptor.java
blob: 7d95a77fde2b72cf2ca634de1a54ea95d37c5301 (plain)
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
/*
 * Copyright 2000-2008 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package com.sun.jmx.interceptor;


// JMX RI
import static com.sun.jmx.defaults.JmxProperties.MBEANSERVER_LOGGER;
import com.sun.jmx.mbeanserver.DynamicMBean2;
import com.sun.jmx.mbeanserver.Introspector;
import com.sun.jmx.mbeanserver.MBeanInjector;
import com.sun.jmx.mbeanserver.MBeanInstantiator;
import com.sun.jmx.mbeanserver.ModifiableClassLoaderRepository;
import com.sun.jmx.mbeanserver.NamedObject;
import com.sun.jmx.mbeanserver.NotifySupport;
import com.sun.jmx.mbeanserver.Repository;
import com.sun.jmx.mbeanserver.Repository.RegistrationContext;
import com.sun.jmx.mbeanserver.Util;
import com.sun.jmx.remote.util.EnvHelp;

import java.lang.ref.WeakReference;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.Permission;
import java.security.PrivilegedAction;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.logging.Level;

// JMX import
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.DynamicWrapperMBean;
import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.InvalidAttributeValueException;
import javax.management.JMRuntimeException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanPermission;
import javax.management.MBeanRegistration;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerNotification;
import javax.management.MBeanTrustPermission;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.NotificationBroadcaster;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationEmitter;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.QueryEval;
import javax.management.QueryExp;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeOperationsException;
import javax.management.namespace.JMXNamespace;

/**
 * This is the default class for MBean manipulation on the agent side. It
 * contains the methods necessary for the creation, registration, and
 * deletion of MBeans as well as the access methods for registered MBeans.
 * This is the core component of the JMX infrastructure.
 * <P>
 * Every MBean which is added to the MBean server becomes manageable: its attributes and operations
 * become remotely accessible through the connectors/adaptors connected to that MBean server.
 * A Java object cannot be registered in the MBean server unless it is a JMX compliant MBean.
 * <P>
 * When an MBean is registered or unregistered in the MBean server an
 * {@link javax.management.MBeanServerNotification MBeanServerNotification}
 * Notification is emitted. To register an object as listener to MBeanServerNotifications
 * you should call the MBean server method {@link #addNotificationListener addNotificationListener} with <CODE>ObjectName</CODE>
 * the <CODE>ObjectName</CODE> of the {@link javax.management.MBeanServerDelegate MBeanServerDelegate}.
 * This <CODE>ObjectName</CODE> is:
 * <BR>
 * <CODE>JMImplementation:type=MBeanServerDelegate</CODE>.
 *
 * @since 1.5
 */
public class DefaultMBeanServerInterceptor
        extends MBeanServerInterceptorSupport {

    /** The MBeanInstantiator object used by the
     *  DefaultMBeanServerInterceptor */
    private final transient MBeanInstantiator instantiator;

    /** The MBean server object that is associated to the
     *  DefaultMBeanServerInterceptor */
    private transient MBeanServer server = null;

    /** The MBean server delegate object that is associated to the
     *  DefaultMBeanServerInterceptor */
    private final transient MBeanServerDelegate delegate;

    /** The Repository object used by the DefaultMBeanServerInterceptor */
    private final transient Repository repository;

    /** Wrappers for client listeners.  */
    /* See the comment before addNotificationListener below.  */
    private final transient
        WeakHashMap<ListenerWrapper, WeakReference<ListenerWrapper>>
            listenerWrappers =
                new WeakHashMap<ListenerWrapper,
                                WeakReference<ListenerWrapper>>();

    private final NamespaceDispatchInterceptor dispatcher;

    /** The default domain of the object names */
    private final String domain;

    /** The mbeanServerName  */
    private final String mbeanServerName;

    /** The sequence number identifying the notifications sent */
    // Now sequence number is handled by MBeanServerDelegate.
    // private int sequenceNumber=0;

    /**
     * Creates a DefaultMBeanServerInterceptor with the specified
     * repository instance.
     * <p>Do not forget to call <code>initialize(outer,delegate)</code>
     * before using this object.
     * @param outer A pointer to the MBeanServer object that must be
     *        passed to the MBeans when invoking their
     *        {@link javax.management.MBeanRegistration} interface.
     * @param delegate A pointer to the MBeanServerDelegate associated
     *        with the new MBeanServer. The new MBeanServer must register
     *        this MBean in its MBean repository.
     * @param instantiator The MBeanInstantiator that will be used to
     *        instantiate MBeans and take care of class loading issues.
     * @param repository The repository to use for this MBeanServer.
     * @param dispatcher The dispatcher used by this MBeanServer
     */
    public DefaultMBeanServerInterceptor(MBeanServer         outer,
                                         MBeanServerDelegate delegate,
                                         MBeanInstantiator   instantiator,
                                         Repository          repository,
                                         NamespaceDispatchInterceptor dispatcher)  {
        if (outer == null) throw new
            IllegalArgumentException("outer MBeanServer cannot be null");
        if (delegate == null) throw new
            IllegalArgumentException("MBeanServerDelegate cannot be null");
        if (instantiator == null) throw new
            IllegalArgumentException("MBeanInstantiator cannot be null");
        if (repository == null) throw new
            IllegalArgumentException("Repository cannot be null");

        this.server   = outer;
        this.delegate = delegate;
        this.instantiator = instantiator;
        this.repository   = repository;
        this.domain       = repository.getDefaultDomain();
        this.dispatcher   = dispatcher;
        this.mbeanServerName = Util.getMBeanServerSecurityName(delegate);
    }

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

        return createMBean(className, name, (Object[]) null, (String[]) null);

    }

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

        return createMBean(className, name, loaderName, (Object[]) null,
                           (String[]) null);
    }

    public ObjectInstance createMBean(String className, ObjectName name,
                                      Object[] params, String[] signature)
        throws ReflectionException, InstanceAlreadyExistsException,
               MBeanRegistrationException, MBeanException,
               NotCompliantMBeanException  {

        try {
            return createMBean(className, name, null, true,
                               params, signature);
        } catch (InstanceNotFoundException e) {
            /* Can only happen if loaderName doesn't exist, but we just
               passed null, so we shouldn't get this exception.  */
            throw EnvHelp.initCause(
                new IllegalArgumentException("Unexpected exception: " + e), e);
        }
    }

    public ObjectInstance createMBean(String className, ObjectName name,
                                      ObjectName loaderName,
                                      Object[] params, String[] signature)
        throws ReflectionException, InstanceAlreadyExistsException,
               MBeanRegistrationException, MBeanException,
               NotCompliantMBeanException, InstanceNotFoundException  {

        return createMBean(className, name, loaderName, false,
                           params, signature);
    }

    private ObjectInstance createMBean(String className, ObjectName name,
                                       ObjectName loaderName,
                                       boolean withDefaultLoaderRepository,
                                       Object[] params, String[] signature)
        throws ReflectionException, InstanceAlreadyExistsException,
               MBeanRegistrationException, MBeanException,
               NotCompliantMBeanException, InstanceNotFoundException {

        Class theClass;

        if (className == null) {
            final RuntimeException wrapped =
                new IllegalArgumentException("The class name cannot be null");
            throw new RuntimeOperationsException(wrapped,
                      "Exception occurred during MBean creation");
        }

        if (name != null) {
            if (name.isPattern()) {
                final RuntimeException wrapped =
                    new IllegalArgumentException("Invalid name->" +
                                                 name.toString());
                final String msg = "Exception occurred during MBean creation";
                throw new RuntimeOperationsException(wrapped, msg);
            }

            name = nonDefaultDomain(name);
        }

        checkMBeanPermission(mbeanServerName,className, null, null, "instantiate");
        checkMBeanPermission(mbeanServerName,className, null, name, "registerMBean");

        /* Load the appropriate class. */
        if (withDefaultLoaderRepository) {
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
                MBEANSERVER_LOGGER.logp(Level.FINER,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "createMBean",
                        "ClassName = " + className + ", ObjectName = " + name);
            }
            theClass =
                instantiator.findClassWithDefaultLoaderRepository(className);
        } else if (loaderName == null) {
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
                MBEANSERVER_LOGGER.logp(Level.FINER,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "createMBean", "ClassName = " + className +
                        ", ObjectName = " + name + ", Loader name = null");
            }

            theClass = instantiator.findClass(className,
                                  server.getClass().getClassLoader());
        } else {
            loaderName = nonDefaultDomain(loaderName);

            if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
                MBEANSERVER_LOGGER.logp(Level.FINER,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "createMBean", "ClassName = " + className +
                        ", ObjectName = " + name +
                        ", Loader name = " + loaderName);
            }

            theClass = instantiator.findClass(className, loaderName);
        }

        checkMBeanTrustPermission(theClass);

        // Check that the MBean can be instantiated by the MBeanServer.
        Introspector.testCreation(theClass);

        // Check the JMX MBean compliance of the class
        Introspector.checkCompliance(theClass);

        Object moi= instantiator.instantiate(theClass, params,  signature,
                                             server.getClass().getClassLoader());

        final String infoClassName = getNewMBeanClassName(moi);

        return registerObject(infoClassName, moi, name);
    }

    public ObjectInstance registerMBean(Object object, ObjectName name)
        throws InstanceAlreadyExistsException, MBeanRegistrationException,
        NotCompliantMBeanException  {

        // ------------------------------
        // ------------------------------
        Class theClass = object.getClass();

        Introspector.checkCompliance(theClass);

        final String infoClassName = getNewMBeanClassName(object);

        checkMBeanPermission(mbeanServerName,infoClassName, null, name, "registerMBean");
        checkMBeanTrustPermission(theClass);

        return registerObject(infoClassName, object, name);
    }

    private static String getNewMBeanClassName(Object mbeanToRegister)
            throws NotCompliantMBeanException {
        if (mbeanToRegister instanceof DynamicMBean) {
            DynamicMBean mbean = (DynamicMBean) mbeanToRegister;
            final String name;
            try {
                name = mbean.getMBeanInfo().getClassName();
            } catch (Exception e) {
                // Includes case where getMBeanInfo() returns null
                NotCompliantMBeanException ncmbe =
                    new NotCompliantMBeanException("Bad getMBeanInfo()");
                ncmbe.initCause(e);
                throw ncmbe;
            }
            if (name == null) {
                final String msg = "MBeanInfo has null class name";
                throw new NotCompliantMBeanException(msg);
            }
            return name;
        } else
            return mbeanToRegister.getClass().getName();
    }

    private final Set<ObjectName> beingUnregistered =
        new HashSet<ObjectName>();

    public void unregisterMBean(ObjectName name)
            throws InstanceNotFoundException, MBeanRegistrationException  {

        if (name == null) {
            final RuntimeException wrapped =
                new IllegalArgumentException("Object name cannot be null");
            throw new RuntimeOperationsException(wrapped,
                      "Exception occurred trying to unregister the MBean");
        }

        name = nonDefaultDomain(name);

        /* The semantics of preDeregister are tricky.  If it throws an
           exception, then the unregisterMBean fails.  This allows an
           MBean to refuse to be unregistered.  If it returns
           successfully, then the unregisterMBean can proceed.  In
           this case the preDeregister may have cleaned up some state,
           and will not expect to be called a second time.  So if two
           threads try to unregister the same MBean at the same time
           then one of them must wait for the other one to either (a)
           call preDeregister and get an exception or (b) call
           preDeregister successfully and unregister the MBean.
           Suppose thread T1 is unregistering an MBean and thread T2
           is trying to unregister the same MBean, so waiting for T1.
           Then a deadlock is possible if the preDeregister for T1
           ends up needing a lock held by T2.  Given the semantics
           just described, there does not seem to be any way to avoid
           this.  This will not happen to code where it is clear for
           any given MBean what thread may unregister that MBean.

           On the other hand we clearly do not want a thread that is
           unregistering MBean A to have to wait for another thread
           that is unregistering another MBean B (see bug 6318664).  A
           deadlock in this situation could reasonably be considered
           gratuitous.  So holding a global lock across the
           preDeregister call would be bad.

           So we have a set of ObjectNames that some thread is
           currently unregistering.  When a thread wants to unregister
           a name, it must first check if the name is in the set, and
           if so it must wait.  When a thread successfully unregisters
           a name it removes the name from the set and notifies any
           waiting threads that the set has changed.

           This implies that we must be very careful to ensure that
           the name is removed from the set and waiters notified, no
           matter what code path is taken.  */

        synchronized (beingUnregistered) {
            while (beingUnregistered.contains(name)) {
                try {
                    beingUnregistered.wait();
                } catch (InterruptedException e) {
                    throw new MBeanRegistrationException(e, e.toString());
                    // pretend the exception came from preDeregister;
                    // in another execution sequence it could have
                }
            }
            beingUnregistered.add(name);
        }

        try {
            exclusiveUnregisterMBean(name);
        } finally {
            synchronized (beingUnregistered) {
                beingUnregistered.remove(name);
                beingUnregistered.notifyAll();
            }
        }
    }

    private void exclusiveUnregisterMBean(ObjectName name)
            throws InstanceNotFoundException, MBeanRegistrationException {

        DynamicMBean instance = getMBean(name);
        // may throw InstanceNotFoundException

        checkMBeanPermission(mbeanServerName, instance, null, name,
                "unregisterMBean");

        if (instance instanceof MBeanRegistration)
            preDeregisterInvoke((MBeanRegistration) instance);

        final Object resource = getResource(instance);

        // Unregisters the MBean from the repository.
        // Returns the resource context that was used.
        // The returned context does nothing for regular MBeans.
        // For ClassLoader MBeans and JMXNamespace (and JMXDomain)
        // MBeans - the context makes it possible to unregister these
        // objects from the appropriate framework artifacts, such as
        // the CLR or the dispatcher, from within the repository lock.
        // In case of success, we also need to call context.done() at the
        // end of this method.
        //
        final ResourceContext context =
                unregisterFromRepository(resource, instance, name);

        try {
            if (instance instanceof MBeanRegistration)
                postDeregisterInvoke(name,(MBeanRegistration) instance);
        } finally {
            context.done();
        }
    }

    public ObjectInstance getObjectInstance(ObjectName name)
            throws InstanceNotFoundException {

        name = nonDefaultDomain(name);
        DynamicMBean instance = getMBean(name);

        checkMBeanPermission(mbeanServerName,
                instance, null, name, "getObjectInstance");

        final String className = getClassName(instance);

        return new ObjectInstance(name, className);
    }

    public Set<ObjectInstance> queryMBeans(ObjectName name, QueryExp query) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Check if the caller has the right to invoke 'queryMBeans'
            //
            checkMBeanPermission(mbeanServerName,(String) null, null, null, "queryMBeans");

            // Perform query without "query".
            //
            Set<ObjectInstance> list = queryMBeansImpl(name, null);

            // Check if the caller has the right to invoke 'queryMBeans'
            // on each specific classname/objectname in the list.
            //
            Set<ObjectInstance> allowedList =
                new HashSet<ObjectInstance>(list.size());
            for (ObjectInstance oi : list) {
                try {
                    checkMBeanPermission(mbeanServerName,oi.getClassName(), null,
                                         oi.getObjectName(), "queryMBeans");
                    allowedList.add(oi);
                } catch (SecurityException e) {
                    // OK: Do not add this ObjectInstance to the list
                }
            }

            // Apply query to allowed MBeans only.
            //
            return filterListOfObjectInstances(allowedList, query);
        } else {
            // Perform query.
            //
            return queryMBeansImpl(name, query);
        }
    }

    private Set<ObjectInstance> queryMBeansImpl(ObjectName name,
                                                QueryExp query) {
        // Query the MBeans on the repository
        //
        Set<NamedObject> list = repository.query(name, query);

        return (objectInstancesFromFilteredNamedObjects(list, query));
    }

    public Set<ObjectName> queryNames(ObjectName name, QueryExp query) {
        Set<ObjectName> queryList;
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Check if the caller has the right to invoke 'queryNames'
            //
            checkMBeanPermission(mbeanServerName,(String) null, null, null, "queryNames");

            // Perform query without "query".
            //
            Set<ObjectInstance> list = queryMBeansImpl(name, null);

            // Check if the caller has the right to invoke 'queryNames'
            // on each specific classname/objectname in the list.
            //
            Set<ObjectInstance> allowedList =
                new HashSet<ObjectInstance>(list.size());
            for (ObjectInstance oi : list) {
                try {
                    checkMBeanPermission(mbeanServerName, oi.getClassName(), null,
                                         oi.getObjectName(), "queryNames");
                    allowedList.add(oi);
                } catch (SecurityException e) {
                    // OK: Do not add this ObjectInstance to the list
                }
            }

            // Apply query to allowed MBeans only.
            //
            Set<ObjectInstance> queryObjectInstanceList =
                filterListOfObjectInstances(allowedList, query);
            queryList = new HashSet<ObjectName>(queryObjectInstanceList.size());
            for (ObjectInstance oi : queryObjectInstanceList) {
                queryList.add(oi.getObjectName());
            }
        } else {
            // Perform query.
            //
            queryList = queryNamesImpl(name, query);
        }
        return queryList;
    }

    private Set<ObjectName> queryNamesImpl(ObjectName name, QueryExp query) {
        // Query the MBeans on the repository
        //
        Set<NamedObject> list = repository.query(name, query);

        return (objectNamesFromFilteredNamedObjects(list, query));
    }

    public boolean isRegistered(ObjectName name) {
        if (name == null) {
            throw new RuntimeOperationsException(
                     new IllegalArgumentException("Object name cannot be null"),
                     "Object name cannot be null");
        }

        name = nonDefaultDomain(name);

        /* No Permission check */
        // isRegistered is always unchecked as per JMX spec.

        return (repository.contains(name));
    }

    public String[] getDomains()  {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            // Check if the caller has the right to invoke 'getDomains'
            //
            checkMBeanPermission(mbeanServerName, (String) null, null, null, "getDomains");

            // Return domains
            //
            String[] domains = repository.getDomains();

            // Check if the caller has the right to invoke 'getDomains'
            // on each specific domain in the list.
            //
            List<String> result = new ArrayList<String>(domains.length);
            for (int i = 0; i < domains.length; i++) {
                try {
                    ObjectName dom =
                            Util.newObjectName(domains[i] + ":x=x");
                    checkMBeanPermission(mbeanServerName, (String) null, null, dom, "getDomains");
                    result.add(domains[i]);
                } catch (SecurityException e) {
                    // OK: Do not add this domain to the list
                }
            }

            // Make an array from result.
            //
            return result.toArray(new String[result.size()]);
        } else {
            return repository.getDomains();
        }
    }

    public Integer getMBeanCount() {
        return (repository.getCount());
    }

    public Object getAttribute(ObjectName name, String attribute)
        throws MBeanException, AttributeNotFoundException,
               InstanceNotFoundException, ReflectionException {

        if (name == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Object name cannot be null"),
                "Exception occurred trying to invoke the getter on the MBean");
        }
        if (attribute == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Attribute cannot be null"),
                "Exception occurred trying to invoke the getter on the MBean");
        }

        name = nonDefaultDomain(name);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "getAttribute",
                    "Attribute = " + attribute + ", ObjectName = " + name);
        }

        final DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName, instance, attribute,
                name, "getAttribute");

        try {
            return instance.getAttribute(attribute);
        } catch (AttributeNotFoundException e) {
            throw e;
        } catch (Throwable t) {
            rethrowMaybeMBeanException(t);
            throw new AssertionError(); // not reached
        }
    }

    public AttributeList getAttributes(ObjectName name, String[] attributes)
        throws InstanceNotFoundException, ReflectionException  {

        if (name == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("ObjectName name cannot be null"),
                "Exception occurred trying to invoke the getter on the MBean");
        }

        if (attributes == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Attributes cannot be null"),
                "Exception occurred trying to invoke the getter on the MBean");
        }

        name = nonDefaultDomain(name);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "getAttributes", "ObjectName = " + name);
        }

        final DynamicMBean instance = getMBean(name);
        final String[] allowedAttributes;
        final SecurityManager sm = System.getSecurityManager();
        if (sm == null)
            allowedAttributes = attributes;
        else {
            final String classname = getClassName(instance);

            // Check if the caller has the right to invoke 'getAttribute'
            //
            checkMBeanPermission(mbeanServerName, classname, null, name, "getAttribute");

            // Check if the caller has the right to invoke 'getAttribute'
            // on each specific attribute
            //
            List<String> allowedList =
                new ArrayList<String>(attributes.length);
            for (String attr : attributes) {
                try {
                    checkMBeanPermission(mbeanServerName, classname, attr,
                                         name, "getAttribute");
                    allowedList.add(attr);
                } catch (SecurityException e) {
                    // OK: Do not add this attribute to the list
                }
            }
            allowedAttributes =
                    allowedList.toArray(new String[allowedList.size()]);
        }

        try {
            return instance.getAttributes(allowedAttributes);
        } catch (Throwable t) {
            rethrow(t);
            throw new AssertionError();
        }
    }

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

        if (name == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("ObjectName name cannot be null"),
                "Exception occurred trying to invoke the setter on the MBean");
        }

        if (attribute == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Attribute cannot be null"),
                "Exception occurred trying to invoke the setter on the MBean");
        }

        name = nonDefaultDomain(name);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "setAttribute", "ObjectName = " + name +
                    ", Attribute = " + attribute.getName());
        }

        DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName, instance, attribute.getName(),
                             name, "setAttribute");

        try {
            instance.setAttribute(attribute);
        } catch (AttributeNotFoundException e) {
            throw e;
        } catch (InvalidAttributeValueException e) {
            throw e;
        } catch (Throwable t) {
            rethrowMaybeMBeanException(t);
            throw new AssertionError();
        }
    }

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

        if (name == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("ObjectName name cannot be null"),
                "Exception occurred trying to invoke the setter on the MBean");
        }

        if (attributes == null) {
            throw new RuntimeOperationsException(new
            IllegalArgumentException("AttributeList  cannot be null"),
            "Exception occurred trying to invoke the setter on the MBean");
        }

        name = nonDefaultDomain(name);

        final DynamicMBean instance = getMBean(name);
        final AttributeList allowedAttributes;
        final SecurityManager sm = System.getSecurityManager();
        if (sm == null)
            allowedAttributes = attributes;
        else {
            String classname = getClassName(instance);

            // Check if the caller has the right to invoke 'setAttribute'
            //
            checkMBeanPermission(mbeanServerName, classname, null, name, "setAttribute");

            // Check if the caller has the right to invoke 'setAttribute'
            // on each specific attribute
            //
            allowedAttributes = new AttributeList(attributes.size());
            for (Iterator i = attributes.iterator(); i.hasNext();) {
                try {
                    Attribute attribute = (Attribute) i.next();
                    checkMBeanPermission(mbeanServerName, classname, attribute.getName(),
                                         name, "setAttribute");
                    allowedAttributes.add(attribute);
                } catch (SecurityException e) {
                    // OK: Do not add this attribute to the list
                }
            }
        }
        try {
            return instance.setAttributes(allowedAttributes);
        } catch (Throwable t) {
            rethrow(t);
            throw new AssertionError();
        }
    }

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

        name = nonDefaultDomain(name);

        DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName, instance, operationName,
                name, "invoke");
        try {
            return instance.invoke(operationName, params, signature);
        } catch (Throwable t) {
            rethrowMaybeMBeanException(t);
            throw new AssertionError();
        }
    }

    /* Centralize some of the tedious exception wrapping demanded by the JMX
       spec. */
    private static void rethrow(Throwable t)
            throws ReflectionException {
        try {
            throw t;
        } catch (ReflectionException e) {
            throw e;
        } catch (RuntimeOperationsException e) {
            throw e;
        } catch (RuntimeErrorException e) {
            throw e;
        } catch (RuntimeException e) {
            throw new RuntimeMBeanException(e, e.toString());
        } catch (Error e) {
            throw new RuntimeErrorException(e, e.toString());
        } catch (Throwable t2) {
            // should not happen
            throw new RuntimeException("Unexpected exception", t2);
        }
    }

    private static void rethrowMaybeMBeanException(Throwable t)
            throws ReflectionException, MBeanException {
        if (t instanceof MBeanException)
            throw (MBeanException) t;
        rethrow(t);
    }

    /**
     * Register <code>object</code> in the repository, with the
     * given <code>name</code>.
     * This method is called by the various createMBean() flavours
     * and by registerMBean() after all MBean compliance tests
     * have been performed.
     * <p>
     * This method does not performed any kind of test compliance,
     * and the caller should make sure that the given <code>object</code>
     * is MBean compliant.
     * <p>
     * This methods performed all the basic steps needed for object
     * registration:
     * <ul>
     * <li>If the <code>object</code> implements the MBeanRegistration
     *     interface, it invokes preRegister() on the object.</li>
     * <li>Then the object is added to the repository with the given
     *     <code>name</code>.</li>
     * <li>Finally, if the <code>object</code> implements the
     *     MBeanRegistration interface, it invokes postRegister()
     *     on the object.</li>
     * </ul>
     * @param object A reference to a MBean compliant object.
     * @param name   The ObjectName of the <code>object</code> MBean.
     * @return the actual ObjectName with which the object was registered.
     * @exception InstanceAlreadyExistsException if an object is already
     *            registered with that name.
     * @exception MBeanRegistrationException if an exception occurs during
     *            registration.
     **/
    private ObjectInstance registerObject(String classname,
                                          Object object, ObjectName name)
        throws InstanceAlreadyExistsException,
               MBeanRegistrationException,
               NotCompliantMBeanException {

        if (object == null) {
            final RuntimeException wrapped =
                new IllegalArgumentException("Cannot add null object");
            throw new RuntimeOperationsException(wrapped,
                        "Exception occurred trying to register the MBean");
        }

        DynamicMBean mbean = Introspector.makeDynamicMBean(object);

        return registerDynamicMBean(classname, mbean, name);
    }

    private ObjectInstance registerDynamicMBean(String classname,
                                                DynamicMBean mbean,
                                                ObjectName name)
        throws InstanceAlreadyExistsException,
               MBeanRegistrationException,
               NotCompliantMBeanException {


        name = nonDefaultDomain(name);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "registerMBean", "ObjectName = " + name);
        }

        ObjectName logicalName = preRegister(mbean, server, name);

        // preRegister returned successfully, so from this point on we
        // must call postRegister(false) if there is any problem.
        boolean registered = false;
        boolean registerFailed = false;
        ResourceContext context = null;

        try {
            mbean = injectResources(mbean, server, logicalName);

            if (mbean instanceof DynamicMBean2) {
                try {
                    ((DynamicMBean2) mbean).preRegister2(server, logicalName);
                    registerFailed = true;  // until we succeed
                } catch (Exception e) {
                    if (e instanceof RuntimeException)
                        throw (RuntimeException) e;
                    if (e instanceof InstanceAlreadyExistsException)
                        throw (InstanceAlreadyExistsException) e;
                    throw new RuntimeException(e);
                }
            }

            if (logicalName != name && logicalName != null) {
                logicalName =
                        ObjectName.getInstance(nonDefaultDomain(logicalName));
            }

            checkMBeanPermission(mbeanServerName, classname, null, logicalName,
                    "registerMBean");

            if (logicalName == null) {
                final RuntimeException wrapped =
                    new IllegalArgumentException("No object name specified");
                throw new RuntimeOperationsException(wrapped,
                            "Exception occurred trying to register the MBean");
            }

            final Object resource = getResource(mbean);

            // Register the MBean with the repository.
            // Returns the resource context that was used.
            // The returned context does nothing for regular MBeans.
            // For ClassLoader MBeans and JMXNamespace (and JMXDomain)
            // MBeans - the context makes it possible to register these
            // objects with the appropriate framework artifacts, such as
            // the CLR or the dispatcher, from within the repository lock.
            // In case of success, we also need to call context.done() at the
            // end of this method.
            //
            context = registerWithRepository(resource, mbean, logicalName);


            registerFailed = false;
            registered = true;

        } finally {
            try {
                postRegister(logicalName, mbean, registered, registerFailed);
            } finally {
                if (registered && context!=null) context.done();
            }
        }
        return new ObjectInstance(logicalName, classname);
    }

    private static void throwMBeanRegistrationException(Throwable t, String where)
    throws MBeanRegistrationException {
        if (t instanceof RuntimeException) {
            throw new RuntimeMBeanException((RuntimeException)t,
                    "RuntimeException thrown " + where);
        } else if (t instanceof Error) {
            throw new RuntimeErrorException((Error)t,
                    "Error thrown " + where);
        } else if (t instanceof MBeanRegistrationException) {
            throw (MBeanRegistrationException)t;
        } else if (t instanceof Exception) {
            throw new MBeanRegistrationException((Exception)t,
                    "Exception thrown " + where);
        } else // neither Error nor Exception??
            throw new RuntimeException(t);
    }

    private static ObjectName preRegister(
            DynamicMBean mbean, MBeanServer mbs, ObjectName name)
            throws InstanceAlreadyExistsException, MBeanRegistrationException {

        ObjectName newName = null;

        try {
            if (mbean instanceof MBeanRegistration)
                newName = ((MBeanRegistration) mbean).preRegister(mbs, name);
        } catch (Throwable t) {
            throwMBeanRegistrationException(t, "in preRegister method");
        }

        if (newName != null) return newName;
        else return name;
    }

    private static DynamicMBean injectResources(
            DynamicMBean mbean, MBeanServer mbs, ObjectName name)
    throws MBeanRegistrationException {
        try {
            Object resource = getResource(mbean);
            MBeanInjector.inject(resource, mbs, name);
            if (MBeanInjector.injectsSendNotification(resource)) {
                NotificationBroadcasterSupport nbs =
                        new NotificationBroadcasterSupport();
                MBeanInjector.injectSendNotification(resource, nbs);
                mbean = NotifySupport.wrap(mbean, nbs);
            }
            return mbean;
        } catch (Throwable t) {
            throwMBeanRegistrationException(t, "injecting @Resources");
            return null;  // not reached
        }
    }

    private static void postRegister(
            ObjectName logicalName, DynamicMBean mbean,
            boolean registrationDone, boolean registerFailed) {

        if (registerFailed && mbean instanceof DynamicMBean2)
            ((DynamicMBean2) mbean).registerFailed();
        try {
            if (mbean instanceof MBeanRegistration)
                ((MBeanRegistration) mbean).postRegister(registrationDone);
        } catch (RuntimeException e) {
            MBEANSERVER_LOGGER.fine("While registering MBean ["+logicalName+
                    "]: " + "Exception thrown by postRegister: " +
                    "rethrowing <"+e+">, but keeping the MBean registered");
            throw new RuntimeMBeanException(e,
                      "RuntimeException thrown in postRegister method: "+
                      "rethrowing <"+e+">, but keeping the MBean registered");
        } catch (Error er) {
            MBEANSERVER_LOGGER.fine("While registering MBean ["+logicalName+
                    "]: " + "Error thrown by postRegister: " +
                    "rethrowing <"+er+">, but keeping the MBean registered");
            throw new RuntimeErrorException(er,
                      "Error thrown in postRegister method: "+
                      "rethrowing <"+er+">, but keeping the MBean registered");
        }
    }

    private static void preDeregisterInvoke(MBeanRegistration moi)
            throws MBeanRegistrationException {
        try {
            moi.preDeregister();
        } catch (Throwable t) {
            throwMBeanRegistrationException(t, "in preDeregister method");
        }
    }

    private static void postDeregisterInvoke(ObjectName mbean,
            MBeanRegistration moi) {
        try {
            moi.postDeregister();
        } catch (RuntimeException e) {
            MBEANSERVER_LOGGER.fine("While unregistering MBean ["+mbean+
                    "]: " + "Exception thrown by postDeregister: " +
                    "rethrowing <"+e+">, although the MBean is succesfully " +
                    "unregistered");
            throw new RuntimeMBeanException(e,
                      "RuntimeException thrown in postDeregister method: "+
                      "rethrowing <"+e+
                      ">, although the MBean is sucessfully unregistered");
        } catch (Error er) {
            MBEANSERVER_LOGGER.fine("While unregistering MBean ["+mbean+
                    "]: " + "Error thrown by postDeregister: " +
                    "rethrowing <"+er+">, although the MBean is succesfully " +
                    "unregistered");
            throw new RuntimeErrorException(er,
                      "Error thrown in postDeregister method: "+
                      "rethrowing <"+er+
                      ">, although the MBean is sucessfully unregistered");
        }
    }

    /**
     * Gets a specific MBean controlled by the DefaultMBeanServerInterceptor.
     * The name must have a non-default domain.
     */
    private DynamicMBean getMBean(ObjectName name)
        throws InstanceNotFoundException {

        if (name == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Object name cannot be null"),
                               "Exception occurred trying to get an MBean");
        }
        DynamicMBean obj = repository.retrieve(name);
        if (obj == null) {
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
                MBEANSERVER_LOGGER.logp(Level.FINER,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "getMBean", name + " : Found no object");
            }
            throw new InstanceNotFoundException(name.toString());
        }
        return obj;
    }

    private static Object getResource(DynamicMBean mbean) {
        if (mbean instanceof DynamicWrapperMBean)
            return ((DynamicWrapperMBean) mbean).getWrappedObject();
        else
            return mbean;
    }

    private static ClassLoader getResourceLoader(DynamicMBean mbean) {
        if (mbean instanceof DynamicWrapperMBean)
            return ((DynamicWrapperMBean) mbean).getWrappedClassLoader();
        else
            return mbean.getClass().getClassLoader();
    }

    private ObjectName nonDefaultDomain(ObjectName name) {
        if (name == null || name.getDomain().length() > 0)
            return name;

        /* The ObjectName looks like ":a=b", and that's what its
           toString() will return in this implementation.  So
           we can just stick the default domain in front of it
           to get a non-default-domain name.  We depend on the
           fact that toString() works like that and that it
           leaves wildcards in place (so we can detect an error
           if one is supplied where it shouldn't be).  */
        final String completeName = domain + name;

        return Util.newObjectName(completeName);
    }

    public String getDefaultDomain()  {
        return domain;
    }

    /*
     * Notification handling.
     *
     * This is not trivial, because the MBeanServer translates the
     * source of a received notification from a reference to an MBean
     * into the ObjectName of that MBean.  While that does make
     * notification sending easier for MBean writers, it comes at a
     * considerable cost.  We need to replace the source of a
     * notification, which is basically wrong if there are also
     * listeners registered directly with the MBean (without going
     * through the MBean server).  We also need to wrap the listener
     * supplied by the client of the MBeanServer with a listener that
     * performs the substitution before forwarding.  This is why we
     * strongly discourage people from putting MBean references in the
     * source of their notifications.  Instead they should arrange to
     * put the ObjectName there themselves.
     *
     * However, existing code relies on the substitution, so we are
     * stuck with it.
     *
     * Here's how we handle it.  When you add a listener, we make a
     * ListenerWrapper around it.  We look that up in the
     * listenerWrappers map, and if there was already a wrapper for
     * that listener with the given ObjectName, we reuse it.  This map
     * is a WeakHashMap, so a listener that is no longer registered
     * with any MBean can be garbage collected.
     *
     * We cannot use simpler solutions such as always creating a new
     * wrapper or always registering the same listener with the MBean
     * and using the handback to find the client's original listener.
     * The reason is that we need to support the removeListener
     * variant that removes all (listener,filter,handback) triples on
     * a broadcaster that have a given listener.  And we do not have
     * any way to inspect a broadcaster's internal list of triples.
     * So the same client listener must always map to the same
     * listener registered with the broadcaster.
     *
     * Another possible solution would be to map from ObjectName to
     * list of listener wrappers (or IdentityHashMap of listener
     * wrappers), making this list the first time a listener is added
     * on a given MBean, and removing it when the MBean is removed.
     * This is probably more costly in memory, but could be useful if
     * some day we don't want to rely on weak references.
     */
    public void addNotificationListener(ObjectName name,
                                        NotificationListener listener,
                                        NotificationFilter filter,
                                        Object handback)
            throws InstanceNotFoundException {

        // ------------------------------
        // ------------------------------
        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "addNotificationListener", "ObjectName = " + name);
        }

        DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName, instance, null,
                name, "addNotificationListener");

        NotificationBroadcaster broadcaster =
                getNotificationBroadcaster(name, instance,
                                           NotificationBroadcaster.class);

        // ------------------
        // Check listener
        // ------------------
        if (listener == null) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException("Null listener"),"Null listener");
        }

        NotificationListener listenerWrapper =
            getListenerWrapper(listener, name, instance, true);
        broadcaster.addNotificationListener(listenerWrapper, filter, handback);
    }

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

        // ------------------------------
        // ------------------------------

        // ----------------
        // Get listener object
        // ----------------
        DynamicMBean instance = getMBean(listener);
        Object resource = getResource(instance);
        if (!(resource instanceof NotificationListener)) {
            throw new RuntimeOperationsException(new
                IllegalArgumentException(listener.getCanonicalName()),
                "The MBean " + listener.getCanonicalName() +
                "does not implement the NotificationListener interface") ;
        }

        // ----------------
        // Add a listener on an MBean
        // ----------------
        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "addNotificationListener",
                    "ObjectName = " + name + ", Listener = " + listener);
        }
        server.addNotificationListener(name,(NotificationListener) resource,
                                       filter, handback) ;
    }

    public void removeNotificationListener(ObjectName name,
                                           NotificationListener listener)
            throws InstanceNotFoundException, ListenerNotFoundException {
        removeNotificationListener(name, listener, null, null, true);
    }

    public void removeNotificationListener(ObjectName name,
                                           NotificationListener listener,
                                           NotificationFilter filter,
                                           Object handback)
            throws InstanceNotFoundException, ListenerNotFoundException {
        removeNotificationListener(name, listener, filter, handback, false);
    }

    public void removeNotificationListener(ObjectName name,
                                           ObjectName listener)
            throws InstanceNotFoundException, ListenerNotFoundException {
        NotificationListener instance = getListener(listener);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "removeNotificationListener",
                    "ObjectName = " + name + ", Listener = " + listener);
        }
        server.removeNotificationListener(name, instance);
    }

    public void removeNotificationListener(ObjectName name,
                                           ObjectName listener,
                                           NotificationFilter filter,
                                           Object handback)
            throws InstanceNotFoundException, ListenerNotFoundException {

        NotificationListener instance = getListener(listener);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "removeNotificationListener",
                    "ObjectName = " + name + ", Listener = " + listener);
        }
        server.removeNotificationListener(name, instance, filter, handback);
    }

    private NotificationListener getListener(ObjectName listener)
        throws ListenerNotFoundException {
        // ----------------
        // Get listener object
        // ----------------
        DynamicMBean instance;
        try {
            instance = getMBean(listener);
        } catch (InstanceNotFoundException e) {
            throw EnvHelp.initCause(
                          new ListenerNotFoundException(e.getMessage()), e);
        }

        Object resource = getResource(instance);
        if (!(resource instanceof NotificationListener)) {
            final RuntimeException exc =
                new IllegalArgumentException(listener.getCanonicalName());
            final String msg =
                "MBean " + listener.getCanonicalName() + " does not " +
                "implement " + NotificationListener.class.getName();
            throw new RuntimeOperationsException(exc, msg);
        }
        return (NotificationListener) resource;
    }

    private void removeNotificationListener(ObjectName name,
                                            NotificationListener listener,
                                            NotificationFilter filter,
                                            Object handback,
                                            boolean removeAll)
            throws InstanceNotFoundException, ListenerNotFoundException {

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "removeNotificationListener", "ObjectName = " + name);
        }

        DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName, instance, null, name,
                             "removeNotificationListener");

        /* We could simplify the code by assigning broadcaster after
           assigning listenerWrapper, but that would change the error
           behavior when both the broadcaster and the listener are
           erroneous.  */

        Class<? extends NotificationBroadcaster> reqClass =
            removeAll ? NotificationBroadcaster.class : NotificationEmitter.class;
        NotificationBroadcaster broadcaster =
            getNotificationBroadcaster(name, instance, reqClass);

        NotificationListener listenerWrapper =
            getListenerWrapper(listener, name, instance, false);

        if (listenerWrapper == null)
            throw new ListenerNotFoundException("Unknown listener");

        if (removeAll)
            broadcaster.removeNotificationListener(listenerWrapper);
        else {
            NotificationEmitter emitter = (NotificationEmitter) broadcaster;
            emitter.removeNotificationListener(listenerWrapper,
                                               filter,
                                               handback);
        }
    }

    private static <T extends NotificationBroadcaster>
            T getNotificationBroadcaster(ObjectName name, Object instance,
                                         Class<T> reqClass) {
        if (reqClass.isInstance(instance))
            return reqClass.cast(instance);
        if (instance instanceof DynamicWrapperMBean)
            instance = ((DynamicWrapperMBean) instance).getWrappedObject();
        if (reqClass.isInstance(instance))
            return reqClass.cast(instance);
        final RuntimeException exc =
            new IllegalArgumentException(name.getCanonicalName());
        final String msg =
            "MBean " + name.getCanonicalName() + " does not " +
            "implement " + reqClass.getName();
        throw new RuntimeOperationsException(exc, msg);
    }

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

        // ------------------------------
        // ------------------------------

        DynamicMBean moi = getMBean(name);
        final MBeanInfo mbi;
        try {
            mbi = moi.getMBeanInfo();
        } catch (RuntimeMBeanException e) {
            throw e;
        } catch (RuntimeErrorException e) {
            throw e;
        } catch (RuntimeException e) {
            throw new RuntimeMBeanException(e,
                    "getMBeanInfo threw RuntimeException");
        } catch (Error e) {
            throw new RuntimeErrorException(e, "getMBeanInfo threw Error");
        }
        if (mbi == null)
            throw new JMRuntimeException("MBean " + name +
                                         "has no MBeanInfo");

        checkMBeanPermission(mbeanServerName, mbi.getClassName(), null, name, "getMBeanInfo");

        return mbi;
    }

    public boolean isInstanceOf(ObjectName name, String className)
        throws InstanceNotFoundException {

        final DynamicMBean instance = getMBean(name);
        checkMBeanPermission(mbeanServerName,
                instance, null, name, "isInstanceOf");

        try {
            Object resource = getResource(instance);

            final String resourceClassName =
                    (resource instanceof DynamicMBean) ?
                        getClassName((DynamicMBean) resource) :
                        resource.getClass().getName();

            if (resourceClassName.equals(className))
                return true;
            final ClassLoader cl = getResourceLoader(instance);

            final Class<?> classNameClass = Class.forName(className, false, cl);
            if (classNameClass.isInstance(resource))
                return true;

            // Ensure that isInstanceOf(NotificationEmitter) is true when
            // the MBean is a NotificationEmitter by virtue of a @Resource
            // annotation specifying a SendNotification resource.
            // This is a hack.
            if (instance instanceof NotificationBroadcaster &&
                    classNameClass.isAssignableFrom(NotificationEmitter.class))
                return true;

            final Class<?> resourceClass = Class.forName(resourceClassName, false, cl);
            return classNameClass.isAssignableFrom(resourceClass);
        } catch (Exception x) {
            /* Could be SecurityException or ClassNotFoundException */
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
                MBEANSERVER_LOGGER.logp(Level.FINEST,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "isInstanceOf", "Exception calling isInstanceOf", x);
            }
            return false;
        }

    }

    /**
     * <p>Return the {@link java.lang.ClassLoader} that was used for
     * loading the class of the named MBean.
     * @param mbeanName The ObjectName of the MBean.
     * @return The ClassLoader used for that MBean.
     * @exception InstanceNotFoundException if the named MBean is not found.
     */
    public ClassLoader getClassLoaderFor(ObjectName mbeanName)
        throws InstanceNotFoundException {

        DynamicMBean instance = getMBean(mbeanName);
        checkMBeanPermission(mbeanServerName, instance, null, mbeanName,
                "getClassLoaderFor");
        return getResourceLoader(instance);
    }

    /**
     * <p>Return the named {@link java.lang.ClassLoader}.
     * @param loaderName The ObjectName of the ClassLoader.
     * @return The named ClassLoader.
     * @exception InstanceNotFoundException if the named ClassLoader
     * is not found.
     */
    public ClassLoader getClassLoader(ObjectName loaderName)
            throws InstanceNotFoundException {

        if (loaderName == null) {
            checkMBeanPermission(mbeanServerName, (String) null, null, null, "getClassLoader");
            return server.getClass().getClassLoader();
        }

        DynamicMBean instance = getMBean(loaderName);
        checkMBeanPermission(mbeanServerName, instance, null, loaderName,
                "getClassLoader");

        Object resource = getResource(instance);

        /* Check if the given MBean is a ClassLoader */
        if (!(resource instanceof ClassLoader))
            throw new InstanceNotFoundException(loaderName.toString() +
                                                " is not a classloader");

        return (ClassLoader) resource;
    }

    /**
     * Sends an MBeanServerNotifications with the specified type for the
     * MBean with the specified ObjectName
     */
    private void sendNotification(String NotifType, ObjectName name) {

        // ------------------------------
        // ------------------------------

        // ---------------------
        // Create notification
        // ---------------------
        MBeanServerNotification notif = new MBeanServerNotification(
            NotifType,MBeanServerDelegate.DELEGATE_NAME,0,name);

        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "sendNotification", NotifType + " " + name);
        }

        delegate.sendNotification(notif);
    }

    /**
     * Applies the specified queries to the set of NamedObjects.
     */
    private Set<ObjectName>
        objectNamesFromFilteredNamedObjects(Set<NamedObject> list,
                                            QueryExp query) {
        Set<ObjectName> result = new HashSet<ObjectName>();
        // No query ...
        if (query == null) {
            for (NamedObject no : list) {
                result.add(no.getName());
            }
        } else {
            // Access the filter
            final MBeanServer oldServer = QueryEval.getMBeanServer();
            query.setMBeanServer(server);
            try {
                for (NamedObject no : list) {
                    boolean res;
                    try {
                        res = query.apply(no.getName());
                    } catch (Exception e) {
                        res = false;
                    }
                    if (res) {
                        result.add(no.getName());
                    }
                }
            } finally {
                /*
                 * query.setMBeanServer is probably
                 * QueryEval.setMBeanServer so put back the old
                 * value.  Since that method uses a ThreadLocal
                 * variable, this code is only needed for the
                 * unusual case where the user creates a custom
                 * QueryExp that calls a nested query on another
                 * MBeanServer.
                 */
                query.setMBeanServer(oldServer);
            }
        }
        return result;
    }

    /**
     * Applies the specified queries to the set of NamedObjects.
     */
    private Set<ObjectInstance>
        objectInstancesFromFilteredNamedObjects(Set<NamedObject> list,
                                                QueryExp query) {
        Set<ObjectInstance> result = new HashSet<ObjectInstance>();
        // No query ...
        if (query == null) {
            for (NamedObject no : list) {
                final DynamicMBean obj = no.getObject();
                final String className = safeGetClassName(obj);
                result.add(new ObjectInstance(no.getName(), className));
            }
        } else {
            // Access the filter
            MBeanServer oldServer = QueryEval.getMBeanServer();
            query.setMBeanServer(server);
            try {
                for (NamedObject no : list) {
                    final DynamicMBean obj = no.getObject();
                    boolean res;
                    try {
                        res = query.apply(no.getName());
                    } catch (Exception e) {
                        res = false;
                    }
                    if (res) {
                        String className = safeGetClassName(obj);
                        result.add(new ObjectInstance(no.getName(), className));
                    }
                }
            } finally {
                /*
                 * query.setMBeanServer is probably
                 * QueryEval.setMBeanServer so put back the old
                 * value.  Since that method uses a ThreadLocal
                 * variable, this code is only needed for the
                 * unusual case where the user creates a custom
                 * QueryExp that calls a nested query on another
                 * MBeanServer.
                 */
                query.setMBeanServer(oldServer);
            }
        }
        return result;
    }

    private static String safeGetClassName(DynamicMBean mbean) {
        try {
            return getClassName(mbean);
        } catch (Exception e) {
            if (MBEANSERVER_LOGGER.isLoggable(Level.FINEST)) {
                MBEANSERVER_LOGGER.logp(Level.FINEST,
                        DefaultMBeanServerInterceptor.class.getName(),
                        "safeGetClassName",
                        "Exception getting MBean class name", e);
            }
            return null;
        }
    }

    /**
     * Applies the specified queries to the set of ObjectInstances.
     */
    private Set<ObjectInstance>
            filterListOfObjectInstances(Set<ObjectInstance> list,
                                        QueryExp query) {
        // Null query.
        //
        if (query == null) {
            return list;
        } else {
            Set<ObjectInstance> result = new HashSet<ObjectInstance>();
            // Access the filter.
            //
            for (ObjectInstance oi : list) {
                boolean res = false;
                MBeanServer oldServer = QueryEval.getMBeanServer();
                query.setMBeanServer(server);
                try {
                    res = query.apply(oi.getObjectName());
                } catch (Exception e) {
                    res = false;
                } finally {
                    /*
                     * query.setMBeanServer is probably
                     * QueryEval.setMBeanServer so put back the old
                     * value.  Since that method uses a ThreadLocal
                     * variable, this code is only needed for the
                     * unusual case where the user creates a custom
                     * QueryExp that calls a nested query on another
                     * MBeanServer.
                     */
                    query.setMBeanServer(oldServer);
                }
                if (res) {
                    result.add(oi);
                }
            }
            return result;
        }
    }

    /*
     * Get the existing wrapper for this listener, name, and mbean, if
     * there is one.  Otherwise, if "create" is true, create and
     * return one.  Otherwise, return null.
     *
     * We use a WeakHashMap so that if the only reference to a user
     * listener is in listenerWrappers, it can be garbage collected.
     * This requires a certain amount of care, because only the key in
     * a WeakHashMap is weak; the value is strong.  We need to recover
     * the existing wrapper object (not just an object that is equal
     * to it), so we would like listenerWrappers to map any
     * ListenerWrapper to the canonical ListenerWrapper for that
     * (listener,name,mbean) set.  But we do not want this canonical
     * wrapper to be referenced strongly.  Therefore we put it inside
     * a WeakReference and that is the value in the WeakHashMap.
     */
    private NotificationListener getListenerWrapper(NotificationListener l,
                                                    ObjectName name,
                                                    DynamicMBean mbean,
                                                    boolean create) {
        Object resource = getResource(mbean);
        ListenerWrapper wrapper = new ListenerWrapper(l, name, resource);
        synchronized (listenerWrappers) {
            WeakReference<ListenerWrapper> ref = listenerWrappers.get(wrapper);
            if (ref != null) {
                NotificationListener existing = ref.get();
                if (existing != null)
                    return existing;
            }
            if (create) {
                ref = new WeakReference<ListenerWrapper>(wrapper);
                listenerWrappers.put(wrapper, ref);
                return wrapper;
            } else
                return null;
        }
    }

    private static class ListenerWrapper implements NotificationListener {
        ListenerWrapper(NotificationListener l, ObjectName name,
                        Object mbean) {
            this.listener = l;
            this.name = name;
            this.mbean = mbean;
        }

        public void handleNotification(Notification notification,
                                       Object handback) {
            if (notification != null) {
                if (notification.getSource() == mbean)
                    notification.setSource(name);
            }

            /*
             * Listeners are not supposed to throw exceptions.  If
             * this one does, we could remove it from the MBean.  It
             * might indicate that a connector has stopped working,
             * for instance, and there is no point in sending future
             * notifications over that connection.  However, this
             * seems rather drastic, so instead we propagate the
             * exception and let the broadcaster handle it.
             */
            listener.handleNotification(notification, handback);
        }

        @Override
        public boolean equals(Object o) {
            if (!(o instanceof ListenerWrapper))
                return false;
            ListenerWrapper w = (ListenerWrapper) o;
            return (w.listener == listener && w.mbean == mbean
                    && w.name.equals(name));
            /*
             * We compare all three, in case the same MBean object
             * gets unregistered and then reregistered under a
             * different name, or the same name gets assigned to two
             * different MBean objects at different times.  We do the
             * comparisons in this order to avoid the slow
             * ObjectName.equals when possible.
             */
        }

        @Override
        public int hashCode() {
            return (System.identityHashCode(listener) ^
                    System.identityHashCode(mbean));
            /*
             * We do not include name.hashCode() in the hash because
             * computing it is slow and usually we will not have two
             * instances of ListenerWrapper with the same mbean but
             * different ObjectNames.  That can happen if the MBean is
             * unregistered from one name and reregistered with
             * another, and there is no garbage collection between; or
             * if the same object is registered under two names (which
             * is not recommended because MBeanRegistration will
             * break).  But even in these unusual cases the hash code
             * does not have to be unique.
             */
        }

        private NotificationListener listener;
        private ObjectName name;
        private Object mbean;
    }

    // SECURITY CHECKS
    //----------------

    private static String getClassName(DynamicMBean mbean) {
        if (mbean instanceof DynamicMBean2)
            return ((DynamicMBean2) mbean).getClassName();
        else
            return mbean.getMBeanInfo().getClassName();
    }

    private static void checkMBeanPermission(String mbeanServerName,
                                             DynamicMBean mbean,
                                             String member,
                                             ObjectName objectName,
                                             String actions) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkMBeanPermission(mbeanServerName,
                                 safeGetClassName(mbean),
                                 member,
                                 objectName,
                                 actions);
        }
    }

    private static void checkMBeanPermission(String mbeanServerName,
                                             String classname,
                                             String member,
                                             ObjectName objectName,
                                             String actions) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            Permission perm = new MBeanPermission(mbeanServerName,
                                                  classname,
                                                  member,
                                                  objectName,
                                                  actions);
            sm.checkPermission(perm);
        }
    }

    private static void checkMBeanTrustPermission(final Class theClass)
        throws SecurityException {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            Permission perm = new MBeanTrustPermission("register");
            PrivilegedAction<ProtectionDomain> act =
                new PrivilegedAction<ProtectionDomain>() {
                    public ProtectionDomain run() {
                        return theClass.getProtectionDomain();
                    }
                };
            ProtectionDomain pd = AccessController.doPrivileged(act);
            AccessControlContext acc =
                new AccessControlContext(new ProtectionDomain[] { pd });
            sm.checkPermission(perm, acc);
        }
    }

    // ------------------------------------------------------------------
    //
    // Dealing with registration of special MBeans in the repository.
    //
    // ------------------------------------------------------------------

    /**
     * A RegistrationContext that makes it possible to perform additional
     * post registration actions (or post unregistration actions) outside
     * of the repository lock, once postRegister (or postDeregister) has
     * been called.
     * The method {@code done()} will be called in registerMBean or
     * unregisterMBean, at the end.
     */
    private static interface ResourceContext extends RegistrationContext {
        public void done();
        /** An empty ResourceContext which does nothing **/
        public static final ResourceContext NONE = new ResourceContext() {
            public void done() {}
            public void registering() {}
            public void unregistered() {}
        };
    }

    /**
     * Adds a MBean in the repository,
     * sends MBeanServerNotification.REGISTRATION_NOTIFICATION,
     * returns ResourceContext for special resources such as ClassLoaders
     * or JMXNamespaces. For regular MBean this method returns
     * ResourceContext.NONE.
     * @return a ResourceContext for special resources such as ClassLoaders
     *         or JMXNamespaces.
     */
    private ResourceContext registerWithRepository(
            final Object resource,
            final DynamicMBean object,
            final ObjectName logicalName)
            throws InstanceAlreadyExistsException,
            MBeanRegistrationException {

        // this will throw an exception if the pair (resource, logicalName)
        // violates namespace conventions - for instance, if logicalName
        // ends with // but resource is not a JMXNamespace.
        //
        checkResourceObjectNameConstraints(resource, logicalName);

        // Creates a registration context, if needed.
        //
        final ResourceContext context =
                makeResourceContextFor(resource, logicalName);


        repository.addMBean(object, logicalName, context);
        // May throw InstanceAlreadyExistsException

        // ---------------------
        // Send create event
        // ---------------------
        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "addObject", "Send create notification of object " +
                    logicalName.getCanonicalName());
        }

        sendNotification(
                MBeanServerNotification.REGISTRATION_NOTIFICATION,
                logicalName);

        return context;
    }

    /**
     * Removes a MBean in the repository,
     * sends MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
     * returns ResourceContext for special resources such as ClassLoaders
     * or JMXNamespaces, or null. For regular MBean this method returns
     * ResourceContext.NONE.
     *
     * @return a ResourceContext for special resources such as ClassLoaders
     *         or JMXNamespaces.
     */
    private ResourceContext unregisterFromRepository(
            final Object resource,
            final DynamicMBean object,
            final ObjectName logicalName)
            throws InstanceNotFoundException {

        // Creates a registration context, if needed.
        //
        final ResourceContext context =
                makeResourceContextFor(resource, logicalName);


        repository.remove(logicalName, context);

        // ---------------------
        // Send deletion event
        // ---------------------
        if (MBEANSERVER_LOGGER.isLoggable(Level.FINER)) {
            MBEANSERVER_LOGGER.logp(Level.FINER,
                    DefaultMBeanServerInterceptor.class.getName(),
                    "unregisterMBean", "Send delete notification of object " +
                    logicalName.getCanonicalName());
        }

        sendNotification(MBeanServerNotification.UNREGISTRATION_NOTIFICATION,
                logicalName);
        return context;
    }


    /**
     * Checks that the ObjectName is legal with regards to the
     * type of the MBean resource.
     * If the MBean name is  domain:type=JMXDomain, the
     *     MBean must be a JMXDomain.
     * If the MBean name is  namespace//:type=JMXNamespace, the
     *     MBean must be a JMXNamespace.
     * If the MBean is a JMXDomain, its name
     *      must be domain:type=JMXDomain.
     * If the MBean is a JMXNamespace,  its name
     *      must be namespace//:type=JMXNamespace.
     */
    private void checkResourceObjectNameConstraints(Object resource,
            ObjectName logicalName)
            throws MBeanRegistrationException {
        try {
            dispatcher.checkLocallyRegistrable(resource, logicalName);
        } catch (Throwable x) {
            DefaultMBeanServerInterceptor.throwMBeanRegistrationException(x, "validating ObjectName");
        }
    }

    /**
     * Registers a JMXNamespace with the dispatcher.
     * This method is called by the ResourceContext from within the
     * repository lock.
     * @param namespace    The JMXNamespace
     * @param logicalName  The JMXNamespaceMBean ObjectName
     * @param postQueue    A queue that will be processed after postRegister.
     */
    private void addJMXNamespace(JMXNamespace namespace,
            final ObjectName logicalName,
            final Queue<Runnable> postQueue) {
        dispatcher.addNamespace(logicalName, namespace, postQueue);
    }

    /**
     * Unregisters a JMXNamespace from the dispatcher.
     * This method is called by the ResourceContext from within the
     * repository lock.
     * @param namespace    The JMXNamespace
     * @param logicalName  The JMXNamespaceMBean ObjectName
     * @param postQueue    A queue that will be processed after postDeregister.
     */
    private void removeJMXNamespace(JMXNamespace namespace,
            final ObjectName logicalName,
            final Queue<Runnable> postQueue) {
        dispatcher.removeNamespace(logicalName, namespace, postQueue);
    }

    /**
     * Registers a ClassLoader with the CLR.
     * This method is called by the ResourceContext from within the
     * repository lock.
     * @param loader       The ClassLoader.
     * @param logicalName  The ClassLoader MBean ObjectName.
     */
    private void addClassLoader(ClassLoader loader,
            final ObjectName logicalName) {
        /**
         * Called when the newly registered MBean is a ClassLoader
         * If so, tell the ClassLoaderRepository (CLR) about it.  We do
         * this even if the loader is a PrivateClassLoader.  In that
         * case, the CLR remembers the loader for use when it is
         * explicitly named (e.g. as the loader in createMBean) but
         * does not add it to the list that is consulted by
         * ClassLoaderRepository.loadClass.
         */
        final ModifiableClassLoaderRepository clr =
                instantiator.getClassLoaderRepository();
        if (clr == null) {
            final RuntimeException wrapped =
                    new IllegalArgumentException(
                    "Dynamic addition of class loaders" +
                    " is not supported");
            throw new RuntimeOperationsException(wrapped,
                    "Exception occurred trying to register" +
                    " the MBean as a class loader");
        }
        clr.addClassLoader(logicalName, loader);
    }

    /**
     * Unregisters a ClassLoader from the CLR.
     * This method is called by the ResourceContext from within the
     * repository lock.
     * @param loader       The ClassLoader.
     * @param logicalName  The ClassLoader MBean ObjectName.
     */
    private void removeClassLoader(ClassLoader loader,
            final ObjectName logicalName) {
        /**
         * Removes the  MBean from the default loader repository.
         */
        if (loader != server.getClass().getClassLoader()) {
            final ModifiableClassLoaderRepository clr =
                    instantiator.getClassLoaderRepository();
            if (clr != null) {
                clr.removeClassLoader(logicalName);
            }
        }
    }


    /**
     * Creates a ResourceContext for a JMXNamespace MBean.
     * The resource context makes it possible to add the JMXNamespace to
     * (ResourceContext.registering) or resp. remove the JMXNamespace from
     * (ResourceContext.unregistered) the NamespaceDispatchInterceptor
     * when the associated MBean is added to or resp. removed from the
     * repository.
     * Note: JMXDomains are special sub classes of JMXNamespaces and
     *       are also handled by this object.
     *
     * @param namespace    The JMXNamespace MBean being registered or
     *                     unregistered.
     * @param logicalName  The name of the JMXNamespace MBean.
     * @return a ResourceContext that takes in charge the addition or removal
     *         of the namespace to or from the NamespaceDispatchInterceptor.
     */
    private ResourceContext createJMXNamespaceContext(
            final JMXNamespace namespace,
            final ObjectName logicalName) {
        final Queue<Runnable> doneTaskQueue = new LinkedList<Runnable>();
        return new ResourceContext() {

            public void registering() {
                addJMXNamespace(namespace, logicalName, doneTaskQueue);
            }

            public void unregistered() {
                removeJMXNamespace(namespace, logicalName,
                                   doneTaskQueue);
            }

            public void done() {
                for (Runnable r : doneTaskQueue) {
                    try {
                        r.run();
                    } catch (RuntimeException x) {
                        MBEANSERVER_LOGGER.log(Level.FINE,
                                "Failed to process post queue for "+
                                logicalName, x);
                    }
                }
            }
        };
    }

    /**
     * Creates a ResourceContext for a ClassLoader MBean.
     * The resource context makes it possible to add the ClassLoader to
     * (ResourceContext.registering) or resp. remove the ClassLoader from
     * (ResourceContext.unregistered) the CLR
     * when the associated MBean is added to or resp. removed from the
     * repository.
     *
     * @param loader       The ClassLoader MBean being registered or
     *                     unregistered.
     * @param logicalName  The name of the ClassLoader MBean.
     * @return a ResourceContext that takes in charge the addition or removal
     *         of the loader to or from the CLR.
     */
    private ResourceContext createClassLoaderContext(
            final ClassLoader loader,
            final ObjectName logicalName) {
        return new ResourceContext() {

            public void registering() {
                addClassLoader(loader, logicalName);
            }

            public void unregistered() {
                removeClassLoader(loader, logicalName);
            }

            public void done() {
            }
        };
    }

    /**
     * Creates a ResourceContext for the given resource.
     * If the resource does not need a ResourceContext, returns
     * ResourceContext.NONE.
     * At this time, only JMXNamespaces and ClassLoaders need a
     * ResourceContext.
     *
     * @param resource     The resource being registered or unregistered.
     * @param logicalName  The name of the associated MBean.
     * @return
     */
    private ResourceContext makeResourceContextFor(Object resource,
            ObjectName logicalName) {
        if (resource instanceof JMXNamespace) {
            return createJMXNamespaceContext((JMXNamespace) resource,
                    logicalName);
        }
        if (resource instanceof ClassLoader) {
            return createClassLoaderContext((ClassLoader) resource,
                    logicalName);
        }
        return ResourceContext.NONE;
    }


}