API Overview API Index Package Overview Direct link to this page
JDK 1.6
  javax.management.modelmbean. RequiredModelMBean View Javadoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657

/*
 * @(#)file      RequiredModelMBean.java
 * @(#)author    Sun Microsystems, Inc.
 * @(#)version   1.63
 * @(#)lastedit      07/03/30
 *
 * Copyright IBM Corp. 1999-2000.  All rights reserved.
 *
 * The program is provided "as is" without any warranty express or implied,
 * including the warranty of non-infringement and the implied warranties of
 * merchantibility and fitness for a particular purpose. IBM will not be
 * liable for any damages suffered by you or any third party claim against
 * you regarding the Program.
 *
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * This software is the proprietary information of Sun Microsystems, Inc.
 * Use is subject to license terms.
 *
 * Copyright 2006 Sun Microsystems, Inc.  Tous droits reserves.
 * Ce logiciel est propriete de Sun Microsystems, Inc.
 * Distribue par des licences qui en restreignent l'utilisation.
 *
 */




package javax.management.modelmbean;

/* java imports */

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import java.io.PrintStream;
import java.io.FileOutputStream;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeChangeNotification;
import javax.management.AttributeChangeNotificationFilter;
import javax.management.AttributeNotFoundException;
import javax.management.Descriptor;
import javax.management.DescriptorAccess;
import javax.management.InstanceNotFoundException;
import javax.management.InvalidAttributeValueException;
import javax.management.ListenerNotFoundException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanRegistration;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.RuntimeErrorException;
import javax.management.RuntimeMBeanException;
import javax.management.RuntimeOperationsException;
import javax.management.ServiceNotFoundException;
import javax.management.NotificationEmitter;
import javax.management.loading.ClassLoaderRepository;

import com.sun.jmx.trace.Trace;
import sun.reflect.misc.MethodUtil;
import sun.reflect.misc.ReflectUtil;


/**
 * This class is the implementation of a ModelMBean. An appropriate
 * implementation of a ModelMBean must be shipped with every JMX Agent
 * and the class must be named RequiredModelMBean.
 * <P>
 * Java resources wishing to be manageable instantiate the
 * RequiredModelMBean using the MBeanServer's createMBean method.
 * The resource then sets the MBeanInfo and Descriptors for the
 * RequiredModelMBean instance. The attributes and operations exposed
 * via the ModelMBeanInfo for the ModelMBean are accessible
 * from MBeans, connectors/adaptors like other MBeans. Through the
 * Descriptors, values and methods in the managed application can be
 * defined and mapped to attributes and operations of the ModelMBean.
 * This mapping can be defined in an XML formatted file or dynamically and
 * programmatically at runtime.
 * <P>
 * Every RequiredModelMBean which is instantiated in the MBeanServer
 * becomes manageable:<br>
 * its attributes and operations become remotely accessible through the
 * connectors/adaptors connected to that MBeanServer.
 * <P>
 * A Java object cannot be registered in the MBeanServer unless it is a
 * JMX compliant MBean. By instantiating a RequiredModelMBean, resources
 * are guaranteed that the MBean is valid.
 *
 * MBeanException and RuntimeOperationsException must be thrown on every
 * public method.  This allows for wrapping exceptions from distributed
 * communications (RMI, EJB, etc.)
 *
 * @since 1.5
 */

public class RequiredModelMBean implements ModelMBean, MBeanRegistration, NotificationEmitter {

    /*************************************/
    /* attributes                        */
    /*************************************/
    ModelMBeanInfo modelMBeanInfo;

    /* Notification broadcaster for any notification to be sent
     * from the application through the RequiredModelMBean.  */
    private NotificationBroadcasterSupport generalBroadcaster = null;

    /* Notification broadcaster for attribute change notifications */
    private NotificationBroadcasterSupport attributeBroadcaster = null;

    /* handle, name, or reference for instance on which the actual invoke
     * and operations will be executed */
    private Object managedResource = null;

    private static final String currClass = "RequiredModelMBean";

    /* records the registering in MBeanServer */
    private boolean registered = false;
    private transient MBeanServer server = null;

    /*************************************/
    /* constructors                      */
    /*************************************/

    /**
     * Constructs an <CODE>RequiredModelMBean</CODE> with an empty
     * ModelMBeanInfo.
     * <P>
     * The RequiredModelMBean's MBeanInfo and Descriptors
     * can be customized using the {@link #setModelMBeanInfo} method.
     * After the RequiredModelMBean's MBeanInfo and Descriptors are
     * customized, the RequiredModelMBean can be registered with
     * the MBeanServer.
     *
     * @exception MBeanException Wraps a distributed communication Exception.
     *
     * @exception RuntimeOperationsException Wraps a {@link
     * RuntimeException} during the construction of the object.
     **/
    public RequiredModelMBean()
	throws MBeanException, RuntimeOperationsException {

	if (tracing())
	    trace("RequiredModelMBean()","Entry and Exit");

	modelMBeanInfo = createDefaultModelMBeanInfo();
    }

    /**
     * Constructs a RequiredModelMBean object using ModelMBeanInfo passed in.
     * As long as the RequiredModelMBean is not registered
     * with the MBeanServer yet, the RequiredModelMBean's MBeanInfo and
     * Descriptors can be customized using the {@link #setModelMBeanInfo}
     * method.
     * After the RequiredModelMBean's MBeanInfo and Descriptors are
     * customized, the RequiredModelMBean can be registered with the
     * MBeanServer.
     *
     * @param mbi The ModelMBeanInfo object to be used by the
     *            RequiredModelMBean. The given ModelMBeanInfo is cloned
     *            and modified as specified by {@link #setModelMBeanInfo}
     *
     * @exception MBeanException Wraps a distributed communication Exception.
     * @exception RuntimeOperationsException Wraps an
     *    {link java.lang.IllegalArgumentException}:
     *	        The MBeanInfo passed in parameter is null.
     *
     **/
    public RequiredModelMBean(ModelMBeanInfo mbi)
	throws MBeanException, RuntimeOperationsException {

	if (tracing())
	    trace("RequiredModelMBean(MBeanInfo)","Entry");

	setModelMBeanInfo(mbi);

	if (tracing())
	    trace("RequiredModelMBean(MBeanInfo)","Exit");
    }


    /*************************************/
    /* initializers                      */
    /*************************************/

    /**
     * Initializes a ModelMBean object using ModelMBeanInfo passed in.
     * This method makes it possible to set a customized ModelMBeanInfo on
     * the ModelMBean as long as it is not registered with the MBeanServer.
     * <br>
     * Once the ModelMBean's ModelMBeanInfo (with Descriptors) are
     * customized and set on the ModelMBean, the  ModelMBean be
     * registered with the MBeanServer.
     * <P>
     * If the ModelMBean is currently registered, this method throws
     * a {@link javax.management.RuntimeOperationsException} wrapping an
     * {@link IllegalStateException}
     * <P>
     * If the given <var>inModelMBeanInfo</var> does not contain any
     * {@link ModelMBeanNotificationInfo} for the <code>GENERIC</code>
     * or <code>ATTRIBUTE_CHANGE</code> notifications, then the
     * RequiredModelMBean will supply its own default
     * {@link ModelMBeanNotificationInfo ModelMBeanNotificationInfo}s for
     * those missing notifications.
     *
     * @param mbi The ModelMBeanInfo object to be used
     *        by the ModelMBean.
     *	
     * @exception MBeanException Wraps a distributed communication
     *        Exception.
     * @exception RuntimeOperationsException
     * <ul><li>Wraps an {@link IllegalArgumentException} if
     *         the MBeanInfo passed in parameter is null.</li>
     *     <li>Wraps an {@link IllegalStateException} if the ModelMBean
     *         is currently registered in the MBeanServer.</li>
     * </ul>
     *
     **/
    public void setModelMBeanInfo(ModelMBeanInfo mbi)
	throws MBeanException, RuntimeOperationsException {
	
	if (tracing())
	    trace("setModelMBeanInfo(ModelMBeanInfo)","Entry");
	
	if (mbi == null) {
	    if (tracing())	
		trace("setModelMBeanInfo(ModelMBeanInfo)",
		      "ModelMBeanInfo is null: Raising exception.");
	    final RuntimeException x = new
		IllegalArgumentException("ModelMBeanInfo must not be null");
	    final String exceptionText =
		"Exception occurred trying to initialize the " +
		"ModelMBeanInfo of the RequiredModelMBean";
	    throw new RuntimeOperationsException(x,exceptionText);
	}

	if (registered) {
	    if (tracing())	
		trace("setModelMBeanInfo(ModelMBeanInfo)",
		      "RequiredMBean is registered: Raising exception.");
	    final String exceptionText =
		"Exception occurred trying to set the " +
		"ModelMBeanInfo of the RequiredModelMBean";
	    final RuntimeException x = new IllegalStateException(
	     "cannot call setModelMBeanInfo while ModelMBean is registered");
	    throw new RuntimeOperationsException(x,exceptionText);
	}

	if (tracing()) {
	    trace("setModelMBeanInfo(ModelMBeanInfo)",
		  "Setting ModelMBeanInfo to " + printModelMBeanInfo(mbi));
	    trace("setModelMBeanInfo(ModelMBeanInfo)",
		  "ModelMBeanInfo notifications has " +
		  (mbi.getNotifications()).length + " elements");
	}

	modelMBeanInfo = (ModelMBeanInfo)mbi.clone();
	
	if (tracing())
	    trace("setModelMBeanInfo(ModelMBeanInfo)","set mbeanInfo to: "+
		  printModelMBeanInfo(modelMBeanInfo));
	
	if (tracing())
	    trace("setModelMBeanInfo(ModelMBeanInfo)","Exit");
    }


    /**
     * Sets the instance handle of the object against which to
     * execute all methods in this ModelMBean management interface
     * (MBeanInfo and Descriptors).
     *
     * @param mr Object that is the managed resource
     * @param mr_type The type of reference for the managed resource.
     *     <br>Can be: "ObjectReference", "Handle", "IOR", "EJBHandle",
     *         or "RMIReference".
     *     <br>In this implementation only "ObjectReference" is supported.
     *
     * @exception MBeanException The initializer of the object has
     *            thrown an exception.
     * @exception InstanceNotFoundException The managed resource
     *            object could not be found
     * @exception InvalidTargetObjectTypeException The managed
     *            resource type should be "ObjectReference".
     * @exception RuntimeOperationsException Wraps a {@link
     *            RuntimeException} when setting the resource.
     **/
    public void setManagedResource(Object mr, String mr_type)
	throws MBeanException, RuntimeOperationsException,
	       InstanceNotFoundException, InvalidTargetObjectTypeException {
	if (tracing())
	    trace("setManagedResource(Object,String)","Entry");

	// check that the mr_type is supported by this JMXAgent
	// only "objectReference" is supported
	if ((mr_type == null) ||
	    (! mr_type.equalsIgnoreCase("objectReference"))) {
	    if (tracing())
		trace("setManagedResource(Object,String)",
		      "Managed Resouce Type is not supported: " + mr_type);
	
	    throw new InvalidTargetObjectTypeException(mr_type);
	}

	if (tracing())
	    trace("setManagedResource(Object,String)",
		  "Managed Resouce is valid");

	managedResource = mr;
		
	if (tracing())
	    trace("setManagedResource(Object, String)", "Exit");
    }

    /**
     * <p>Instantiates this MBean instance with the data found for
     * the MBean in the persistent store.  The data loaded could include
     * attribute and operation values.</p>
     *
     * <p>This method should be called during construction or
     * initialization of this instance, and before the MBean is
     * registered with the MBeanServer.</p>
     *
     * <p>If the implementation of this class does not support
     * persistence, an {@link MBeanException} wrapping a {@link
     * ServiceNotFoundException} is thrown.</p>
     *
     * @exception MBeanException Wraps another exception, or
     * persistence is not supported
     * @exception RuntimeOperationsException Wraps exceptions from the
     * persistence mechanism
     * @exception InstanceNotFoundException Could not find or load
     * this MBean from persistent storage
     */
    public void load()
	throws MBeanException, RuntimeOperationsException,
	       InstanceNotFoundException {
	final ServiceNotFoundException x = new ServiceNotFoundException(
			        "Persistence not supported for this MBean");
	throw new MBeanException(x, x.getMessage());
    }

        /**
     * <p>Captures the current state of this MBean instance and writes
     * it out to the persistent store.  The state stored could include
     * attribute and operation values.</p>
     *
     * <p>If the implementation of this class does not support
     * persistence, an {@link MBeanException} wrapping a {@link
     * ServiceNotFoundException} is thrown.</p>
     *
     * <p>Persistence policy from the MBean and attribute descriptor
     * is used to guide execution of this method. The MBean should be
     * stored if 'persistPolicy' field is:</p>
     *
     * <PRE>  != "never"
     *   = "always"
     *   = "onTimer" and now > 'lastPersistTime' + 'persistPeriod'
     *   = "NoMoreOftenThan" and now > 'lastPersistTime' + 'persistPeriod'
     *   = "onUnregister"
     * </PRE>
     *
     * <p>Do not store the MBean if 'persistPolicy' field is:</p>
     * <PRE>
     *    = "never"
     *    = "onUpdate"
     *    = "onTimer" && now < 'lastPersistTime' + 'persistPeriod'
     * </PRE>
     *
     * @exception MBeanException Wraps another exception, or
     * persistence is not supported
     * @exception RuntimeOperationsException Wraps exceptions from the
     * persistence mechanism
     * @exception InstanceNotFoundException Could not find/access the
     * persistent store
     */
    public void store()
	throws MBeanException, RuntimeOperationsException,
	       InstanceNotFoundException {
	final ServiceNotFoundException x = new ServiceNotFoundException(
			        "Persistence not supported for this MBean");
	throw new MBeanException(x, x.getMessage());
    }

    /*************************************/
    /* DynamicMBean Interface            */
    /*************************************/

    /**
     * The resolveForCacheValue method checks the descriptor passed in to
     * see if there is a valid cached value in the descriptor.
     * The valid value will be in the 'value' field if there is one.
     * If the 'currencyTimeLimit' field in the descriptor is:
     * <ul>
     *   <li><b>&lt;0</b> Then the value is not cached and is never valid.
     *         Null is returned. The 'value' and 'lastUpdatedTimeStamp'
     *         fields are cleared.</li>
     *   <li><b>=0</b> Then the value is always cached and always valid.
     *         The 'value' field is returned.
     *         The 'lastUpdatedTimeStamp' field is not checked.</li>
     *   <li><b>&gt;0</b> Represents the number of seconds that the
     *         'value' field is valid.
     *         The 'value' field is no longer valid when
     *         'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.</li>
     * </ul>
     * <li>When 'value' is valid, 'valid' is returned.</li>
     * <li>When 'value' is no longer valid then null is returned and
     *     'value' and 'lastUpdatedTimeStamp' fields are cleared.</li>
     *
     **/
    private Object resolveForCacheValue(Descriptor descr)
	throws MBeanException, RuntimeOperationsException {
	if (tracing())
	    trace("resolveForCacheValue(Descriptor)","Entry");

	Object response = null;
	boolean resetValue = false, returnCachedValue = true;
	long currencyPeriod = 0;

	if (descr == null) {
	    if (tracing())
		trace("resolveForCacheValue(Descriptor)",
		      "Input Descriptor is null");
	    return response;
	}

	if (tracing())
	    trace("resolveForCacheValue(Descriptor)","descriptor is " +
		  descr.toString());

	final Descriptor mmbDescr = modelMBeanInfo.getMBeanDescriptor();
	if (mmbDescr == null) {
	    if (tracing())
		trace("resolveForCacheValue(Descriptor)",
		      "MBean Descriptor is null");
	    //return response;
	}

	Object objExpTime = descr.getFieldValue("currencyTimeLimit");

	String expTime;
	if (objExpTime != null) {	
	    expTime = objExpTime.toString();
	} else {
	    expTime = null;
	}

	if ((expTime == null) && (mmbDescr != null)) {
	    objExpTime = mmbDescr.getFieldValue("currencyTimeLimit");
	    if (objExpTime != null) {		
		expTime = objExpTime.toString();
	    } else {
		expTime = null;
	    }	
	}

	if (expTime != null) {
	    if (tracing())
		trace("resolveForCacheValue(Descriptor)",
		      "currencyTimeLimit: " + expTime);

	    // convert seconds to milliseconds for time comparison
	    currencyPeriod = ((new Long(expTime)).longValue()) * 1000;	
	    if (currencyPeriod < 0) {
		/* if currencyTimeLimit is -1 then value is never cached */
		returnCachedValue = false;
		resetValue = true;
		if (tracing())
		    trace("resolveForCacheValue(Descriptor)",
			  currencyPeriod + ": never Cached");
	    } else if (currencyPeriod == 0) {
		/* if currencyTimeLimit is 0 then value is always cached */
		returnCachedValue = true;
		resetValue = false;
		if (tracing())
		    trace("resolveForCacheValue(Descriptor)",
			  "always valid Cache");
	    } else {
		Object objtStamp =
		    descr.getFieldValue("lastUpdatedTimeStamp");

		String tStamp;
		if (objtStamp != null) tStamp = objtStamp.toString();
		else tStamp = null;
		
		if (tracing())
		    trace("resolveForCacheValue(Descriptor)",
			  "lastUpdatedTimeStamp: " + tStamp);

		if (tStamp == null)
		    tStamp = "0";
	
		long lastTime = (new Long(tStamp)).longValue();

		if (tracing())
		    trace("resolveForCacheValue(Descriptor)",
			  " currencyPeriod:" + currencyPeriod +
			  " lastUpdatedTimeStamp:" + lastTime);

		long now = (new Date()).getTime();

		if (now < (lastTime + currencyPeriod)) {
		    returnCachedValue = true;
		    resetValue = false;
		    if (tracing())
			trace("resolveForCacheValue(Descriptor)",
			      " timed valid Cache for " + now + " < " +
			      (lastTime + currencyPeriod));
		} else { /* value is expired */
		    returnCachedValue = false;
		    resetValue = true;
		    if (tracing())
			trace("resolveForCacheValue(Descriptor)",
			      "timed expired cache for " + now + " > " +
			      (lastTime + currencyPeriod));
		}
	    }

	    if (tracing())
		trace("resolveForCacheValue(Descriptor)",
		      "returnCachedValue:" + returnCachedValue +
		      " resetValue: " + resetValue);

	    if (returnCachedValue == true) {
		Object currValue = descr.getFieldValue("value");
		if (currValue != null) {
		    /* error/validity check return value here */
		    response = currValue;
		    /* need to cast string cached value to type */
		    if (tracing())
			trace("resolveForCacheValue(Descriptor)",
			      "valid Cache value: " + currValue);
					
		} else {
		    response = null;
		    if (tracing())
			trace("resolveForCacheValue(Descriptor)",
			      "no Cached value");
		}
	    }

	    if (resetValue == true) {
		/* value is not current, so remove it */
		descr.removeField("lastUpdatedTimeStamp");
		descr.removeField("value");
		response = null;
		modelMBeanInfo.setDescriptor(descr,null);
		if (tracing())
		    trace("resolveForCacheValue(Descriptor)",
			  "reset cached value to null");
	    }
	}

	if (tracing())
	    trace("resolveForCache(Descriptor)","Exit");

	return response;
    }

    /**
     * Returns the attributes, operations, constructors and notifications
     * that this RequiredModelMBean exposes for management.
     *
     * @return  An instance of ModelMBeanInfo allowing retrieval all
     *          attributes, operations, and Notifications of this MBean.
     *
     **/
    public MBeanInfo getMBeanInfo() {
	
	if (tracing())
	    trace("getMBeanInfo()","Entry and Exit");

	if (modelMBeanInfo == null) {
	    if (tracing())
		trace("getMBeanInfo()","modelMBeanInfo is null");
	    modelMBeanInfo = createDefaultModelMBeanInfo();
	    //return new ModelMBeanInfo(" ", "", null, null, null, null);
	}

	if (tracing()) {
	    trace("getMBeanInfo()","ModelMBeanInfo is " +
		  modelMBeanInfo.getClassName() + " for " +
		  modelMBeanInfo.getDescription());
	    trace("getMBeanInfo()",printModelMBeanInfo(modelMBeanInfo));
	}

	return((MBeanInfo) ((ModelMBeanInfo)modelMBeanInfo).clone());
    }

    private String printModelMBeanInfo(ModelMBeanInfo info) {
	final StringBuffer retStr = new StringBuffer();
	if (info == null) {
	    if (tracing())
		trace("printModelMBeanInfo(ModelMBeanInfo)",
		      "ModelMBeanInfo to print is null, " +
		      "printing local ModelMBeanInfo");
	    info = modelMBeanInfo;
	}

	retStr.append("\nMBeanInfo for ModelMBean is:");
	retStr.append("\nCLASSNAME: \t"+ info.getClassName());
	retStr.append("\nDESCRIPTION: \t"+ info.getDescription());


	try {
	    retStr.append("\nMBEAN DESCRIPTOR: \t"+
			  info.getMBeanDescriptor());
	} catch (Exception e) {
	    retStr.append("\nMBEAN DESCRIPTOR: \t" + " is invalid");
	}

	retStr.append("\nATTRIBUTES");

	final MBeanAttributeInfo[] attrInfo = info.getAttributes();
	if ((attrInfo != null) && (attrInfo.length>0)) {
	    for (int i=0; i<attrInfo.length; i++) {
		final ModelMBeanAttributeInfo attInfo =
		    (ModelMBeanAttributeInfo)attrInfo[i];
		retStr.append(" ** NAME: \t"+ attInfo.getName());
		retStr.append("    DESCR: \t"+ attInfo.getDescription());
		retStr.append("    TYPE: \t"+ attInfo.getType() +
			      "    READ: \t"+ attInfo.isReadable() +
			      "    WRITE: \t"+ attInfo.isWritable());
		retStr.append("    DESCRIPTOR: " +
			      attInfo.getDescriptor().toString());
	    }
	} else {
	    retStr.append(" ** No attributes **");
	}

	retStr.append("\nCONSTRUCTORS");
	final MBeanConstructorInfo[] constrInfo = info.getConstructors();
	if ((constrInfo != null) && (constrInfo.length > 0 )) {
	    for (int i=0; i<constrInfo.length; i++) {
		final ModelMBeanConstructorInfo ctorInfo =
		    (ModelMBeanConstructorInfo)constrInfo[i];
		retStr.append(" ** NAME: \t"+ ctorInfo.getName());
		retStr.append("    DESCR: \t"+
			      ctorInfo.getDescription());
		retStr.append("    PARAM: \t"+
			      ctorInfo.getSignature().length +
			      " parameter(s)");
		retStr.append("    DESCRIPTOR: " +
			      ctorInfo.getDescriptor().toString());
	    }
	} else {
	    retStr.append(" ** No Constructors **");
	}
		
	retStr.append("\nOPERATIONS");
	final MBeanOperationInfo[] opsInfo = info.getOperations();
	if ((opsInfo != null) && (opsInfo.length>0)) {
	    for (int i=0; i<opsInfo.length; i++) {
		final ModelMBeanOperationInfo operInfo =
		    (ModelMBeanOperationInfo)opsInfo[i];
		retStr.append(" ** NAME: \t"+ operInfo.getName());
		retStr.append("    DESCR: \t"+ operInfo.getDescription());
		retStr.append("    PARAM: \t"+
			      operInfo.getSignature().length +
			      " parameter(s)");
		retStr.append("    DESCRIPTOR: " +
			      operInfo.getDescriptor().toString());
	    }
	} else {
	    retStr.append(" ** No operations ** ");
	}

	retStr.append("\nNOTIFICATIONS");

	MBeanNotificationInfo[] notifInfo = info.getNotifications();
	if ((notifInfo != null) && (notifInfo.length>0)) {
	    for (int i=0; i<notifInfo.length; i++) {
		final ModelMBeanNotificationInfo nInfo =
		    (ModelMBeanNotificationInfo)notifInfo[i];
		retStr.append(" ** NAME: \t"+ nInfo.getName());
		retStr.append("    DESCR: \t"+ nInfo.getDescription());
		retStr.append("    DESCRIPTOR: " +
			      nInfo.getDescriptor().toString());
	    }
	} else {
	    retStr.append(" ** No notifications **");
	}

	retStr.append(" ** ModelMBean: End of MBeanInfo ** ");

	return retStr.toString();
    }

    private void echo(String txt) {
	trace("echo(txt)",txt);
    }


    /**
     * Invokes a method on or through a RequiredModelMBean and returns
     * the result of the method execution.
     * <P>
     * If the given method to be invoked, together with the provided
     * signature, matches one of RequiredModelMbean
     * accessible methods, this one will be call. Otherwise the call to
     * the given method will be tried on the managed resource.
     * <P>
     * The last value returned by an operation may be cached in
     * the operation's descriptor which
     * is in the ModelMBeanOperationInfo's descriptor.
     * The valid value will be in the 'value' field if there is one.
     * If the 'currencyTimeLimit' field in the descriptor is:
     * <UL>
     * <LI><b>&lt;0</b> Then the value is not cached and is never valid.
     *      The operation method is invoked.
     *      The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI>
     * <LI><b>=0</b> Then the value is always cached and always valid.
     *      The 'value' field is returned. If there is no 'value' field
     *      then the operation method is invoked for the attribute.
     *      The 'lastUpdatedTimeStamp' field and `value' fields are set to
     *      the operation's return value and the current time stamp.</LI>
     * <LI><b>&gt;0</b> Represents the number of seconds that the 'value'
     *      field is valid.
     *      The 'value' field is no longer valid when
     *      'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.
     *      <UL>
     *         <LI>When 'value' is valid, 'value' is returned.</LI>
     *         <LI>When 'value' is no longer valid then the operation
     *             method is invoked. The 'lastUpdatedTimeStamp' field
     *             and `value' fields are updated.</lI>
     *      </UL>
     * </LI>
     * </UL>
     *
     * <p><b>Note:</b> because of inconsistencies in previous versions of
     * this specification, it is recommended not to use negative or zero
     * values for <code>currencyTimeLimit</code>.  To indicate that a
     * cached value is never valid, omit the
     * <code>currencyTimeLimit</code> field.  To indicate that it is
     * always valid, use a very large number for this field.</p>
     *
     * @param opName The name of the method to be invoked. The
     *     name can be the fully qualified method name including the
     *     classname, or just the method name if the classname is
     *     defined in the 'class' field of the operation descriptor.
     * @param opArgs An array containing the parameters to be set
     *     when the operation is invoked
     * @param sig An array containing the signature of the
     *     operation. The class objects will be loaded using the same
     *     class loader as the one used for loading the MBean on which
     *     the operation was invoked.
     *
     * @return  The object returned by the method, which represents the
     *     result of invoking the method on the specified managed resource.
     *
     * @exception MBeanException  Wraps one of the following Exceptions:
     * <UL>
     * <LI> An Exception thrown by the managed object's invoked method.</LI>
     * <LI> {@link ServiceNotFoundException}: No ModelMBeanOperationInfo or
     *      no descriptor defined for the specified operation or the managed
     *      resource is null.</LI>
     * <LI> {@link InvalidTargetObjectTypeException}: The 'targetType'
     *      field value is not 'objectReference'.</LI>
     * </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *      thrown while trying to invoke the method.
     * @exception RuntimeOperationsException Wraps an
     *      {@link IllegalArgumentException} Method name is null.
     *
     **/
    /*
      The requirement to be able to invoke methods on the
      RequiredModelMBean class itself makes this method considerably
      more complicated than it might otherwise be.  Note that, unlike
      earlier versions, we do not allow you to invoke such methods if
      they are not explicitly mentioned in the ModelMBeanInfo.  Doing
      so was potentially a security problem, and certainly very
      surprising.

      We do not look for the method in the RequiredModelMBean class
      itself if:
      (a) there is a "targetObject" field in the Descriptor for the
      operation; or
      (b) there is a "class" field in the Descriptor for the operation
      and the named class is not RequiredModelMBean or one of its
      superinterfaces; or
      (c) the name of the operation is not the name of a method in
      RequiredModelMBean (this is just an optimization).

      In cases (a) and (b), if you have gone to the trouble of adding
      those fields specifically for this operation then presumably you
      do not want RequiredModelMBean's methods to be called.

      We have to pay attention to class loading issues.  If the
      "class" field is present, the named class has to be resolved
      relative to RequiredModelMBean's class loader to test the
      condition (b) above, and relative to the managed resource's
      class loader to ensure that the managed resource is in fact of
      the named class (or a subclass).  The class names in the sig
      array likewise have to be resolved, first against
      RequiredModelMBean's class loader, then against the managed
      resource's class loader.  There is no point in using any other
      loader because when we call Method.invoke we must call it on
      a Method that is implemented by the target object.
     */
    public Object invoke(String opName, Object[] opArgs, String[] sig)
	    throws MBeanException, ReflectionException {
	final boolean tracing = tracing();

	if (tracing)
	    trace("invoke(String, Object[], String[])","Entry");

	if (opName == null) {
	    final RuntimeException x =
		new IllegalArgumentException("Method name must not be null");
	    throw new RuntimeOperationsException(x,
                      "An exception occurred while trying to " +
		      "invoke a method on a RequiredModelMBean");
	}

	String opClassName = null;
	String opMethodName;

	// Parse for class name and method
	int opSplitter = opName.lastIndexOf(".");
	if (opSplitter > 0) {
	    opClassName = opName.substring(0,opSplitter);
	    opMethodName = opName.substring(opSplitter+1);
	} else
	    opMethodName = opName;

	/* Ignore anything after a left paren.  We keep this for
	   compatibility but it isn't specified.  */
	opSplitter = opMethodName.indexOf("(");
	if (opSplitter > 0)
	    opMethodName = opMethodName.substring(0,opSplitter);
	
	if (tracing)
	    trace("invoke(String, Object[], String[])",
		  "Finding operation " + opName + " as " + opMethodName);

	ModelMBeanOperationInfo opInfo =
	    modelMBeanInfo.getOperation(opMethodName);
	if (opInfo == null) {
	    final String msg =
		"Operation " + opName + " not in ModelMBeanInfo";
	    throw new MBeanException(new ServiceNotFoundException(msg), msg);
	}

	final Descriptor opDescr = opInfo.getDescriptor();
	if (opDescr == null) {	
	    final String msg = "Operation descriptor null";
	    throw new MBeanException(new ServiceNotFoundException(msg), msg);
	}

	final Object cached = resolveForCacheValue(opDescr);
	if (cached != null) {
	    if (tracing)
		trace("invoke(String, Object[], String[])",
		      "Returning cached value");
	    return cached;
	}

        if (opClassName == null)
	    opClassName = (String) opDescr.getFieldValue("class");
	// may still be null now

	opMethodName = (String) opDescr.getFieldValue("name");
	if (opMethodName == null) {
	    final String msg =
		"Method descriptor must include `name' field";
	    throw new MBeanException(new ServiceNotFoundException(msg), msg);
	}

	final String targetTypeField = (String)
	    opDescr.getFieldValue("targetType");
	if (targetTypeField != null
	    && !targetTypeField.equalsIgnoreCase("objectReference")) {
	    final String msg =
		"Target type must be objectReference: " + targetTypeField;
	    throw new MBeanException(new InvalidTargetObjectTypeException(msg),
				     msg);
	}

	final Object targetObjectField = opDescr.getFieldValue("targetObject");
	if (tracing && targetObjectField != null)
	    trace("invoke(String, Object[], String[])",
		  "Found target object in descriptor");

	/* Now look for the method, either in RequiredModelMBean itself
	   or in the target object.  Set "method" and "targetObject"
	   appropriately.  */
	Method method;
	Object targetObject;

	method = findRMMBMethod(opMethodName, targetObjectField,
				opClassName, sig);

	if (method != null)
	    targetObject = this;
	else {
	    if (tracing)
		trace("invoke(String, Object[], String[])",
		      "looking for method in managedResource class");
	    if (targetObjectField != null)
		targetObject = targetObjectField;
	    else {
		targetObject = managedResource;
		if (targetObject == null) {
		    final String msg =
			"managedResource for invoke " + opName +
			" is null";
		    Exception snfe = new ServiceNotFoundException(msg);
		    throw new MBeanException(snfe);
		}
	    }

	    final Class targetClass;

	    if (opClassName != null) {
		try {
		    final ClassLoader targetClassLoader =
			targetObject.getClass().getClassLoader();
		    targetClass = Class.forName(opClassName, false,
						targetClassLoader);
		} catch (ClassNotFoundException e) {
		    final String msg =
			"class for invoke " + opName + " not found";
		    throw new ReflectionException(e, msg);
		}
	    } else
		targetClass = targetObject.getClass();

	    method = resolveMethod(targetClass, opMethodName, sig);
	}

	if (tracing)
	    trace("invoke(String, Object[], String[])",
		  "found " + opMethodName + ", now invoking");

	final Object result =
	    invokeMethod(opName, method, targetObject, opArgs);

	if (tracing)
	    trace("invoke(String, Object[], String[])",
		  "successfully invoked method");

	if (result != null)
	    cacheResult(opInfo, opDescr, result);

	return result;
    }

    private static Method resolveMethod(Class targetClass,
					String opMethodName,
					String[] sig)
	    throws ReflectionException {
	final boolean tracing = tracing();

	if (tracing)
	    trace("resolveMethod",
		  "resolving " + targetClass + "." + opMethodName);

	final Class[] argClasses;

	if (sig == null)
	    argClasses = null;
	else {
	    final ClassLoader targetClassLoader = targetClass.getClassLoader();
	    argClasses = new Class[sig.length];
	    for (int i = 0; i < sig.length; i++) {
		if (tracing)
		    trace("resolveMethod", "resolve type " + sig[i]);
		argClasses[i] = (Class) primitiveClassMap.get(sig[i]);
		if (argClasses[i] == null) {
		    try {
			argClasses[i] =
			    Class.forName(sig[i], false, targetClassLoader);
		    } catch (ClassNotFoundException e) {
			if (tracing)
			    trace("resolveMethod", "class not found");
			final String msg = "Parameter class not found";
			throw new ReflectionException(e, msg);
		    }
		}
	    }
	}

	try {
	    return targetClass.getMethod(opMethodName, argClasses);
	} catch (NoSuchMethodException e) {
	    final String msg =
		"Target method not found: " + targetClass.getName() + "." +
		opMethodName;
	    throw new ReflectionException(e, msg);
	}
    }

    /* Map e.g. "int" to int.class.  Goodness knows how many time this
       particular wheel has been reinvented.  */
    private static final Class[] primitiveClasses = {
	int.class, long.class, boolean.class, double.class,
	float.class, short.class, byte.class, char.class,
    };
    private static final Map<String,Class<?>> primitiveClassMap =
	new HashMap<String,Class<?>>();
    static {
	for (int i = 0; i < primitiveClasses.length; i++) {
	    final Class c = primitiveClasses[i];
	    primitiveClassMap.put(c.getName(), c);
	}
    }

    /* Find a method in RequiredModelMBean as determined by the given
       parameters.  Return null if there is none, or if the parameters
       exclude using it.  Called from invoke. */
    private static Method findRMMBMethod(String opMethodName,
					 Object targetObjectField,
					 String opClassName,
					 String[] sig) {
	if (tracing())
	    trace("invoke(String, Object[], String[])",
		  "looking for method in RequiredModelMBean class");
	if (!isRMMBMethodName(opMethodName))
	    return null;
	if (targetObjectField != null)
	    return null;
	final Class<RequiredModelMBean> rmmbClass = RequiredModelMBean.class;
	final Class<?> targetClass;
	if (opClassName == null)
	    targetClass = rmmbClass;
	else {
	    try {
		final ClassLoader targetClassLoader =
		    rmmbClass.getClassLoader();
		targetClass = Class.forName(opClassName, false,
					    targetClassLoader);
		if (!rmmbClass.isAssignableFrom(targetClass))
		    return null;
	    } catch (ClassNotFoundException e) {
		return null;
	    }
	}
	try {
	    return resolveMethod(targetClass, opMethodName, sig);
	} catch (ReflectionException e) {
	    return null;
	}
    }

    /*
     * Invoke the given method, and throw the somewhat unpredictable
     * appropriate exception if the method itself gets an exception.
     */
    private Object invokeMethod(String opName, Method method,
				Object targetObject, Object[] opArgs)
	    throws MBeanException, ReflectionException {
	try {
	    ReflectUtil.checkPackageAccess(method.getDeclaringClass());
	    return MethodUtil.invoke(method, targetObject, opArgs);
	} catch (RuntimeErrorException ree) {
	    throw new RuntimeOperationsException(ree,
		      "RuntimeException occurred in RequiredModelMBean "+
		      "while trying to invoke operation " + opName);
	} catch (RuntimeException re) {
	    throw new RuntimeOperationsException(re,
		      "RuntimeException occurred in RequiredModelMBean "+
		      "while trying to invoke operation " + opName);
	} catch (IllegalAccessException iae) {
	    throw new ReflectionException(iae,
		      "IllegalAccessException occurred in " +
		      "RequiredModelMBean while trying to " +
		      "invoke operation " + opName);
	} catch (InvocationTargetException ite) {
	    Throwable mmbTargEx = ite.getTargetException();
	    if (mmbTargEx instanceof RuntimeException) {
		throw new MBeanException ((RuntimeException)mmbTargEx,
		      "RuntimeException thrown in RequiredModelMBean "+
		      "while trying to invoke operation " + opName);
	    } else if (mmbTargEx instanceof Error) {
		throw new RuntimeErrorException((Error)mmbTargEx,
		      "Error occurred in RequiredModelMBean while trying "+
		      "to invoke operation " + opName);
	    } else if (mmbTargEx instanceof ReflectionException) {
		throw (ReflectionException) mmbTargEx;
	    } else {
		throw new MBeanException ((Exception)mmbTargEx,
		      "Exception thrown in RequiredModelMBean "+
		      "while trying to invoke operation " + opName);
	    }
	} catch (Error err) {
	    throw new RuntimeErrorException(err,
		  "Error occurred in RequiredModelMBean while trying "+
		  "to invoke operation " + opName);
	} catch (Exception e) {
	    throw new ReflectionException(e,
		  "Exception occurred in RequiredModelMBean while " +
		  "trying to invoke operation " + opName);
	}
    }

    /*
     * Cache the result of an operation in the descriptor, if that is
     * called for by the descriptor's configuration.  Note that we
     * don't remember operation parameters when caching the result, so
     * this is unlikely to be useful if there are any.
     */
    private void cacheResult(ModelMBeanOperationInfo opInfo,
			     Descriptor opDescr, Object result)
	    throws MBeanException {

	Descriptor mmbDesc =
	    modelMBeanInfo.getMBeanDescriptor();

	Object objctl =
	    opDescr.getFieldValue("currencyTimeLimit");
	String ctl;
	if (objctl != null) {		
	    ctl = objctl.toString();
	} else {
	    ctl = null;
	}					
	if ((ctl == null) && (mmbDesc != null)) {
	    objctl =
		mmbDesc.getFieldValue("currencyTimeLimit");
	    if (objctl != null) {		
		ctl = objctl.toString();
	    } else {
		ctl = null;
	    }
	}
	if ((ctl != null) && !(ctl.equals("-1"))) {
	    opDescr.setField("value", result);
	    opDescr.setField("lastUpdatedTimeStamp",
	      (new Long((new Date()).getTime())).toString());

	    modelMBeanInfo.setDescriptor(opDescr,
					 "operation");
	    if (tracing()) {
		trace("invoke(String,Object[],Object[])",
		      "new descriptor is " +
		      opDescr.toString());
	    }
	}
    }

    /*
     * Determine whether the given name is the name of a public method
     * in this class.  This is only an optimization: it prevents us
     * from trying to do argument type lookups and reflection on a
     * method that will obviously fail because it has the wrong name.
     *
     * The first time this method is called we do the reflection, and
     * every other time we reuse the remembered values.
     *
     * It's conceivable that the (possibly malicious) first caller
     * doesn't have the required permissions to do reflection, in
     * which case we don't touch anything so as not to interfere
     * with a later permissionful caller.
     */
    private static Set<String> rmmbMethodNames;
    private static synchronized boolean isRMMBMethodName(String name) {
	if (rmmbMethodNames == null) {
	    try {
		Set<String> names = new HashSet<String>();
		Method[] methods = RequiredModelMBean.class.getMethods();
		for (int i = 0; i < methods.length; i++)
		    names.add(methods[i].getName());
		rmmbMethodNames = names;
	    } catch (Exception e) {
		return true;
		// This is only an optimization so we'll go on to discover
		// whether the name really is an RMMB method.
	    }
	}
	return rmmbMethodNames.contains(name);
    }

    /**
     * Returns the value of a specific attribute defined for this
     * ModelMBean.
     * The last value returned by an attribute may be cached in the
     * attribute's descriptor.
     * The valid value will be in the 'value' field if there is one.
     * If the 'currencyTimeLimit' field in the descriptor is:
     * <UL>
     * <LI>  <b>&lt;0</b> Then the value is not cached and is never valid.
     *       The getter method is invoked for the attribute.
     *       The 'value' and 'lastUpdatedTimeStamp' fields are cleared.</LI>
     * <LI>  <b>=0</b> Then the value is always cached and always valid.
     *       The 'value' field is returned. If there is no'value' field
     *       then the getter method is invoked for the attribute.
     *       The 'lastUpdatedTimeStamp' field and `value' fields are set
     *       to the attribute's value and the current time stamp.</LI>
     * <LI>  <b>&gt;0</b> Represents the number of seconds that the 'value'
     *       field is valid.
     *       The 'value' field is no longer valid when
     *       'lastUpdatedTimeStamp' + 'currencyTimeLimit' &gt; Now.
     *   <UL>
     *        <LI>When 'value' is valid, 'value' is returned.</LI>
     *        <LI>When 'value' is no longer valid then the getter
     *            method is invoked for the attribute.
     *            The 'lastUpdatedTimeStamp' field and `value' fields
     *            are updated.</LI>
     *   </UL></LI>
     * </UL>
     *
     * <p><b>Note:</b> because of inconsistencies in previous versions of
     * this specification, it is recommended not to use negative or zero
     * values for <code>currencyTimeLimit</code>.  To indicate that a
     * cached value is never valid, omit the
     * <code>currencyTimeLimit</code> field.  To indicate that it is
     * always valid, use a very large number for this field.</p>
     *
     * <p>If the 'getMethod' field contains the name of a valid
     * operation descriptor, then the method described by the
     * operation descriptor is executed.  The response from the
     * method is returned as the value of the attribute.  If the
     * operation fails or the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     *
     * <p>If no 'getMethod' field is defined then the default value of the
     * attribute is returned. If the returned value is not compatible with
     * the declared type of the attribute, an exception will be thrown.</p>
     * 
     * <p>The declared type of the attribute is the String returned by
     * {@link ModelMBeanAttributeInfo#getType()}.  A value is compatible
     * with this type if one of the following is true:
     * <ul>
     * <li>the value is null;</li>
     * <li>the declared name is a primitive type name (such as "int")
     *     and the value is an instance of the corresponding wrapper
     *     type (such as java.lang.Integer);</li>
     * <li>the name of the value's class is identical to the declared name;</li>
     * <li>the declared name can be loaded by the value's class loader and
     *     produces a class to which the value can be assigned.</li>
     * </ul>
     *
     * <p>In this implementation, in every case where the getMethod needs to
     * be called, because the method is invoked through the standard "invoke"
     * method and thus needs operationInfo, an operation must be specified
     * for that getMethod so that the invocation works correctly.</p>
     *
     * @param attrName A String specifying the name of the
     * attribute to be retrieved. It must match the name of a
     * ModelMBeanAttributeInfo.
     *
     * @return The value of the retrieved attribute from the
     * descriptor 'value' field or from the invocation of the
     * operation in the 'getMethod' field of the descriptor.
     *
     * @exception AttributeNotFoundException The specified attribute is
     *    not accessible in the MBean.
     *    The following cases may result in an AttributeNotFoundException:
     *    <UL>
     *      <LI> No ModelMBeanInfo was found for the Model MBean.</LI>
     *      <LI> No ModelMBeanAttributeInfo was found for the specified
     *           attribute name.</LI>
     *      <LI> The ModelMBeanAttributeInfo isReadable method returns
     *           'false'.</LI>
     *    </UL>
     * @exception MBeanException  Wraps one of the following Exceptions:
     *    <UL>
     *      <LI> {@link InvalidAttributeValueException}: A wrong value type
     *           was received from the attribute's getter method or
     *           no 'getMethod' field defined in the descriptor for
     *           the attribute and no default value exists.</LI>
     *      <LI> {@link ServiceNotFoundException}: No
     *           ModelMBeanOperationInfo defined for the attribute's
     *           getter method or no descriptor associated with the
     *           ModelMBeanOperationInfo or the managed resource is
     *           null.</LI>
     *      <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
     *           field value is not 'objectReference'.</LI>
     *      <LI> An Exception thrown by the managed object's getter.</LI>
     *    </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *    thrown while trying to invoke the getter.
     * @exception RuntimeOperationsException Wraps an
     *    {@link IllegalArgumentException}: The attribute name in
     *    parameter is null.
     *
     * @see #setAttribute(javax.management.Attribute)
     **/
    public Object getAttribute(String attrName)
	throws AttributeNotFoundException, MBeanException,
	       ReflectionException {
	if (attrName == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("attributeName must not be null"),
		"Exception occurred trying to get attribute of a " +
	        "RequiredModelMBean");

	if (tracing())
	    trace("getAttribute(String)","Entry with" + attrName);

	/* Check attributeDescriptor for getMethod */
	ModelMBeanAttributeInfo attrInfo=null;
	Descriptor attrDescr=null;
	Object response = null;

	try {
	    if (modelMBeanInfo == null)
		throw new AttributeNotFoundException(
                      "getAttribute failed: ModelMBeanInfo not found for "+
		      attrName);

	    attrInfo = modelMBeanInfo.getAttribute(attrName);
	    Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();

	    if (attrInfo == null)
		throw new AttributeNotFoundException("getAttribute failed:"+
		      " ModelMBeanAttributeInfo not found for " + attrName);
	
	    attrDescr = attrInfo.getDescriptor();
	    if (attrDescr != null) {
		if (!attrInfo.isReadable()) 			
		    throw new AttributeNotFoundException(
			  "getAttribute failed: " + attrName +
			  " is not readable ");
		
		response = resolveForCacheValue(attrDescr);

		/* return current cached value */
		if (tracing())
		    trace("getAttribute(String)","*** cached value is " +
			  response);

		if (response == null) {
		    /* no cached value, run getMethod */
		    if (tracing())
			trace("getAttribute(String)",
			      "**** cached value is null" +
			      " - " + "getting getMethod");
		    String attrGetMethod =
			(String)(attrDescr.getFieldValue("getMethod"));

		    if (attrGetMethod != null) {	
			/* run method from operations descriptor */
			if (tracing())
			    trace("getAttribute(String)",
				  "invoking a getMethod for " +  attrName);

			Object getResponse =
			    invoke(attrGetMethod, new Object[] {},
				   new String[] {});

			if (getResponse != null) {
			    // error/validity check return value here
			    if (tracing())
				trace("getAttribute(String)",
				 "got a non-null response from getMethod\n");

			    response = getResponse;

			    // change cached value in attribute descriptor
			    Object objctl =
				attrDescr.getFieldValue("currencyTimeLimit");

			    String ctl;
			    if (objctl != null) ctl = objctl.toString();
			    else ctl = null;
			
			    if ((ctl == null) && (mmbDesc != null)) {
				objctl = mmbDesc.
				    getFieldValue("currencyTimeLimit");
				if (objctl != null) ctl = objctl.toString();
				else ctl = null;
			    }

			    if ((ctl != null) && !(ctl.equals("-1"))) {
				if (tracing())
				    trace("getAttribute(String)",
					  "setting cached value and "+
					  "lastUpdatedTime in descriptor");

				attrDescr.setField("value", response);
				final String stamp =
				    (new Long((new Date()).getTime())).
				    toString();
				attrDescr.setField("lastUpdatedTimeStamp",
						   stamp);
				attrInfo.setDescriptor(attrDescr);
				modelMBeanInfo.setDescriptor(attrDescr,
							     "attribute");
				if (tracing()) {
				    trace("getAttribute(String)",
					  "new descriptor is " +
					  attrDescr.toString());
				    trace("getAttribute(String)","local: "+
					  "AttributeInfo descriptor is "+
					  attrInfo.getDescriptor().
					  toString());
				    final String attStr = modelMBeanInfo.
					getDescriptor(attrName,"attribute").
					toString();
				    trace("getAttribute(String)",
					  "modelMBeanInfo: " +
					  "AttributeInfo descriptor is " +
					  attStr);
				}
			    }
			} else {
			    // response was invalid or really returned null
			    if (tracing())
				trace("getAttribute(String)",
				     "got a null response from getMethod\n");
			    response = null;
			}
		    } else {
			// not getMethod so return descriptor (default) value
			String qualifier="";
			response = attrDescr.getFieldValue("value");
			if (response == null) {
			    qualifier="default ";
			    response = attrDescr.getFieldValue("default");
			}
			if (tracing())
			    trace("getAttribute(String)",
				  "could not find getMethod for " +
				  attrName + ", returning descriptor " +
				  qualifier + "value");
			// !! cast response to right class
		    }
		}

		// make sure response class matches type field
		String respType = attrInfo.getType();
		if (response != null) {
		    String responseClass = response.getClass().getName();
		    if (!respType.equals(responseClass)) {
			boolean wrongType = false;
                        boolean primitiveType = false;
                        boolean correspondingTypes = false;
                        for (int i = 0; i < primitiveTypes.length; i++) {
                            if (respType.equals(primitiveTypes[i])) {
                                primitiveType = true;
                                if (responseClass.equals(primitiveWrappers[i]))
                                    correspondingTypes = true;
                                break;
                            }
                        }
			if (primitiveType) {
			    // inequality may come from primitive/wrapper class
			    if (!correspondingTypes)
				wrongType = true;
			} else {
			    // inequality may come from type subclassing
			    boolean subtype;
			    try {
				ClassLoader cl =
				    response.getClass().getClassLoader();
				Class c = Class.forName(respType, true, cl);
				subtype = c.isInstance(response);
			    } catch (Exception e) {
				subtype = false;
				if (tracing())
				    traceX("getAttribute(String)", e);
			    }
			    if (!subtype)
				wrongType = true;
			}
			if (wrongType) {
			    if (tracing())
				trace("getAttribute(String)",
				      "Wrong response type '" + respType + "'");
			    // throw exception, didn't get
			    // back right attribute type
			    throw new MBeanException(
			      new InvalidAttributeValueException(
			        "Wrong value type received for get attribute"),
			      "An exception occurred while trying to get an " +
			      "attribute value through a RequiredModelMBean");
			}
                    }
		}
	    } else {
		if (tracing())
		    trace("getAttribute(String)","getMethod failed " +
			  attrName + " not in attributeDescriptor\n");
		throw new MBeanException(new
		    InvalidAttributeValueException(
		    "Unable to resolve attribute value, " +
		    "no getMethod defined in descriptor for attribute"),
		    "An exception occurred while trying to get an "+
		    "attribute value through a RequiredModelMBean");
	    }

	} catch (MBeanException mbe) {
	    throw mbe;
	} catch (AttributeNotFoundException t) {
	    throw t;
	} catch (Exception e) {
	    if (tracing())
		trace("getAttribute(String)","getMethod failed with " +
		      e.getMessage() + " exception type " +
		      (e.getClass()).toString());
	    throw new MBeanException(e,"An exception occurred while trying "+
		      "to get an attribute value: " + e.getMessage());
	}
		
	if (tracing())
	    trace("getAttribute(String)","Exit");

	return response;
    }

    /**
     * Returns the values of several attributes in the ModelMBean.
     * Executes a getAttribute for each attribute name in the
     * attrNames array passed in.
     *
     * @param attrNames A String array of names of the attributes
     * to be retrieved.
     *
     * @return The array of the retrieved attributes.
     *
     * @exception RuntimeOperationsException Wraps an
     * {@link IllegalArgumentException}: The object name in parameter is
     * null or attributes in parameter is null.
     *
     * @see #setAttributes(javax.management.AttributeList)
     */
    public AttributeList getAttributes(String[] attrNames)	{
	if (tracing())
	    trace("getAttributes(String[])","Entry");

	AttributeList responseList = null;
	if (attrNames == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("attributeNames must not be null"),
		"Exception occurred trying to get attributes of a "+
		"RequiredModelMBean");

	responseList = new AttributeList();
	for (int i = 0; i < attrNames.length; i++) {
	    try {
		responseList.add(new Attribute(attrNames[i],
				     getAttribute(attrNames[i])));
	    } catch (Exception e) {
		// eat exceptions because interface doesn't have an
		// exception on it
		error("getAttributes(String[])","Failed to get \"" +
		      attrNames[i] + "\": " + e);
		traceX("getAttributes(String[])",e);
	    }
	}
	
	if (tracing())
	    trace("getAttributes(String[])","Exit");
		
	return responseList;
    }

    /**
     * Sets the value of a specific attribute of a named ModelMBean.
     *
     * If the 'setMethod' field of the attribute's descriptor
     * contains the name of a valid operation descriptor, then the
     * method described by the operation descriptor is executed.
     * In this implementation, the operation descriptor must be specified
     * correctly and assigned to the modelMBeanInfo so that the 'setMethod'
     * works correctly.
     * The response from the method is set as the value of the attribute
     * in the descriptor.
     *
     * <p>If currencyTimeLimit is &gt; 0, then the new value for the
     * attribute is cached in the attribute descriptor's
     * 'value' field and the 'lastUpdatedTimeStamp' field is set to
     * the current time stamp.
     *
     * <p>If the persist field of the attribute's descriptor is not null
     * then Persistence policy from the attribute descriptor is used to
     * guide storing the attribute in a persistent store.
     * <br>Store the MBean if 'persistPolicy' field is:
     * <UL>
     * <Li> != "never"</Li>
     * <Li> = "always"</Li>
     * <Li> = "onUpdate"</Li>
     * <Li> = "onTimer" and now &gt; 'lastPersistTime' + 'persistPeriod'</Li>
     * <Li> = "NoMoreOftenThan" and now &gt; 'lastPersistTime' +
     *         'persistPeriod'</Li>
     * </UL>
     * Do not store the MBean if 'persistPolicy' field is:
     * <UL>
     * <Li> = "never"</Li>
     * <Li> = "onTimer" && now &lt; 'lastPersistTime' + 'persistPeriod'</Li>
     * <Li> = "onUnregister"</Li>
     * <Li> = "NoMoreOftenThan" and now &lt; 'lastPersistTime' +
     *        'persistPeriod'</Li>
     * </UL>
     *
     * <p>The ModelMBeanInfo of the Model MBean is stored in a file.
     *
     * @param attribute The Attribute instance containing the name of
     *        the attribute to be set and the value it is to be set to.
     *
     *
     * @exception AttributeNotFoundException The specified attribute is
     *   not accessible in the MBean.
     *   <br>The following cases may result in an AttributeNotFoundException:
     *   <UL>
     *     <LI> No ModelMBeanAttributeInfo is found for the specified
     *          attribute.</LI>
     *     <LI> The ModelMBeanAttributeInfo's isWritable method returns
     *          'false'.</LI>
     *   </UL>
     * @exception InvalidAttributeValueException No descriptor is defined
     *   for the specified attribute.
     * @exception MBeanException Wraps one of the following Exceptions:
     *   <UL>
     *     <LI> An Exception thrown by the managed object's setter.</LI>
     *     <LI> A {@link ServiceNotFoundException} if a setMethod field is 
     *          defined in the descriptor for the attribute and the managed 
     *          resource is null; or if no setMethod field is defined and 
     *          caching is not enabled for the attribute. 
     *          Note that if there is no getMethod field either, then caching 
     *          is automatically enabled.</LI>
     *     <LI> {@link InvalidTargetObjectTypeException} The 'targetType'
     *          field value is not 'objectReference'.</LI>
     *     <LI> An Exception thrown by the managed object's getter.</LI>
     *   </UL>
     * @exception ReflectionException  Wraps an {@link java.lang.Exception}
     *   thrown while trying to invoke the setter.
     * @exception RuntimeOperationsException Wraps an
     *   {@link IllegalArgumentException}: The attribute in parameter is
     *   null.
     *
     * @see #getAttribute(java.lang.String)
     **/
    public void setAttribute(Attribute attribute)
	throws AttributeNotFoundException, InvalidAttributeValueException,
	       MBeanException, ReflectionException {
	
	if (tracing())
	    trace("setAttribute()","Entry");

	if (attribute == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("attribute must not be null"),
		"Exception occurred trying to set an attribute of a "+
		"RequiredModelMBean");
	
	/* run setMethod if there is one */
	/* return cached value if its current */
	/* set cached value in descriptor and set date/time */
	/* send attribute change Notification */
	/* check persistence policy and persist if need be */
	String attrName = attribute.getName();
	Object attrValue = attribute.getValue();
	boolean updateDescriptor = false;

	ModelMBeanAttributeInfo attrInfo =
	    modelMBeanInfo.getAttribute(attrName);

	if (attrInfo == null)
	    throw new AttributeNotFoundException("setAttribute failed: " +
					       attrName + " is not found ");

	Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
	Descriptor attrDescr = attrInfo.getDescriptor();

	if (attrDescr != null) {
	    if (!attrInfo.isWritable())	
		throw new AttributeNotFoundException("setAttribute failed: "
					  + attrName + " is not writable ");

	    Object setResponse = null;
	    String attrSetMethod = (String)
		(attrDescr.getFieldValue("setMethod"));
            String attrGetMethod = (String)
		(attrDescr.getFieldValue("getMethod"));
            
	    String attrType = (String)(attrInfo.getType());
	    Object currValue = "Unknown";

	    try {
		currValue = this.getAttribute(attrName);
	    } catch (Throwable t) {			
		// OK: Default "Unknown" value used for unknown attribute
	    }

	    Attribute oldAttr = new Attribute(attrName, currValue);
					
	    /* run method from operations descriptor */
	    if (attrSetMethod == null) {
		if (attrValue != null) {
		    try {
			final Class  clazz    = loadClass(attrType);
			if (! clazz.isInstance(attrValue))  throw new
			    InvalidAttributeValueException(clazz.getName() +
							   " expected, "   +
					    attrValue.getClass().getName() +
							   " received.");
		    } catch (ClassNotFoundException x) {
			error("setAttribute","Class " + attrType +
			      " for attribute " + attrName + " not found: " +
			      x);
			debug("setAttribute",x);
		    }
		}
		updateDescriptor = true;
	    } else {
	    setResponse = invoke(attrSetMethod,
				 (new Object[] {attrValue}),
				 (new String[] {attrType}) );
	    }
		
	    /* change cached value */
	    Object objctl = attrDescr.getFieldValue("currencyTimeLimit");
	    String ctl;
	    if (objctl != null) ctl = objctl.toString();
	    else ctl = null;
					
	    if ((ctl == null) && (mmbDesc != null)) {		
		objctl = mmbDesc.getFieldValue("currencyTimeLimit");
		if (objctl != null) ctl = objctl.toString();
		else ctl = null;
	    }
		
	    final boolean updateCache = ((ctl != null) && !(ctl.equals("-1")));

             if(attrSetMethod == null  && !updateCache && attrGetMethod != null)
                throw new MBeanException(new ServiceNotFoundException("No " +
                        "setMethod field is defined in the descriptor for " +
                        attrName + " attribute and caching is not enabled " +
                        "for it"));
            
	    if (updateCache || updateDescriptor) {
		if (tracing())
		    trace("setAttribute()","setting cached value of " +
			  attrName + " to " + attrValue);

		attrDescr.setField("value", attrValue);

		if (updateCache) {
		    final String currtime =
			(new Long((new Date()).getTime())).toString();

		attrDescr.setField("lastUpdatedTimeStamp", currtime);
		}

		attrInfo.setDescriptor(attrDescr);
			
		modelMBeanInfo.setDescriptor(attrDescr,"attribute");
		if (tracing()) {
		    trace("setAttribute()","new descriptor is " +
			  attrDescr.toString());
		    trace("setAttribute()","AttributeInfo descriptor is " +
			  attrInfo.getDescriptor().toString());
		    trace("setAttribute()","AttributeInfo descriptor is " +
			  modelMBeanInfo.getDescriptor(attrName,"attribute")
			  .toString());
		}
			
	    }

	    if (tracing())
		trace("setAttribute()","sending sendAttributeNotification");
		
	    sendAttributeChangeNotification(oldAttr,attribute);
		
	} else { // if descriptor ... else no descriptor
				
	    if (tracing())
		trace("setAttribute(String)","setMethod failed "+attrName+
		      " not in attributeDescriptor\n");

	    throw new InvalidAttributeValueException(
                      "Unable to resolve attribute value, "+
		      "no defined in descriptor for attribute");
	} // else no descriptor
			
	if (tracing())
	    trace("setAttribute(Attribute)","Exit");

    }

    /**
     * Sets the values of an array of attributes of this ModelMBean.
     * Executes the setAttribute() method for each attribute in the list.
     *
     * @param attributes A list of attributes: The identification of the
     * attributes to be set and  the values they are to be set to.
     *
     * @return  The array of attributes that were set, with their new
     *    values in Attribute instances.
     *
     * @exception RuntimeOperationsException Wraps an
     *   {@link IllegalArgumentException}: The object name in parameter
     *   is null or attributes in parameter is null.
     *
     * @see #getAttributes
     **/
    public AttributeList setAttributes(AttributeList attributes) {

	if (tracing())
	    trace("setAttributes(AttributeList)","Entry");

	if (attributes == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("attributes must not be null"),
		"Exception occurred trying to set attributes of a "+
		"RequiredModelMBean");

	final AttributeList responseList = new AttributeList();

	// Go through the list of attributes
	for (Iterator i = attributes.iterator(); i.hasNext();) {
	    final Attribute attr = (Attribute) i.next();
	    try {
		setAttribute(attr);
		responseList.add(attr);
	    } catch (Exception excep) {
		responseList.remove(attr);
	    }
	}

	return responseList;
    }



    private ModelMBeanInfo createDefaultModelMBeanInfo() {
	return(new ModelMBeanInfoSupport((this.getClass().getName()),
		   "Default ModelMBean", null, null, null, null));
    }

    /*************************************/
    /* NotificationBroadcaster Interface */
    /*************************************/


    private synchronized void writeToLog(String logFileName,
					 String logEntry) throws Exception {
	
	PrintStream logOut = null;
	FileOutputStream fos = null;
	if (tracing()) trace("writeToLog()","Notification Logging to " +
			     logFileName + ": " + logEntry);
	if ((logFileName == null) || (logEntry == null)) {
	    if (tracing()) trace("writeToLog()","Bad input parameters");
	    return;
	}

	try {
	    fos = new FileOutputStream(logFileName, true);
	    logOut = new PrintStream(fos);
	    logOut.println(logEntry);
            logOut.close();
	    if (tracing()) trace("writeToLog()",
				 "Successfully opened log " + logFileName);
	} catch (Exception e) {
	    if (tracing())
		trace("writeToLog","Exception " + e.toString() +
		      " trying to write to the Notification log file " +
		      logFileName);
	    throw e;
	}		
    }


    /**
     * Registers an object which implements the NotificationListener
     * interface as a listener.  This
     * object's 'handleNotification()' method will be invoked when any
     * notification is issued through or by the ModelMBean.  This does
     * not include attributeChangeNotifications.  They must be registered
     * for independently.
     *
     * @param listener The listener object which will handles
     *        notifications emitted by the registered MBean.
     * @param filter The filter object. If null, no filtering will be
     *        performed before handling notifications.
     * @param handback The context to be sent to the listener with
     *        the notification when a notification is emitted.
     *
     * @exception IllegalArgumentException The listener cannot be null.
     *
     * @see #removeNotificationListener
     */
    public void addNotificationListener(NotificationListener listener,
					NotificationFilter filter,
					Object handback)
	throws java.lang.IllegalArgumentException {
	final String ftag = "addNotificationListener(NotificationListener, NotificationFilter, Object)";
	if (tracing())
	    trace(ftag,"Entry");
		
	if (listener == null)
	    throw new IllegalArgumentException(
                  "notification listener must not be null");

	if (generalBroadcaster == null)
	    generalBroadcaster = new NotificationBroadcasterSupport();

	generalBroadcaster.addNotificationListener(listener, filter,
						   handback);
	if (tracing()) {
	    trace(ftag,"NotificationListener added");
	    trace(ftag,"Exit");
	}
    }

    /**
     * Removes a listener for Notifications from the RequiredModelMBean.
     *
     * @param listener The listener name which was handling notifications
     *    emitted by the registered MBean.
     *    This method will remove all information related to this listener.
     *
     * @exception ListenerNotFoundException The listener is not registered
     *    in the MBean or is null.
     *
     * @see #addNotificationListener
     **/
    public void removeNotificationListener(NotificationListener listener)
	throws ListenerNotFoundException {
	if (listener == null)
	    throw new ListenerNotFoundException(
		      "Notification listener is null");
	
	final String ftag="removeNotificationListener(NotificationListener)";

	if (tracing()) trace(ftag,"Entry");

	if (generalBroadcaster == null)
	    throw new ListenerNotFoundException(
                  "No notification listeners registered");
	
	
	generalBroadcaster.removeNotificationListener(listener);

	if (tracing()) trace(ftag,"Exit");
		
    }

    public void removeNotificationListener(NotificationListener listener,
					   NotificationFilter filter,
					   Object handback)
	throws ListenerNotFoundException {

	if (listener == null)
	    throw new ListenerNotFoundException(
		      "Notification listener is null");
	
	final String ftag="removeNotificationListener(NotificationListener, NotificationFilter, Object)";

	if (tracing()) trace(ftag,"Entry");

	if (generalBroadcaster == null)
	    throw new ListenerNotFoundException(
                  "No notification listeners registered");
	
	
	generalBroadcaster.removeNotificationListener(listener,filter,
						      handback);

	if (tracing()) trace(ftag,"Exit");
		
    }

    public void sendNotification(Notification ntfyObj)
	throws MBeanException, RuntimeOperationsException {
	if (tracing())
	    trace("sendNotification(Notification)","Entry");

	if (ntfyObj == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("notification object must not be "+
					 "null"),
		"Exception occurred trying to send a notification from a "+
		"RequiredModelMBean");
		
	
	// log notification if specified in descriptor		
	Descriptor ntfyDesc =
	    modelMBeanInfo.getDescriptor(ntfyObj.getType(),"notification");
	Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();

	if (ntfyDesc != null) {
	    String logging = (String) ntfyDesc.getFieldValue("log");

	    if (logging == null) {
		if (mmbDesc != null)
		    logging = (String) mmbDesc.getFieldValue("log");
	    }

	    if ((logging != null) &&
		(logging.equalsIgnoreCase("t") ||
		 logging.equalsIgnoreCase("true"))) {

		String logfile = (String) ntfyDesc.getFieldValue("logfile");
		if (logfile == null) {
		    if (mmbDesc != null)
			logfile = (String)mmbDesc.getFieldValue("logfile");
		}
		if (logfile != null) {				
		    try {
			writeToLog(logfile,"LogMsg: " +
			    ((new Date(ntfyObj.getTimeStamp())).toString())+
			    " " + ntfyObj.getType() + " " +
			    ntfyObj.getMessage() + " Severity = " +
			    (String)ntfyDesc.getFieldValue("severity"));
		    } catch (Exception e) {
			error("sendNotification(Notification)",
			      "Failed to log " + ntfyObj.getType() +
			      " notification: " + e);
			traceX("sendNotification(Notification)",e);
		    }
		}
	    }
	}
	if (generalBroadcaster != null) {
	    generalBroadcaster.sendNotification(ntfyObj);
	}

	if (tracing()) trace("sendNotification(Notification)",
		  "sendNotification sent provided notification object");
		
	if (tracing())
	    trace("sendNotification(Notification)","Exit");

    }


    public void sendNotification(String ntfyText)
	throws MBeanException, RuntimeOperationsException {
	if (tracing())
	    trace("sendNotification(String)","Entry");

	if (ntfyText == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("notification message must not "+
					 "be null"),
		"Exception occurred trying to send a text notification "+
		"from a ModelMBean");
		
	Notification myNtfyObj = new Notification("jmx.modelmbean.generic",
						  this, 1, ntfyText);
	sendNotification(myNtfyObj);
	if (tracing()) trace("sendNotification(string)",
			     "Notification sent");

	if (tracing())
	    trace("sendNotification(String)","Exit");
    }

    /**
     * Returns `true' if the notification `notifName' is found
     * in `info'. (bug 4744667)
     **/
    private static final
	boolean hasNotification(final ModelMBeanInfo info,
				final String notifName) {
	try {
	    if (info == null) return false;
	    else return (info.getNotification(notifName)!=null);
	} catch (MBeanException x) {
	    return false;
	} catch (RuntimeOperationsException r) {
	    return false;
	}
    }

    /**
     * Creates a default ModelMBeanNotificationInfo for GENERIC
     * notification.  (bug 4744667)
     **/
    private static final ModelMBeanNotificationInfo makeGenericInfo() {
	final Descriptor genericDescriptor = new DescriptorSupport( new
	    String[] {
		"name=GENERIC",
		"descriptorType=notification",
		"log=T",
		"severity=6",
		"displayName=jmx.modelmbean.generic"} );
	
	return new ModelMBeanNotificationInfo(new
	    String[] {"jmx.modelmbean.generic"},
	    "GENERIC",
	    "A text notification has been issued by the managed resource",
	    genericDescriptor);
    }

    /**
     * Creates a default ModelMBeanNotificationInfo for ATTRIBUTE_CHANGE
     * notification.  (bug 4744667)
     **/
    private static final
	ModelMBeanNotificationInfo makeAttributeChangeInfo() {
	final Descriptor attributeDescriptor = new DescriptorSupport(new
	    String[] {
		"name=ATTRIBUTE_CHANGE",
		"descriptorType=notification",
		"log=T",
		"severity=6",
		"displayName=jmx.attribute.change"});

	return new ModelMBeanNotificationInfo(new
	    String[] {"jmx.attribute.change"},
	    "ATTRIBUTE_CHANGE",
	    "Signifies that an observed MBean attribute value has changed",
	    attributeDescriptor );
    }

    /**
     * Returns the array of Notifications always generated by the
     * RequiredModelMBean.
     * <P>
     *
     * RequiredModelMBean may always send also two additional notifications:
     * <UL>
     *   <LI> One with descriptor <code>"name=GENERIC,descriptorType=notification,log=T,severity=6,displayName=jmx.modelmbean.generic"</code></LI>
     *   <LI> Second is a standard attribute change notification
     *        with descriptor <code>"name=ATTRIBUTE_CHANGE,descriptorType=notification,log=T,severity=6,displayName=jmx.attribute.change"</code></LI>
     * </UL>
     * Thus these two notifications are always added to those specified
     * by the application.
     *
     * @return MBeanNotificationInfo[]
     *
     **/
    public MBeanNotificationInfo[] getNotificationInfo() {
	if (tracing())
	   trace("getNotificationInfo()","Entry");

	// Using hasNotification() is not optimal, but shouldn't really
	// matter in this context...
	
	// hasGeneric==true if GENERIC notification is present.
	// (bug 4744667)
	final boolean hasGeneric = hasNotification(modelMBeanInfo,"GENERIC");

	// hasAttributeChange==true if ATTRIBUTE_CHANGE notification is
	// present.
	// (bug 4744667)
	final boolean hasAttributeChange =
	   hasNotification(modelMBeanInfo,"ATTRIBUTE_CHANGE");

	// User supplied list of notification infos.
	//
	final ModelMBeanNotificationInfo[] currInfo =
	   (ModelMBeanNotificationInfo[])modelMBeanInfo.getNotifications();

	// Length of the returned list of notification infos:
	//    length of user suplied list + possibly 1 for GENERIC, +
	//    possibly 1 for ATTRIBUTE_CHANGE
	//    (bug 4744667)
	final int len = ((currInfo==null?0:currInfo.length) +
			 (hasGeneric?0:1) + (hasAttributeChange?0:1));

	// Returned list of notification infos:
	//
	final ModelMBeanNotificationInfo[] respInfo =
	   new ModelMBeanNotificationInfo[len];

	// Preserve previous ordering (JMX 1.1)
	//
	
	// Counter of "standard" notification inserted before user
	// supplied notifications.
	//
	int inserted=0;
	if (!hasGeneric)
	    // We need to add description for GENERIC notification
	    // (bug 4744667)
	    respInfo[inserted++] = makeGenericInfo();
	

	if (!hasAttributeChange)
	    // We need to add description for ATTRIBUTE_CHANGE notification
	    // (bug 4744667)
	    respInfo[inserted++] = makeAttributeChangeInfo();

	// Now copy user supplied list in returned list.
	//
	final int count  = currInfo.length;
	final int offset = inserted;
	for (int j=0; j < count; j++) {
	    respInfo[offset+j] = (ModelMBeanNotificationInfo)(currInfo[j]);
	}

	if (tracing())
            trace("getNotificationInfo()","Exit");

	return respInfo;
    }


    public void addAttributeChangeNotificationListener(NotificationListener
						       inlistener,
						       String
						       inAttributeName,
						       Object inhandback)
	throws MBeanException, RuntimeOperationsException,
	       IllegalArgumentException {
	final String ftag="addAttributeChangeNotificationListener(NotificationListener, String, Object)";

	if (tracing()) trace(ftag,"Entry");

	if (inlistener == null)
	    throw new IllegalArgumentException(
                  "Listener to be registered must not be null");
		
		 	
	if (attributeBroadcaster == null)
	    attributeBroadcaster = new NotificationBroadcasterSupport();

	AttributeChangeNotificationFilter currFilter =
	    new AttributeChangeNotificationFilter();

	MBeanAttributeInfo[] attrInfo = modelMBeanInfo.getAttributes();
	boolean found = false;
	if (inAttributeName == null) {		
	    if ((attrInfo != null) && (attrInfo.length>0)) {
		for (int i=0; i<attrInfo.length; i++) {
		    currFilter.enableAttribute(attrInfo[i].getName());
		}
	    }
	} else {
	    if ((attrInfo != null) && (attrInfo.length>0)) {
		for (int i=0; i<attrInfo.length; i++) {
		    if (inAttributeName.equals(attrInfo[i].getName())) {
			found = true;
			currFilter.enableAttribute(inAttributeName);
			break;
		    }				
		}
            }
            if (!found) {
                throw new RuntimeOperationsException(new
                    IllegalArgumentException(
                    "The attribute name does not exist"),
                    "Exception occurred trying to add an "+
                    "AttributeChangeNotification listener");
            }
	}

	if (tracing())
	    trace(ftag, "Set attribute change filter to " +
	    ((currFilter.getEnabledAttributes()).firstElement()).toString());

	attributeBroadcaster.addNotificationListener(inlistener,currFilter,
						     inhandback);
	if (tracing()) trace("addAttributeChangeNotificationListener",
			     "added for " + inAttributeName);
	
	if (tracing()) trace(ftag,"Exit");
    }

    public void removeAttributeChangeNotificationListener(NotificationListener inlistener, String inAttributeName)
	throws MBeanException, RuntimeOperationsException,
	       ListenerNotFoundException {
	if (inlistener == null) throw new
	    ListenerNotFoundException("Notification listener is null");
	
	final String ftag = "removeAttributeChangeNotificationListener(NotificationListener, String)";

	if (tracing()) trace(ftag,"Entry");
		
	
	if (attributeBroadcaster == null)
	    throw new ListenerNotFoundException(
                  "No attribute change notification listeners registered");
		
	
	MBeanAttributeInfo[] attrInfo = modelMBeanInfo.getAttributes();
	boolean found = false;	
	if ((attrInfo != null) && (attrInfo.length>0)) {
	    for (int i=0; i<attrInfo.length; i++) {
		if (attrInfo[i].getName().equals(inAttributeName)) {
		    found = true;
		    break;
		}				
	    }	
	}
		
	if ((!found) && (inAttributeName != null)) {
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("Invalid attribute name"),
		"Exception occurred trying to remove "+
		"attribute change notification listener");
	}

	/* note: */
        /* this may be a problem if the same listener is registered for
	   multiple attributes with multiple filters and/or handback
	   objects.  It may remove all of them */
		
	attributeBroadcaster.removeNotificationListener(inlistener);
		
		
	if (tracing()) trace(ftag,"Exit");
	
    }


    public void sendAttributeChangeNotification(AttributeChangeNotification
						ntfyObj)
	throws MBeanException, RuntimeOperationsException {
	final String ftag =
	    "sendAttributeChangeNotification(AttributeChangeNotification)";

	if (tracing()) trace(ftag,"Entry");
	
	if (ntfyObj == null)
	    throw new RuntimeOperationsException(new
		IllegalArgumentException(
                "attribute change notification object must not be null"),
		"Exception occurred trying to send "+
                "attribute change notification of a ModelMBean");
	
	Object oldv = ntfyObj.getOldValue();
	Object newv =  ntfyObj.getNewValue();

	if (oldv == null) oldv = "null";
	if (newv == null) newv = "null";
		
	if (tracing())
	    trace(ftag,"Sending AttributeChangeNotification " +
		  " with " + ntfyObj.getAttributeName() +
		  ntfyObj.getAttributeType() +
		  ntfyObj.getNewValue() +
		  ntfyObj.getOldValue());
	
	// log notification if specified in descriptor
	Descriptor ntfyDesc =
	    modelMBeanInfo.getDescriptor(ntfyObj.getType(),"notification");
	Descriptor mmbDesc = modelMBeanInfo.getMBeanDescriptor();
	
	String logging, logfile;
	
	if (ntfyDesc != null) {
	    logging =(String)  ntfyDesc.getFieldValue("log");
	    if (logging == null) {
		if (mmbDesc != null)
		    logging = (String) mmbDesc.getFieldValue("log");
	    }
	    if ((logging != null) &&
		( logging.equalsIgnoreCase("t") ||
		  logging.equalsIgnoreCase("true"))) {
		logfile = (String) ntfyDesc.getFieldValue("logfile");
		if (logfile == null) {
		    if (mmbDesc != null)
			logfile = (String)mmbDesc.getFieldValue("logfile");
		}
	    	
		if (logfile != null) {			
		    try {
			writeToLog(logfile,"LogMsg: " +
			   ((new Date(ntfyObj.getTimeStamp())).toString())+
			   " " + ntfyObj.getType() + " " +
			   ntfyObj.getMessage() +
			   " Name = " + ntfyObj.getAttributeName() +
			   " Old value = " + oldv +
			   " New value = " + newv);			
		    } catch (Exception e) {
			error(ftag,"Failed to log " + ntfyObj.getType() +
			      " notification: " + e);
			traceX(ftag,e);
		    }
		}
	    }
	} else if (mmbDesc != null) {
	    logging = (String) mmbDesc.getFieldValue("log");
	    if ((logging != null) &&
		( logging.equalsIgnoreCase("t") ||
		  logging.equalsIgnoreCase("true") )) {
		logfile = (String) mmbDesc.getFieldValue("logfile");

		if (logfile != null) {
		    try {
			writeToLog(logfile,"LogMsg: " +
			   ((new Date(ntfyObj.getTimeStamp())).toString())+
			   " " + ntfyObj.getType() + " " +
			   ntfyObj.getMessage() +
			   " Name = " + ntfyObj.getAttributeName() +
			   " Old value = " + oldv +
			   " New value = " + newv);
		    } catch (Exception e) {
			error(ftag,"Failed to log " + ntfyObj.getType() +
			      " notification: " + e);
			traceX(ftag,e);
		    }
		}	
	    }
	}
	if (attributeBroadcaster != null) {
	    attributeBroadcaster.sendNotification(ntfyObj);
	}

	// XXX Revisit: This is a quickfix: it would be better to have a
	//     single broadcaster. However, it is not so simple because
	//     removeAttributeChangeNotificationListener() should
	//     remove only listeners whose filter is an instanceof
	//     AttributeChangeNotificationFilter.
	//
	if (generalBroadcaster != null) {
	    generalBroadcaster.sendNotification(ntfyObj);
	}
	if (tracing()) trace(ftag,"sent notification");
	
	if (tracing()) trace(ftag,"Exit");
    }


    public void sendAttributeChangeNotification(Attribute inOldVal,
						Attribute inNewVal)
	throws MBeanException, RuntimeOperationsException {
	final String ftag =
	    "sendAttributeChangeNotification(Attribute, Attribute)";
	if (tracing()) trace(ftag,"Entry");

	// do we really want to do this?
	if ((inOldVal == null) || (inNewVal == null))
	    throw new RuntimeOperationsException(new
	       IllegalArgumentException("Attribute object must not be null"),
	       "Exception occurred trying to send " +
	       "attribute change notification of a ModelMBean");
	

	if (!(inOldVal.getName().equals(inNewVal.getName())))
	    throw new RuntimeOperationsException(new
		IllegalArgumentException("Attribute names are not the same"),
		"Exception occurred trying to send " +
		"attribute change notification of a ModelMBean");

	
	Object newVal = inNewVal.getValue();	
	Object oldVal = inOldVal.getValue();
	String className = "unknown";
	if (newVal != null)
	    className = newVal.getClass().getName();		
	if (oldVal != null)
	    className = oldVal.getClass().getName();
	
	AttributeChangeNotification myNtfyObj = new
	    AttributeChangeNotification(this,
					1,
					((new Date()).getTime()),
					"AttributeChangeDetected",
					inOldVal.getName(),
					className,
					inOldVal.getValue(),
					inNewVal.getValue());
	
	sendAttributeChangeNotification(myNtfyObj);

	if (tracing()) trace(ftag,"Exit");

    }

    /**
     * Return the Class Loader Repository used to perform class loading.
     * Subclasses may wish to redefine this method in order to return
     * the appropriate {@link javax.management.loading.ClassLoaderRepository}
     * that should be used in this object.
     *
     * @return the Class Loader Repository.
     *
     * @since.unbundled JMX 1.1
     */
    protected ClassLoaderRepository getClassLoaderRepository() {
	return MBeanServerFactory.getClassLoaderRepository(server);
    }

    private  Class loadClass(String className)
	throws ClassNotFoundException {
	try {
	    return Class.forName(className);
	} catch (ClassNotFoundException e) {
	    final ClassLoaderRepository clr =
		getClassLoaderRepository();
	    if (clr == null) throw new ClassNotFoundException(className);
	    return clr.loadClass(className);
	}
    }


    /*************************************/
    /* MBeanRegistration Interface       */
    /*************************************/

    /**
     * Allows the MBean to perform any operations it needs before
     * being registered in the MBean server.  If the name of the MBean
     * is not specified, the MBean can provide a name for its
     * registration.  If any exception is raised, the MBean will not be
     * registered in the MBean server.
     * <P>
     * In order to ensure proper run-time semantics of RequireModelMBean,
     * Any subclass of RequiredModelMBean overloading or overriding this
     * method should call <code>super.preRegister(server, name)</code>
     * in its own <code>preRegister</code> implementation.
     *
     * @param server The MBean server in which the MBean will be registered.
     *
     * @param name The object name of the MBean.  This name is null if
     * the name parameter to one of the <code>createMBean</code> or
     * <code>registerMBean</code> methods in the {@link MBeanServer}
     * interface is null.  In that case, this method must return a
     * non-null ObjectName for the new MBean.
     *
     * @return The name under which the MBean is to be registered.
     * This value must not be null.  If the <code>name</code>
     * parameter is not null, it will usually but not necessarily be
     * the returned value.
     *
     * @exception java.lang.Exception This exception will be caught by
     * the MBean server and re-thrown as an
     * {@link javax.management.MBeanRegistrationException
     * MBeanRegistrationException}.
     */
    public ObjectName preRegister(MBeanServer server,
				  ObjectName name)
	throws java.lang.Exception  {
        // Since ModelMbeanInfo cannot be null (otherwise exception
	// thrown at creation)
        // no exception thrown on ModelMBeanInfo not set.
        if (name == null) throw new NullPointerException(
		     "name of RequiredModelMBean to registered is null");
	this.server = server;
        return name;
    }

    /**
     * Allows the MBean to perform any operations needed after having been
     * registered in the MBean server or after the registration has failed.
     * <P>
     * In order to ensure proper run-time semantics of RequireModelMBean,
     * Any subclass of RequiredModelMBean overloading or overriding this
     * method should call <code>super.postRegister(registrationDone)</code>
     * in its own <code>postRegister</code> implementation.
     *
     * @param registrationDone Indicates whether or not the MBean has
     * been successfully registered in the MBean server. The value
     * false means that the registration phase has failed.
     */
    public void postRegister(Boolean registrationDone) {
        registered = registrationDone.booleanValue();
    }

    /**
     * Allows the MBean to perform any operations it needs before
     * being unregistered by the MBean server.
     * <P>
     * In order to ensure proper run-time semantics of RequireModelMBean,
     * Any subclass of RequiredModelMBean overloading or overriding this
     * method should call <code>super.preDeregister()</code> in its own
     * <code>preDeregister</code> implementation.
     *
     * @exception java.lang.Exception This exception will be caught by
     * the MBean server and re-thrown as an
     * {@link javax.management.MBeanRegistrationException
     * MBeanRegistrationException}.
     */
    public void preDeregister() throws java.lang.Exception {
    }

    /**
     * Allows the MBean to perform any operations needed after having been
     * unregistered in the MBean server.
     * <P>
     * In order to ensure proper run-time semantics of RequireModelMBean,
     * Any subclass of RequiredModelMBean overloading or overriding this
     * method should call <code>super.postDeregister()</code> in its own
     * <code>postDeregister</code> implementation.
     */
    public void postDeregister() {
        registered = false;
	this.server=null;
    }

    // SUN Trace and debug functions
    private final static boolean tracing() {
		
	return Trace.isSelected(Trace.LEVEL_TRACE, Trace.INFO_MODELMBEAN);
    }

    private static void trace(String inClass, String inMethod, String inText) {
	Trace.send(Trace.LEVEL_TRACE, Trace.INFO_MODELMBEAN, inClass,
		   inMethod, inText);
    }

    private static void traceX(String inMethod, Throwable x) {
	Trace.send(Trace.LEVEL_TRACE, Trace.INFO_MODELMBEAN, currClass,
		   inMethod, x);
    }

    private static void trace(String inMethod, String inText) {
	trace(currClass, inMethod, inText);
    }

    private static void error(String inMethod, String inText) {
	Trace.send(Trace.LEVEL_ERROR, Trace.INFO_MODELMBEAN, currClass,
		   inMethod, inText);
    }

    private static boolean debugging() {
	return Trace.isSelected(Trace.LEVEL_DEBUG, Trace.INFO_MODELMBEAN);
    }

    private static void debug(String inClass, String inMethod, String inText) {
	Trace.send(Trace.LEVEL_DEBUG, Trace.INFO_MODELMBEAN, inClass,
		   inMethod, inText);
    }

    private static void debug(String inMethod, String inText) {
	debug(currClass, inMethod, inText);
    }

    private static void debug(String inMethod, Throwable x) {
	Trace.send(Trace.LEVEL_DEBUG, Trace.INFO_MODELMBEAN, currClass,
		   inMethod, x);
    }

    private static final String[] primitiveTypes;
    private static final String[] primitiveWrappers;
    static {
        primitiveTypes = new String[] {
            Boolean.TYPE.getName(),
            Byte.TYPE.getName(),
            Character.TYPE.getName(),
            Short.TYPE.getName(),
            Integer.TYPE.getName(),
            Long.TYPE.getName(),
            Float.TYPE.getName(),
            Double.TYPE.getName(),
            Void.TYPE.getName()
        };
        primitiveWrappers = new String[] {
            Boolean.class.getName(),
            Byte.class.getName(),
            Character.class.getName(),
            Short.class.getName(),
            Integer.class.getName(),
            Long.class.getName(),
            Float.class.getName(),
            Double.class.getName(),
            Void.class.getName()
        };
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar