KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > compliance > server > MBeanServerTEST


1 /*
2  * JBoss, the OpenSource J2EE webOS
3  *
4  * Distributable under LGPL license.
5  * See terms of license at gnu.org.
6  */

7
8 package test.compliance.server;
9
10 import java.util.Arrays;
11 import java.util.List;
12
13 import javax.management.Attribute;
14 import javax.management.AttributeNotFoundException;
15 import javax.management.InstanceNotFoundException;
16 import javax.management.MBeanException;
17 import javax.management.MBeanRegistrationException;
18 import javax.management.MBeanServer;
19 import javax.management.MBeanServerFactory;
20 import javax.management.MBeanServerNotification;
21 import javax.management.Notification;
22 import javax.management.NotificationFilterSupport;
23 import javax.management.NotificationListener;
24 import javax.management.ObjectInstance;
25 import javax.management.ObjectName;
26 import javax.management.ReflectionException;
27 import javax.management.RuntimeErrorException;
28 import javax.management.RuntimeMBeanException;
29 import javax.management.RuntimeOperationsException;
30 import javax.management.loading.MLet;
31
32 import junit.framework.AssertionFailedError;
33 import junit.framework.TestCase;
34 import test.compliance.server.support.BabarError;
35 import test.compliance.server.support.Base;
36 import test.compliance.server.support.BaseMBean;
37 import test.compliance.server.support.Broadcaster;
38 import test.compliance.server.support.Derived;
39 import test.compliance.server.support.Dynamic;
40 import test.compliance.server.support.ExceptionOnTheRun;
41 import test.compliance.server.support.LockedTest;
42 import test.compliance.server.support.LockedTest2;
43 import test.compliance.server.support.LockedTest3;
44 import test.compliance.server.support.MBeanListener;
45 import test.compliance.server.support.MyScreamingException;
46 import test.compliance.server.support.Test;
47 import test.compliance.server.support.Test2;
48 import test.compliance.server.support.Test3;
49 import test.compliance.server.support.Test4;
50 import test.compliance.server.support.Unrelated;
51 import test.compliance.server.support.UnrelatedMBean;
52
53 /**
54  * Tests the MBean server impl. through the <tt>MBeanServer</tt> interface.
55  *
56  * @author <a HREF="mailto:juha@jboss.org">Juha Lindfors</a>.
57  * @version $Revision: 1.27 $
58  *
59  */

60 public class MBeanServerTEST
61    extends TestCase
62 {
63    public MBeanServerTEST(String s)
64    {
65       super(s);
66    }
67
68    
69    // MBeanServer invoke --------------------------------------------
70

71    /**
72     * Tests invoke with primitive boolean return type. <p>
73     */

74    public void testInvokeWithPrimitiveBooleanReturn() throws Exception
75    {
76       MBeanServer server = MBeanServerFactory.newMBeanServer();
77       ObjectName name = new ObjectName(":test=test");
78       server.registerMBean(new Test(), name);
79       
80       Boolean bool = (Boolean)server.invoke(name, "opWithPrimBooleanReturn", null, null);
81       
82       assertTrue(bool.booleanValue() == true);
83    }
84
85    /**
86     * Tests invoke with primitive long array return type. <p>
87     */

88    public void testInvokeWithPrimitiveLongArrayReturn() throws Exception
89    {
90       MBeanServer server = MBeanServerFactory.newMBeanServer();
91       ObjectName name = new ObjectName(":test=test");
92       server.registerMBean(new Test(), name);
93       
94       long[] array = (long[])server.invoke(name, "opWithPrimLongArrayReturn", null, null);
95       
96       assertTrue(array [0] == 1);
97       assertTrue(array [1] == 2);
98       assertTrue(array [2] == 3);
99    }
100
101    /**
102     * Tests invoke with Long array return type. <p>
103     */

104    public void testInvokeWithLongArrayReturn() throws Exception
105    {
106       MBeanServer server = MBeanServerFactory.newMBeanServer();
107       ObjectName name = new ObjectName(":test=test");
108       server.registerMBean(new Test(), name);
109       
110       Long[] array = (Long[])server.invoke(name, "opWithLongArrayReturn", null, null);
111       
112       assertTrue(array [0].longValue() == 1);
113       assertTrue(array [1].longValue() == 2);
114       assertTrue(array [2].longValue() == 3);
115    }
116    
117    /**
118     * Tests invoke with primitive long return type. <p>
119     */

120    public void testInvokeWithPrimitiveLongReturn() throws Exception
121    {
122       MBeanServer server = MBeanServerFactory.newMBeanServer();
123       ObjectName name = new ObjectName(":test=test");
124       server.registerMBean(new Test(), name);
125       
126       Long l = (Long)server.invoke(name, "opWithPrimLongReturn", null, null);
127       
128       assertTrue(l.longValue() == 1234567890123l);
129    }
130
131    /**
132     * Tests invoke with primitive double return type. <p>
133     */

134    public void testInvokeWithPrimitiveDoubleReturn() throws Exception
135    {
136       MBeanServer server = MBeanServerFactory.newMBeanServer();
137       ObjectName name = new ObjectName(":test=test");
138       server.registerMBean(new Test(), name);
139       
140       Double d = (Double)server.invoke(name, "opWithPrimDoubleReturn", null, null);
141       
142       assertTrue(d.doubleValue() == 0.1234567890123d);
143    }
144    
145    /**
146     * Tests invoke with long signature. <p>
147     */

148    public void testInvokeWithLongSignature() throws Exception
149    {
150       MBeanServer server = MBeanServerFactory.newMBeanServer();
151       ObjectName name = new ObjectName(":test=test");
152       server.registerMBean(new Test(), name);
153       
154       server.invoke(name, "opWithLongSignature",
155       new Object[] { new Integer(1), new Integer(2), new Integer(3), new Integer(4), new Integer(5),
156                      new Integer(6), new Integer(7), new Integer(8), new Integer(9), new Integer(10),
157                      new Integer(11), new Integer(12), new Integer(13), new Integer(14), new Integer(15),
158                      new Integer(16), new Integer(17), new Integer(18), new Integer(19), new Integer(20) },
159       new String[] { "int", "int", "int", "int", "int", "int", "int", "int", "int", "int",
160                      "int", "int", "int", "int", "int", "int", "int", "int", "int", "int" }
161       );
162    }
163
164    /**
165     * Tests invoke with mixed types in signature, especially types with double
166     * byte code length and arrays. <p>
167     */

168    public void testInvokeWithMixedSignature() throws Exception
169    {
170       MBeanServer server = MBeanServerFactory.newMBeanServer();
171       ObjectName name = new ObjectName(":test=test");
172       server.registerMBean(new Test(), name);
173       
174       server.invoke(name, "opWithMixedSignature",
175       new Object[] { new Integer(1), new Double(2.2D), new Long(333L), new Boolean(true), new Byte((byte)0x02),
176                      new Short((short)6), new long[]{7L, 8L}, new Long[]{new Long(1L), new Long(2L)}, new Short((short)9), new Byte((byte)10),
177                      new Long(11L), new Double(1.2D), new Integer(13), new Integer(14), new Integer(15),
178                      new Integer(16), new Integer(17), new Integer(18), new Integer(19), new Integer(20) },
179       new String[] { "int", "double", "long", "boolean", "byte", "short", "[J", "[Ljava.lang.Long;", "java.lang.Short", "java.lang.Byte",
180                      "java.lang.Long", "java.lang.Double", "int", "int", "int", "int", "int", "int", "int", "int" }
181       );
182    }
183
184    
185    /**
186     * Attempts to invoke a method on an unregistered MBean; <tt>InstanceNotFoundException</tt> should occur.
187     */

188    public void testInvokeWithNonExistantMBean() throws Exception
189    {
190       try
191       {
192          MBeanServer server = MBeanServerFactory.newMBeanServer();
193          server.invoke(new ObjectName(":mbean=doesnotexist"), "noMethod", null, null);
194
195          // should not reach here
196
fail("InstanceNotFoundException was not thrown from an invoke operation on a non-existant MBean.");
197       }
198       catch (InstanceNotFoundException e)
199       {
200          // should get here
201
}
202       
203    }
204
205    /**
206     * Attempts to invoke a MBean operation that throws a business exception; <tt>MBeanException</tt> should be thrown.
207     */

208    public void testInvokeWithBusinessException() throws Exception
209    {
210       try
211       {
212          MBeanServer server = MBeanServerFactory.newMBeanServer();
213          ObjectName name = new ObjectName("test:test=test");
214          server.registerMBean(new Test(), name);
215
216          server.invoke(name, "operationWithException", null, null);
217
218          // should not get here
219
fail("MBeanException was not thrown.");
220       }
221       catch (MBeanException e)
222       {
223          // this is expected
224
assertTrue(e.getTargetException() instanceof MyScreamingException);
225       }
226    }
227
228
229    // MBeanServer getAttribute --------------------------------------
230

231    public void testGetAttributeWithNonExistingAttribute() throws Exception
232    {
233       try
234       {
235          MBeanServer server = MBeanServerFactory.newMBeanServer();
236          Object foo = server.getAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), "Foo");
237
238          // should not reach here
239
fail("AttributeNotFoundexception was not thrown when invoking getAttribute() call on a non-existant attribute.");
240       }
241       catch (AttributeNotFoundException e)
242       {
243          // Expecting this.
244
}
245    }
246
247    public void testGetAttributeWithBusinessException() throws Exception
248    {
249       try
250       {
251          MBeanServer server = MBeanServerFactory.newMBeanServer();
252          ObjectName name = new ObjectName("test:test=test");
253          server.registerMBean(new Test(), name);
254
255          Object foo = server.getAttribute(name, "ThisWillScream");
256
257          // should not reach here
258
fail("Did not throw the screaming exception");
259       }
260       catch (MBeanException e)
261       {
262          // this is expected
263
assertTrue(e.getTargetException() instanceof MyScreamingException);
264       }
265    }
266
267    public void testGetAttributeWithNonExistingMBean() throws Exception
268    {
269       try
270       {
271          MBeanServer server = MBeanServerFactory.newMBeanServer();
272          ObjectName name = new ObjectName("test:name=DoesNotExist");
273
274          server.getAttribute(name, "Whatever");
275
276          // should not reach here
277
fail("InstanceNotFoundException was not thrown on a nonexistant MBean.");
278       }
279       catch (InstanceNotFoundException e)
280       {
281          // this is expected
282
}
283    }
284
285    public void testGetAttributeWithUncheckedException() throws Exception
286    {
287       try
288       {
289          MBeanServer server = MBeanServerFactory.newMBeanServer();
290          ObjectName name = new ObjectName("test:test=test");
291          server.registerMBean(new Test(), name);
292
293          server.getAttribute(name, "ThrowUncheckedException");
294
295          // should not reach here
296
fail("RuntimeMBeanException was not thrown");
297       }
298       catch (RuntimeMBeanException e)
299       {
300          // this is expected
301
assertTrue(e.getTargetException() instanceof ExceptionOnTheRun);
302       }
303    }
304
305    public void testGetAttributeWithError() throws Exception
306    {
307       try
308       {
309          MBeanServer server = MBeanServerFactory.newMBeanServer();
310          ObjectName name = new ObjectName("test:test=test");
311          server.registerMBean(new Test(), name);
312
313          server.getAttribute(name, "Error");
314
315          // should not reach here
316
fail("Error was not thrown");
317       }
318       catch (RuntimeErrorException e)
319       {
320          // this is expected
321
assertTrue(e.getTargetError() instanceof BabarError);
322       }
323    }
324
325    
326    // MBeanServer setAttribute --------------------------------------
327

328    public void testSetAttributeWithNonExistingAttribute() throws Exception
329    {
330       try
331       {
332          MBeanServer server = MBeanServerFactory.newMBeanServer();
333          server.setAttribute(new ObjectName("JMImplementation:type=MBeanServerDelegate"), new Attribute("Foo", "value"));
334
335          // should not reach here
336
fail("AttributeNotFoundexception was not thrown when invoking getAttribute() call on a non-existant attribute.");
337       }
338       catch (AttributeNotFoundException e)
339       {
340          // Expecting this.
341
}
342    }
343
344    public void testSetAttributeWithBusinessException() throws Exception
345    {
346       try
347       {
348          MBeanServer server = MBeanServerFactory.newMBeanServer();
349          ObjectName name = new ObjectName("test:test=test");
350          server.registerMBean(new Test(), name);
351
352          server.setAttribute(name, new Attribute("ThisWillScream", "value"));
353
354          // should not reach here
355
fail("Did not throw the screaming exception");
356       }
357       catch (MBeanException e)
358       {
359          // this is expected
360
assertTrue(e.getTargetException() instanceof MyScreamingException);
361       }
362    }
363
364    public void testSetAttributeWithNonExistingMBean() throws Exception
365    {
366       try
367       {
368          MBeanServer server = MBeanServerFactory.newMBeanServer();
369          ObjectName name = new ObjectName("test:name=DoesNotExist");
370
371          server.setAttribute(name, new Attribute("Whatever", "nothing"));
372
373          // should not reach here
374
fail("InstanceNotFoundException was not thrown on a nonexistant MBean.");
375       }
376       catch (InstanceNotFoundException e)
377       {
378          // this is expected
379
}
380    }
381
382    public void testSetAttributeWithUncheckedException() throws Exception
383    {
384       try
385       {
386          MBeanServer server = MBeanServerFactory.newMBeanServer();
387          ObjectName name = new ObjectName("test:test=test");
388          server.registerMBean(new Test(), name);
389
390          server.setAttribute(name, new Attribute("ThrowUncheckedException", "value"));
391
392          // should not reach here
393
fail("RuntimeMBeanException was not thrown");
394       }
395       catch (RuntimeMBeanException e)
396       {
397          // this is expected
398
assertTrue(e.getTargetException() instanceof ExceptionOnTheRun);
399       }
400    }
401
402    public void testSetAttributeWithError() throws Exception
403    {
404       try
405       {
406          MBeanServer server = MBeanServerFactory.newMBeanServer();
407          ObjectName name = new ObjectName("test:test=test");
408          server.registerMBean(new Test(), name);
409
410          server.setAttribute(name, new Attribute("Error", "value"));
411
412          // should not reach here
413
fail("Error was not thrown");
414       }
415       catch (RuntimeErrorException e)
416       {
417          // this is expected
418
assertTrue(e.getTargetError() instanceof BabarError);
419       }
420    }
421
422    
423    // MBeanServer instantiate ---------------------------------------
424

425    /**
426     * Tests instantiate(String className). Class defined by system classloader.
427     */

428    public void testInstantiateWithDefaultConstructor() throws Exception
429    {
430       MBeanServer server = MBeanServerFactory.newMBeanServer();
431       Object o = server.instantiate("test.compliance.server.support.Test");
432       
433       assertTrue(o instanceof test.compliance.server.support.Test);
434    }
435    
436    /**
437     * Tests instantiate(String className) with constructor that throws a checked application exception.
438     * Class defined by system classloader.
439     */

440     public void testInstantiateWithDefaultConstructorAndApplicationException() throws Exception
441     {
442        try
443        {
444           MBeanServer server = MBeanServerFactory.newMBeanServer();
445           Object o = server.instantiate("test.compliance.server.support.ConstructorTest");
446           
447           // shouldn't get here
448
fail("Instantiate should have thrown an MBeanException.");
449        }
450        catch (MBeanException e)
451        {
452           // this is expected
453
}
454     }
455     
456     /**
457      * Tests instantiate(String className) with constructor that throws an unchecked application exception.
458      * Class defined by the system classloader.
459      */

460     public void testInstantiateWithDefaultConstructorAndRuntimeException() throws Exception
461     {
462        try
463        {
464           MBeanServer server = MBeanServerFactory.newMBeanServer();
465           Object o = server.instantiate("test.compliance.server.support.ConstructorTest2");
466           
467           // shouldn't get here
468
fail("Instantiate should have thrown a RuntimeMBeanException.");
469        }
470        catch (RuntimeMBeanException e)
471        {
472           // this is expected
473
}
474     }
475     
476     /**
477      * Tests instantiate(String className) with constructor that throws an error.
478      * Class defined by the system classloader.
479      */

480     public void testInstantiateWithDefaultConstructorAndError() throws Exception
481     {
482        try
483        {
484           MBeanServer server = MBeanServerFactory.newMBeanServer();
485           Object o = server.instantiate("test.compliance.server.support.ConstructorTest3");
486           
487           // shouldn't get here
488
fail("Instantiate should have thrown a RuntimeErrorException.");
489        }
490        catch (RuntimeErrorException e)
491        {
492           // this is expected
493
}
494     }
495     
496     /**
497      * Tests instantiate(String className) with constructor that fails with an unchecked exception in static init block.
498      * Class defined by the system classloader.
499      */

500     public void testInstantiateWithDefaultConstructorAndExceptionInInit() throws Exception
501     {
502        try
503        {
504           MBeanServer server = MBeanServerFactory.newMBeanServer();
505           
506           // FAILS IN RI
507
try
508           {
509              Object o = server.instantiate("test.compliance.server.support.ConstructorTest4");
510           }
511           catch (ExceptionInInitializerError e)
512           {
513              // RI lets this error through unwrapped. In general, the MBean server is responsible
514
// of wrapping all errors and exceptions from MBeans and resource classes with either
515
// RuntimeErrorException, RuntimeMBeanException or MBeanException. The javadoc is unclear in
516
// this case should a ReflectionException or MBeanException be thrown (neither one can wrap an
517
// Error though). JBossMX throws an RuntimeMBeanException in case of an unchecked exception in
518
// static initializer and a RuntimeErrorException in case of an error in static initializer.
519
fail("FAILS IN RI: MBeanServer fails to wrap an error or exception from a static initializer block correctly.");
520           }
521           
522           // shouldn't get here
523
fail("Instantiate should have thrown a RuntimeMBeanException.");
524        }
525        catch (RuntimeMBeanException e)
526        {
527           // this is expected
528

529           assertTrue(e.getTargetException() instanceof NullPointerException);
530        }
531     }
532     
533     /**
534      * Tests instatiante(String className) with constructor that fails with an error in static init block.
535      * Class defined by the system classloader.
536      */

537     public void testInstantiateWithDefaultConstructorAndErrorInInit() throws Exception
538     {
539        try
540        {
541           MBeanServer server = MBeanServerFactory.newMBeanServer();
542           
543           // FAILS IN RI
544
try
545           {
546             Object o = server.instantiate("test.compliance.server.support.ConstructorTest5");
547           }
548           catch (BabarError e)
549           {
550              // RI lets this error through unwrapped. In general, the MBean server is responsible
551
// of wrapping all errors and exceptions from MBeans and resource classes with either
552
// RuntimeErrorException, RuntimeMBeanException or MBeanException. The javadoc is unclear in
553
// this case should a ReflectionException or MBeanException be thrown (neither one can wrap an
554
// Error though). JBossMX throws an RuntimeMBeanException in case of an unchecked exception in
555
// static initializer and a RuntimeErrorException in case of an error in static initializer.
556
fail("FAILS IN RI: MBeanServer fails to wrap an error or exception from a static initializer block correctly.");
557           }
558           
559           // shouldn't get here
560
fail("Instantiate should have thrown a RuntimeErrorException.");
561        }
562        catch (RuntimeErrorException e)
563        {
564           // this is expected
565

566           assertTrue(e.getTargetError() instanceof test.compliance.server.support.BabarError);
567        }
568     }
569     
570     /**
571      * Tests instantiate(String className) with unfound class.
572      */

573     public void testInstantiateWithDefaultConstructorAndUnknownClass() throws Exception
574     {
575        try
576        {
577           MBeanServer server = MBeanServerFactory.newMBeanServer();
578           Object o = server.instantiate("foo.Bar");
579           
580           // should not get here
581
fail("Instantiate should have thrown a ReflectionException.");
582        }
583        catch (ReflectionException e)
584        {
585           // this is expected
586
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
587        }
588     }
589     
590     /**
591      * Tests instantiate(String className) with class that doesn't have a default constructor.
592      */

593     public void testInstantiateWithMissingDefaultConstructor() throws Exception
594     {
595        try
596        {
597           MBeanServer server = MBeanServerFactory.newMBeanServer();
598           Object o = server.instantiate("test.compliance.server.support.ConstructorTest6");
599           
600           // should not get here
601
fail("Instantiate should have thrown a ReflectionException.");
602        }
603        catch (ReflectionException e)
604        {
605           // this is expected
606
}
607     }
608     
609     /**
610      * Tests instantiate(String className) with protected (no access) no args constructor.
611      */

612     public void testInstantiateWithInaccessibleNoArgsConstructor() throws Exception
613     {
614        try
615        {
616           MBeanServer server = MBeanServerFactory.newMBeanServer();
617           Object o = server.instantiate("test.compliance.server.support.ConstructorTest7");
618           
619           // should not get here
620
fail("Instantiate should have thrown a ReflectionException.");
621        }
622        catch (ReflectionException e)
623        {
624           // this is expected
625
}
626     }
627
628    /**
629     * Tests instantiate(String className) with null class name. According to
630     * javadoc, should throw RuntimeOperationsException wrapping IllegalArgException.
631     */

632    public void testInstantiateWithNullClassName() throws Exception
633    {
634       try
635       {
636          MBeanServer server = MBeanServerFactory.newMBeanServer();
637          Object o = server.instantiate(null);
638
639          // should not reach here
640
fail("incorrect exception behavior");
641       }
642       catch (RuntimeOperationsException e)
643       {
644          // expected
645

646          // check that it wraps IAE
647
assertTrue(e.getTargetException() instanceof IllegalArgumentException);
648       }
649    }
650
651    /**
652     * Tests instantiate(String className) with empty class name string. should
653     * throw ReflectionException wrapping CNFE.
654     */

655    public void testInstantiateWithEmptyClassName() throws Exception
656    {
657       try
658       {
659          MBeanServer server = MBeanServerFactory.newMBeanServer();
660          Object o = server.instantiate("");
661
662          // should not reach here
663
fail("incorrect exception/classloading behavior");
664       }
665       catch (ReflectionException e)
666       {
667          // expected
668

669          // check that it wraps CNFE
670
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
671       }
672    }
673
674    /**
675     * Tests instantiate(String className, ObjectName loader) with null class name. According to
676     * javadoc, should throw RuntimeOperationsException wrapping IllegalArgException.
677     */

678    public void testInstantiateWithNullClassName2() throws Exception
679    {
680       try
681       {
682          MBeanServer server = MBeanServerFactory.newMBeanServer();
683          Object o = server.instantiate(null, null);
684
685          // should not reach here
686
fail("incorrect exception behavior");
687       }
688       catch (RuntimeOperationsException e)
689       {
690          // expected
691

692          // check that it wraps IAE
693
assertTrue(e.getTargetException() instanceof IllegalArgumentException);
694       }
695    }
696
697    /**
698     * Tests instantiate(String className, ObjectName loader) with empty class name string. should
699     * throw ReflectionException wrapping CNFE.
700     */

701    public void testInstantiateWithEmptyClassName2() throws Exception
702    {
703       try
704       {
705          MBeanServer server = MBeanServerFactory.newMBeanServer();
706          Object o = server.instantiate("", null);
707
708          // should not reach here
709
fail("incorrect exception/classloading behavior");
710       }
711       catch (ReflectionException e)
712       {
713          // expected
714

715          // check that it wraps CNFE
716
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
717       }
718    }
719
720    /**
721     * Tests instantiate(String className, Object[] args, String[] sign) with null
722     * class name. According to javadoc, should throw RuntimeOperationsException
723     * wrapping IllegalArgException.
724     */

725    public void testInstantiateWithNullClassName3() throws Exception
726    {
727       try
728       {
729          MBeanServer server = MBeanServerFactory.newMBeanServer();
730          Object o = server.instantiate(null, null, null);
731
732          // should not reach here
733
fail("incorrect exception behavior");
734       }
735       catch (RuntimeOperationsException e)
736       {
737          // expected
738

739          // check that it wraps IAE
740
assertTrue(e.getTargetException() instanceof IllegalArgumentException);
741       }
742    }
743
744    /**
745     * Tests instantiate(String className, Object[] args, String[] sign) with
746     * empty class name string. should throw ReflectionException wrapping CNFE.
747     */

748    public void testInstantiateWithEmptyClassName3() throws Exception
749    {
750       try
751       {
752          MBeanServer server = MBeanServerFactory.newMBeanServer();
753          Object o = server.instantiate("", null, null);
754
755          // should not reach here
756
fail("incorrect exception/classloading behavior");
757       }
758       catch (ReflectionException e)
759       {
760          // expected
761

762          // check that it wraps CNFE
763
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
764       }
765    }
766
767    /**
768     * Tests instantiate(String className, ObjectName loader, Object[] args, String[] sign)
769     * with null class name. According to javadoc, should throw RuntimeOperationsException
770     * wrapping IllegalArgException.
771     */

772    public void testInstantiateWithNullClassName4() throws Exception
773    {
774       try
775       {
776          MBeanServer server = MBeanServerFactory.newMBeanServer();
777          Object o = server.instantiate(null, null, null, null);
778
779          // should not reach here
780
fail("incorrect exception behavior");
781       }
782       catch (RuntimeOperationsException e)
783       {
784          // expected
785

786          // check that it wraps IAE
787
assertTrue(e.getTargetException() instanceof IllegalArgumentException);
788       }
789    }
790
791    /**
792     * Tests instantiate(String className, ObjectName loader, Object[] args, String[] sign)
793     * with empty class name string. should throw ReflectionException wrapping CNFE.
794     */

795    public void testInstantiateWithEmptyClassName4() throws Exception
796    {
797       try
798       {
799          MBeanServer server = MBeanServerFactory.newMBeanServer();
800          Object o = server.instantiate("", null, null, null);
801
802          // should not reach here
803
fail("incorrect exception/classloading behavior");
804       }
805       catch (ReflectionException e)
806       {
807          // expected
808

809          // check that it wraps CNFE
810
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
811       }
812    }
813     
814    /**
815     * Tests instantiate(String className) classloading behaviour. According to
816     * javadoc, DLR should be used to instantiate the class
817     */

818    public void testInstantiateWithDefaultLoaderRepository() throws Exception
819    {
820       // NOTE:
821
// the urls used here are relative to the location of the build.xml
822

823       MBeanServer server = MBeanServerFactory.newMBeanServer();
824       MLet mlet = new MLet();
825       ObjectName name = new ObjectName(":test=test");
826       
827       // mlet cl to DLR
828
try
829       {
830          mlet.addURL("file:./output/etc/test/compliance/server/Test.jar");
831          server.registerMBean(mlet, name);
832       
833          Object o = server.instantiate("test.compliance.server.support.AClass");
834       }
835       finally
836       {
837          try
838          {
839             server.unregisterMBean(name);
840          }
841          catch (Exception ignored) {}
842       }
843       
844       //assertTrue(o.getClass().getClassLoader().equals(mlet));
845
}
846    
847    
848    /**
849     * Tests instantiate(String className, ObjectName loader) classloading behaviour. According to
850     * javadoc, DLR should be used to instantiate the class. This should fail as
851     * the MLet MBean is never added to the agent and therefore not in the DLR.
852     */

853    public void testInstantiateWithDefaultLoaderRepository2() throws Exception
854    {
855       try
856       {
857          // NOTE:
858
// the urls used here are relative to the location of the build.xml
859

860          MBeanServer server = MBeanServerFactory.newMBeanServer();
861          MLet mlet = new MLet();
862       
863          // mlet cl to DLR
864
mlet.addURL("file:./output/etc/test/compliance/server/Test.jar");
865          //server.registerMBean(mlet, new ObjectName(":test=test"));
866

867          Object o = server.instantiate("test.compliance.server.support.AClass");
868       
869 //
870
// FIXME: this test won't work until we have means to reset the JVM wide
871
// loader repository
872
//
873

874          // should not reach here
875
//fail("incorrect classloading behavior");
876
//assertTrue(o.getClass().getClassLoader().equals(mlet));
877
}
878       catch (ReflectionException e)
879       {
880          // expected
881

882          // check that it wraps CNFE
883
assertTrue(e.getTargetException() instanceof ClassNotFoundException);
884       }
885    }
886    
887     // MBeanServer registerMBean ------------------------------------
888

889     /**
890      * Tests registering with null object name.
891      */

892     public void testRegisterNullObjectName() throws Exception
893     {
894        boolean caught = false;
895        try
896        {
897           MBeanServer server = MBeanServerFactory.newMBeanServer();
898           server.registerMBean(new Test(), null);
899        }
900        catch (RuntimeOperationsException e)
901        {
902           if (e.getTargetException() instanceof IllegalArgumentException)
903              caught = true;
904           else
905              fail("Wrong wrapped exception " + e.getTargetException());
906        }
907        if (caught == false)
908           fail("Allowed to register with a null object name");
909     }
910     
911     /**
912      * Tests registering with a pattern object name.
913      */

914     public void testRegisterPatternObjectName() throws Exception
915     {
916        boolean caught = false;
917        try
918        {
919           MBeanServer server = MBeanServerFactory.newMBeanServer();
920           server.registerMBean(new Test(), new ObjectName("Domai?:type=test"));
921        }
922        catch (RuntimeOperationsException e)
923        {
924           if (e.getTargetException() instanceof IllegalArgumentException)
925              caught = true;
926           else
927              fail("Wrong wrapped exception " + e.getTargetException());
928        }
929        if (caught == false)
930           fail("Allowed to register with a pattern object name");
931     }
932     
933     /**
934      * Tests registering into JMImplementation
935      */

936     public void testRegisterJMImplementationObjectName() throws Exception
937     {
938        boolean caught = false;
939        try
940        {
941           MBeanServer server = MBeanServerFactory.newMBeanServer();
942           server.registerMBean(new Test(), new ObjectName("JMImplementation:type=test"));
943        }
944        catch (RuntimeOperationsException e)
945        {
946           if (e.getTargetException() instanceof IllegalArgumentException)
947              caught = true;
948           else
949              fail("Wrong wrapped exception " + e.getTargetException());
950        }
951        if (caught == false)
952           fail("Allowed to register into JMImplementation");
953     }
954     
955     /**
956      * Tests registering into JMImplementation using default domain
957      */

958     public void testRegisterJMImplementationDefaultDomainObjectName() throws Exception
959     {
960        boolean caught = false;
961        try
962        {
963           MBeanServer server = MBeanServerFactory.newMBeanServer("JMImplementation");
964           server.registerMBean(new Test(), new ObjectName(":type=test"));
965        }
966        catch (RuntimeOperationsException e)
967        {
968           if (e.getTargetException() instanceof IllegalArgumentException)
969              caught = true;
970           else
971              fail("Wrong wrapped exception " + e.getTargetException());
972        }
973        if (caught == false)
974           fail("Allowed to register into JMImplementation");
975     }
976     
977     
978    /**
979     * Tests register for an MBean that throws unchecked exception from preRegister()
980     */

981    public void testRegisterMBeanOnExceptionFromPreRegister() throws Exception
982    {
983       MBeanServer server = MBeanServerFactory.newMBeanServer();
984       ObjectName name = new ObjectName("test:foo=bar");
985     
986       try
987       {
988          server.registerMBean(new Test2(), name);
989          
990          // should not reach here
991
fail("Test2 registered despite of throwing an exception from the preRegister() method.");
992       }
993       catch (MBeanRegistrationException e)
994       {
995          // expected
996
assertTrue(!server.isRegistered(name));
997          assertTrue(e.getTargetException() instanceof java.lang.RuntimeException);
998       }
999       catch (RuntimeMBeanException e)
1000      {
1001         fail("FAILS IN RI: RuntimeMBeanException instead of MBeanRegistrationException?");
1002      }
1003    }
1004    
1005    /**
1006     * Tests register for an MBean that throws checked exception from preRegister()
1007     */

1008    public void testRegisterMBeanOnExceptionFromPreRegister2() throws Exception
1009    {
1010      MBeanServer server = MBeanServerFactory.newMBeanServer();
1011      ObjectName name = new ObjectName("test:foo=bar");
1012      
1013      try
1014      {
1015         server.registerMBean(new Test3(), name);
1016         
1017         // should not reach here
1018
fail("Test3 registered despite of throwin an exception from the preRegister() method");
1019      }
1020      catch (MBeanRegistrationException e)
1021      {
1022         // expected
1023
assertTrue(!server.isRegistered(name));
1024         assertTrue(e.getTargetException() instanceof MyScreamingException);
1025      }
1026    }
1027    
1028    /**
1029     * Tests register for an MBean that throws an MBeanRegistrationException from
1030     * preRegister() method.
1031     */

1032    public void testRegisterMBeanOnExceptionFromPreRegister3() throws Exception
1033    {
1034       MBeanServer server = MBeanServerFactory.newMBeanServer();
1035       ObjectName name = new ObjectName("test:foo=bar");
1036       
1037       try
1038       {
1039          server.registerMBean(new Test4(), name);
1040          
1041          // should not reach here
1042
fail("Test4 registered despite of throwing an exception from the preRegister() method.");
1043       }
1044       catch (MBeanRegistrationException e)
1045       {
1046          // expected
1047
assertTrue(!server.isRegistered(name));
1048          assertTrue(e.getTargetException() instanceof MyScreamingException);
1049       }
1050    }
1051    
1052    
1053    // MBeanServer unregisterMBean ----------------------------------
1054

1055    /**
1056     * Tests unregister the delegate.
1057     */

1058    public void testUnregisterDelegate() throws Exception
1059    {
1060       boolean caught = false;
1061       try
1062       {
1063          MBeanServer server = MBeanServerFactory.newMBeanServer();
1064          server.unregisterMBean(new ObjectName("JMImplementation:type=MBeanServerDelegate"));
1065       }
1066       // REVIEW: This exception type isn't specified, but it is logical
1067
// and agrees with the RI.
1068
// JPL: agreed
1069
catch (RuntimeOperationsException e)
1070       {
1071          caught = true;
1072       }
1073       if (caught == false)
1074          fail("Allowed to unregister the delegate");
1075    }
1076    
1077    /**
1078     * Tests basic register/unregister
1079     */

1080    public void testBasicUnregister() throws Exception
1081    {
1082       MBeanServer server = MBeanServerFactory.newMBeanServer();
1083       ObjectName name = new ObjectName("test:foo=bar");
1084       
1085       server.registerMBean(new Test(), name);
1086       server.unregisterMBean(name);
1087    }
1088    
1089    /**
1090     * Tests unregister with default domain name
1091     */

1092    public void testUnregisterWithDefaultDomainName() throws Exception
1093    {
1094       try
1095       {
1096          MBeanServer server = MBeanServerFactory.newMBeanServer();
1097          ObjectName name = new ObjectName(":foo=bar");
1098          
1099          server.registerMBean(new Test(), name);
1100          server.unregisterMBean(name);
1101       
1102       }
1103       catch (InstanceNotFoundException e)
1104       {
1105          // FAILS IN RI: RI throws InstanceNotFoundException if you try to
1106
// unregister with implicit default domain name
1107
fail("FAILS IN RI: RI throws InstanceNotFoundException when an existing MBean is unregistered with an implicit default domain name.");
1108       }
1109    }
1110    
1111    /**
1112     * Tests unregister with default domain name gotten from ObjectInstance at registration time.
1113     */

1114     public void testUnregisterWithObjectNameFromRegistration() throws Exception
1115     {
1116        try
1117        {
1118           MBeanServer server = MBeanServerFactory.newMBeanServer();
1119           ObjectName name = new ObjectName(":foo=bar");
1120           
1121           ObjectInstance oi = server.registerMBean(new Test(), name);
1122           name = oi.getObjectName();
1123           
1124           server.unregisterMBean(name);
1125        
1126        }
1127        catch (InstanceNotFoundException e)
1128        {
1129           // FAILS IN RI: RI throws InstanceNotFoundExceptin if you try yo
1130
// unregister with implicit default domain name
1131
fail("FAILS IN RI: RI throws InstanceNotFoundException when an existing MBean is unregistered with an implicit default domain name retrieved from the ObjectInstance returned at registration time.");
1132        }
1133     }
1134    
1135   /**
1136    * Tests unregister for an MBean that prevents unregistration by throwing an
1137    * unchecked exception from its preDeregister() method.
1138    */

1139   public void testUnregisterMBeanOnExceptionFromPreDeregister() throws Exception
1140   {
1141      MBeanServer server = MBeanServerFactory.newMBeanServer();
1142      ObjectName name = new ObjectName("test:foo=bar");
1143    
1144      server.registerMBean(new LockedTest(), name);
1145
1146      try
1147      {
1148         server.unregisterMBean(name);
1149         
1150         // should not reach here
1151
fail("LockedTest unregistered despite of throwing an exception from the preDeregister() method.");
1152      }
1153      catch (MBeanRegistrationException e)
1154      {
1155         // expected, LockedTest should prevent unregistration
1156
assertTrue(server.isRegistered(name));
1157         assertTrue(e.getTargetException() instanceof java.lang.RuntimeException);
1158      }
1159      catch (RuntimeMBeanException e)
1160      {
1161         // FAILS IN RI: according to spec (v1.0, p. 117) any exception thrown from the
1162
// preDeregister() method is wrapped in MBeanRegistrationException by the agent.
1163
fail("FAILS IN RI: spec v1.0: any exception thrown from MBean's preDeregister() method should be wrapped in an MBeanRegistrationException by the agent.");
1164      }
1165    }
1166    
1167    /**
1168     * Tests unregister for an MBean that prevents unregistration by throwing a
1169     * checked exception from its preDeregister() method.
1170     */

1171    public void testUnregisterMBeanOnExceptionFromPreDeregister2() throws Exception
1172    {
1173      MBeanServer server = MBeanServerFactory.newMBeanServer();
1174      ObjectName name = new ObjectName("test:foo=bar");
1175      
1176      server.registerMBean(new LockedTest2(), name);
1177      
1178      try
1179      {
1180         
1181         server.unregisterMBean(name);
1182       
1183         // should not reach here
1184
fail("LockedTest2 unregistered despite of throwin an exception from the preDeregister() method");
1185      }
1186      catch (MBeanRegistrationException e)
1187      {
1188         // expected
1189
assertTrue(server.isRegistered(name));
1190         assertTrue(e.getTargetException() instanceof MyScreamingException);
1191      }
1192    }
1193    
1194    /**
1195     * Tests unregister for an MBean that prevents unregistration by throwing a
1196     * MBeanRegistrationException from its preDeregister() method. This should
1197     * be rethrown by the agent as-is, and not wrapped into another MBeanRegistrationException.
1198     */

1199    public void testUnregisterMBeanOnExceptionFromPreDeregister3() throws Exception
1200    {
1201       MBeanServer server = MBeanServerFactory.newMBeanServer();
1202       ObjectName name = new ObjectName("test:foo=bar");
1203       
1204       server.registerMBean(new LockedTest3(), name);
1205       
1206       try
1207       {
1208          server.unregisterMBean(name);
1209          
1210          // should not reach here
1211
fail("LockedTest3 unregistered despite of throwing an exception from the preDeregister() method.");
1212       }
1213       catch (MBeanRegistrationException e)
1214       {
1215          // expected
1216
assertTrue(server.isRegistered(name));
1217          assertTrue(e.getTargetException() instanceof MyScreamingException);
1218       }
1219    }
1220    
1221   // MBeanServer NotificationListener Plain -----------------------
1222

1223   /**
1224    * Tests basic listener registration to server delegate
1225    */

1226   public synchronized void testAddNotificationListenerToDelegate() throws Exception
1227   {
1228      MBeanServer server = MBeanServerFactory.newMBeanServer();
1229      
1230      class MyNotificationListener implements NotificationListener {
1231
1232         int notificationCount = 0;
1233         
1234         public void handleNotification(Notification notification, Object handback)
1235         {
1236            try
1237            {
1238               notificationCount++;
1239
1240               assertTrue(handback instanceof String);
1241               assertTrue(handback.equals("MyHandback"));
1242               assertTrue(notification.getSource().equals(new ObjectName("JMImplementation:type=MBeanServerDelegate")));
1243            }
1244            catch (Exception e)
1245            {
1246               fail("Unexpected error: " + e.toString());
1247            }
1248         }
1249      }
1250      
1251      MyNotificationListener listener = new MyNotificationListener();
1252      
1253      NotificationFilterSupport filter = new NotificationFilterSupport();
1254      filter.enableType(MBeanServerNotification.REGISTRATION_NOTIFICATION);
1255      
1256      server.addNotificationListener(
1257            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1258            listener, filter, "MyHandback"
1259      );
1260    
1261      // force notification
1262
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1263    
1264      assertTrue(listener.notificationCount == 1);
1265   }
1266    
1267   /**
1268    * Tests multiple listeners with different handbacks
1269    */

1270   public synchronized void testAddMultipleListeners()
1271      throws Exception
1272   {
1273      MBeanServer server = MBeanServerFactory.newMBeanServer();
1274      
1275      class MyNotificationListener implements NotificationListener
1276      {
1277         Object handback;
1278         int result = 0;
1279         public MyNotificationListener(Object handback)
1280         {
1281            this.handback = handback;
1282         }
1283         public void handleNotification(Notification notification, Object handback)
1284         {
1285            result++;
1286            assertEquals(this.handback, handback);
1287            result++;
1288         }
1289      }
1290      
1291      MyNotificationListener listener1 = new MyNotificationListener("handback1");
1292      MyNotificationListener listener2 = new MyNotificationListener("handback2");
1293      
1294      server.addNotificationListener(
1295            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1296            listener1, null, "handback1"
1297      );
1298      server.addNotificationListener(
1299            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1300            listener2, null, "handback2"
1301      );
1302    
1303      // force notification
1304
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1305
1306      assertTrue(listener1.result == 2);
1307      assertTrue(listener2.result == 2);
1308   }
1309    
1310   /**
1311    * Tests one listener multiple handbacks
1312    */

1313   public synchronized void testAddListenerMultipleHandbacks()
1314      throws Exception
1315   {
1316      MBeanServer server = MBeanServerFactory.newMBeanServer();
1317      
1318      class MyNotificationListener implements NotificationListener
1319      {
1320         boolean result1 = false;
1321         boolean result2 = false;
1322         public void handleNotification(Notification notification, Object handback)
1323         {
1324            if (handback.equals("handback1"))
1325               result1 = true;
1326            else if (handback.equals("handback2"))
1327               result2 = true;
1328            else
1329               fail("Unexpected handback: " + handback);
1330         }
1331      }
1332      
1333      MyNotificationListener listener = new MyNotificationListener();
1334      
1335      server.addNotificationListener(
1336            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1337            listener, null, "handback1"
1338      );
1339      server.addNotificationListener(
1340            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1341            listener, null, "handback2"
1342      );
1343    
1344      // force notification
1345
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1346
1347      assertTrue(listener.result1);
1348      assertTrue(listener.result2);
1349   }
1350    
1351   /**
1352    * Tests removing a notification listener including multiple handbacks
1353    */

1354   public synchronized void testRemoveListener()
1355      throws Exception
1356   {
1357      MBeanServer server = MBeanServerFactory.newMBeanServer();
1358      
1359      class MyNotificationListener implements NotificationListener
1360      {
1361         Object handback;
1362         int result = 0;
1363         public MyNotificationListener(Object handback)
1364         {
1365            this.handback = handback;
1366         }
1367         public void handleNotification(Notification notification, Object handback)
1368         {
1369            result++;
1370            assertEquals(this.handback, handback);
1371            result++;
1372         }
1373      }
1374      
1375      class MyOtherNotificationListener implements NotificationListener
1376      {
1377         boolean result1 = false;
1378         boolean result2 = false;
1379         public void handleNotification(Notification notification, Object handback)
1380         {
1381            if (handback.equals("handback1"))
1382               result1 = true;
1383            else if (handback.equals("handback2"))
1384               result2 = true;
1385            else
1386               fail("Unexpected handback: " + handback);
1387         }
1388      }
1389      
1390      MyNotificationListener listener1 = new MyNotificationListener("handback1");
1391      MyOtherNotificationListener listener2 = new MyOtherNotificationListener();
1392      
1393      server.addNotificationListener(
1394            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1395            listener1, null, "handback1"
1396      );
1397      server.addNotificationListener(
1398            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1399            listener2, null, "handback2"
1400      );
1401      server.addNotificationListener(
1402            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1403            listener2, null, "handback3"
1404      );
1405      server.removeNotificationListener(
1406            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1407            listener2
1408      );
1409    
1410      // force notification
1411
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1412
1413      assertTrue(listener1.result == 2);
1414      assertTrue(listener2.result1 == false);
1415      assertTrue(listener2.result2 == false);
1416   }
1417        
1418   /**
1419    * Tests removing a notification listener triplet
1420    */

1421   public synchronized void testRemoveTriplet()
1422      throws Exception
1423   {
1424      MBeanServer server = MBeanServerFactory.newMBeanServer();
1425      
1426      class MyNotificationListener implements NotificationListener
1427      {
1428         Object handback;
1429         int result = 0;
1430         public MyNotificationListener(Object handback)
1431         {
1432            this.handback = handback;
1433         }
1434         public void handleNotification(Notification notification, Object handback)
1435         {
1436            result++;
1437            assertEquals(this.handback, handback);
1438            result++;
1439         }
1440      }
1441      
1442      MyNotificationListener listener1 = new MyNotificationListener("handback1");
1443      MyNotificationListener listener2 = new MyNotificationListener("handback2");
1444      
1445      server.addNotificationListener(
1446            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1447            listener1, null, "handback1"
1448      );
1449      server.addNotificationListener(
1450            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1451            listener2, null, "handback2"
1452      );
1453      server.addNotificationListener(
1454            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1455            listener2, null, "handback3"
1456      );
1457      server.removeNotificationListener(
1458            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1459            listener2, null, "handback3"
1460      );
1461    
1462      // force notification
1463
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1464
1465      assertTrue(listener1.result == 2);
1466      assertTrue(listener1.result == 2);
1467   }
1468
1469   /**
1470    * Tests removing a broadcaster
1471    */

1472   public synchronized void testRemoveBroadcaster()
1473      throws Exception
1474   {
1475      MBeanServer server = MBeanServerFactory.newMBeanServer();
1476      
1477      class MyNotificationListener implements NotificationListener
1478      {
1479         long result = 0;
1480         public MyNotificationListener()
1481         {
1482         }
1483         public void handleNotification(Notification notification, Object handback)
1484         {
1485            result = notification.getSequenceNumber();
1486         }
1487      }
1488
1489      // Register the broadcaster
1490
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1491      Broadcaster broadcaster = new Broadcaster();
1492      server.registerMBean(broadcaster, broadcasterName);
1493      
1494      // Add the listener
1495
MyNotificationListener listener = new MyNotificationListener();
1496      server.addNotificationListener(broadcasterName, listener, null, null);
1497
1498      // Test we get a notification
1499
broadcaster.doSomething();
1500      assertEquals(1, listener.result);
1501
1502      // Remove the broadcaster
1503
server.unregisterMBean(broadcasterName);
1504      
1505      // This notification shouldn't work
1506
broadcaster.doSomething();
1507      try
1508      {
1509         assertEquals(1, listener.result);
1510      }
1511      catch (AssertionFailedError e)
1512      {
1513         fail("FAILS IN RI: Removing a notification broadcaster does not " +
1514              "remove the listeners registered against the object name.");
1515      }
1516   }
1517    
1518   /**
1519    * Tests adding the listener to different broadcasters
1520    */

1521   public synchronized void testAddListenerToTwoBroadcasters()
1522      throws Exception
1523   {
1524      MBeanServer server = MBeanServerFactory.newMBeanServer();
1525      
1526      class MyNotificationListener implements NotificationListener
1527      {
1528         long result = 0;
1529         public MyNotificationListener()
1530         {
1531         }
1532         public void handleNotification(Notification notification, Object handback)
1533         {
1534            result++;
1535         }
1536      }
1537
1538      // Register the broadcaster
1539
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1540      Broadcaster broadcaster = new Broadcaster();
1541      server.registerMBean(broadcaster, broadcasterName);
1542      
1543      // Add the listener to the broadcaster
1544
MyNotificationListener listener = new MyNotificationListener();
1545      server.addNotificationListener(broadcasterName, listener, null, null);
1546      
1547      // Add the listener to the delegate
1548
server.addNotificationListener(
1549            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1550            listener, null, null
1551      );
1552
1553      // Test we get a notification from the broadcaster
1554
broadcaster.doSomething();
1555      assertEquals(1, listener.result);
1556
1557      // Test we get a notification from the delegate
1558
server.registerMBean(new Test(), new ObjectName("Test:foo=bar"));
1559      assertEquals(2, listener.result);
1560
1561      // Remove the broadcaster
1562
server.unregisterMBean(broadcasterName);
1563      assertEquals(3, listener.result);
1564
1565      // Make sure we are still listening to the delegate
1566
server.unregisterMBean(new ObjectName("Test:foo=bar"));
1567      assertEquals(4, listener.result);
1568   }
1569    
1570   /**
1571    * Tests adding the listener to different broadcasters but remove one
1572    */

1573   public synchronized void testAddListenerToTwoBroadcastersRemoveOne()
1574      throws Exception
1575   {
1576      MBeanServer server = MBeanServerFactory.newMBeanServer();
1577      
1578      class MyNotificationListener implements NotificationListener
1579      {
1580         long result = 0;
1581         public MyNotificationListener()
1582         {
1583         }
1584         public void handleNotification(Notification notification, Object handback)
1585         {
1586            result++;
1587         }
1588      }
1589
1590      // Register the broadcaster
1591
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1592      Broadcaster broadcaster = new Broadcaster();
1593      server.registerMBean(broadcaster, broadcasterName);
1594      
1595      // Add the listener to the broadcaster
1596
MyNotificationListener listener = new MyNotificationListener();
1597      server.addNotificationListener(broadcasterName, listener, null, null);
1598      
1599      // Add the listener to the delegate
1600
server.addNotificationListener(
1601            new ObjectName("JMImplementation:type=MBeanServerDelegate"),
1602            listener, null, null
1603      );
1604
1605      // Remove ourselves from the broadcaster
1606
server.removeNotificationListener(broadcasterName, listener);
1607
1608      // Test we get a notification from the broadcaster
1609
broadcaster.doSomething();
1610      assertEquals(0, listener.result);
1611
1612      // Test we get a notification from the delegate
1613
server.registerMBean(new Test(), new ObjectName("Test:foo=bar"));
1614      assertEquals(1, listener.result);
1615   }
1616    
1617   // MBeanServer NotificationListener Object Name -----------------
1618

1619   /**
1620    * Tests basic listener registration to server delegate
1621    */

1622   public synchronized void testaddMBeanToDelegate() throws Exception
1623   {
1624      MBeanServer server = MBeanServerFactory.newMBeanServer();
1625      
1626      MBeanListener listener = new MBeanListener();
1627      ObjectName listenerName = new ObjectName("test:type=listener");
1628      server.registerMBean(listener, listenerName);
1629      
1630      NotificationFilterSupport filter = new NotificationFilterSupport();
1631      filter.enableType(MBeanServerNotification.REGISTRATION_NOTIFICATION);
1632      
1633      ObjectName delegateName =
1634         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1635      server.addNotificationListener(delegateName, listenerName, filter, "MyHandback");
1636    
1637      // force notification
1638
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1639    
1640      assertTrue(listener.count == 1);
1641      assertTrue(listener.source.equals(delegateName));
1642      assertTrue(listener.handback.equals("MyHandback"));
1643   }
1644    
1645   /**
1646    * Tests multiple listeners with different handbacks
1647    */

1648   public synchronized void testAddMBeanMultipleListeners()
1649      throws Exception
1650   {
1651      MBeanServer server = MBeanServerFactory.newMBeanServer();
1652      
1653      MBeanListener listener1 = new MBeanListener();
1654      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1655      server.registerMBean(listener1, listenerName1);
1656      MBeanListener listener2 = new MBeanListener();
1657      ObjectName listenerName2 = new ObjectName("test:type=listener2");
1658      server.registerMBean(listener2, listenerName2);
1659      
1660      ObjectName delegateName =
1661         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1662      server.addNotificationListener(delegateName, listenerName1, null, "handback1");
1663      server.addNotificationListener(delegateName, listenerName2, null, "handback2");
1664    
1665      // force notification
1666
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1667
1668      assertEquals(1, listener1.count);
1669      assertEquals(listener1.source,delegateName);
1670      assertEquals(listener1.handback,"handback1");
1671      assertEquals(1, listener2.count);
1672      assertEquals(listener2.source,delegateName);
1673      assertEquals(listener2.handback,"handback2");
1674   }
1675    
1676   /**
1677    * Tests one listener multiple handbacks
1678    */

1679   public synchronized void testAddMBeanListenerMultipleHandbacks()
1680      throws Exception
1681   {
1682      MBeanServer server = MBeanServerFactory.newMBeanServer();
1683      
1684      MBeanListener listener = new MBeanListener("handback1", "handback2");
1685      ObjectName listenerName = new ObjectName("test:type=listener");
1686      server.registerMBean(listener, listenerName);
1687      
1688      ObjectName delegateName =
1689         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1690      server.addNotificationListener(delegateName, listenerName, null, "handback1");
1691      server.addNotificationListener(delegateName, listenerName, null, "handback2");
1692    
1693      // force notification
1694
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1695
1696      assertTrue(listener.count1 == 1);
1697      assertEquals(listener.source1,delegateName);
1698      assertEquals(listener.handback1,"handback1");
1699      assertTrue(listener.count2 == 1);
1700      assertEquals(listener.source2,delegateName);
1701      assertEquals(listener.handback2,"handback2");
1702   }
1703    
1704   /**
1705    * Tests removing a notification listener including multiple handbacks
1706    */

1707   public synchronized void testMBeanRemoveListener()
1708      throws Exception
1709   {
1710      MBeanServer server = MBeanServerFactory.newMBeanServer();
1711
1712      MBeanListener listener1 = new MBeanListener();
1713      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1714      server.registerMBean(listener1, listenerName1);
1715      MBeanListener listener2 = new MBeanListener("handback2", "handback3");
1716      ObjectName listenerName2 = new ObjectName("test:type=listener2");
1717      server.registerMBean(listener2, listenerName2);
1718      
1719      ObjectName delegateName =
1720         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1721      server.addNotificationListener(delegateName, listenerName1, null, "handback1");
1722      server.addNotificationListener(delegateName, listenerName2, null, "handback2");
1723      server.addNotificationListener(delegateName, listenerName2, null, "handback3");
1724      server.removeNotificationListener(delegateName, listenerName2);
1725    
1726      // force notification
1727
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1728      assertTrue("Listener1 should get a notification", listener1.count == 1);
1729      assertTrue("Source should be the delegate", listener1.source.equals(delegateName));
1730      assertTrue("Listener1 should get handback1", listener1.handback.equals("handback1"));
1731      assertTrue("Listener2 should have no notiifcation", listener2.count == 0);
1732      assertTrue("Listener2 should have no notiifcation for handback2", listener2.count1 == 0);
1733      assertTrue("Listener2 should have no notiifcation for handback3", listener2.count2 == 0);
1734   }
1735    
1736   /**
1737    * Tests removing a notification listener triple
1738    */

1739   public synchronized void testMBeanRemoveTriplet()
1740      throws Exception
1741   {
1742      MBeanServer server = MBeanServerFactory.newMBeanServer();
1743
1744      MBeanListener listener1 = new MBeanListener();
1745      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1746      server.registerMBean(listener1, listenerName1);
1747      MBeanListener listener2 = new MBeanListener("handback2", "handback3");
1748      ObjectName listenerName2 = new ObjectName("test:type=listener2");
1749      server.registerMBean(listener2, listenerName2);
1750      
1751      ObjectName delegateName =
1752         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1753      server.addNotificationListener(delegateName, listenerName1, null, "handback1");
1754      server.addNotificationListener(delegateName, listenerName2, null, "handback2");
1755      server.addNotificationListener(delegateName, listenerName2, null, "handback3");
1756      server.removeNotificationListener(delegateName, listenerName2, null, "handback3");
1757    
1758      // force notification
1759
server.registerMBean(new Test(), new ObjectName(":foo=bar"));
1760      assertTrue("Listener1 should get a notification", listener1.count == 1);
1761      assertTrue("Source should be the delegate", listener1.source.equals(delegateName));
1762      assertTrue("Listener1 should get handback1", listener1.handback.equals("handback1"));
1763      assertTrue("Listener2 should get a notification", listener2.count1 == 1);
1764      assertTrue("Source should be the delegate", listener2.source1.equals(delegateName));
1765      assertTrue("Listener2 should get handback2", listener2.handback1.equals("handback2"));
1766      assertTrue("Listener2 should have no notiifcation for handback3", listener2.count2 == 0);
1767   }
1768    
1769   /**
1770    * Tests MBeanRedeploy notification
1771    */

1772   public synchronized void testMBeanRedeployNotification()
1773      throws Exception
1774   {
1775      MBeanServer server = MBeanServerFactory.newMBeanServer();
1776
1777      MBeanListener listener = new MBeanListener();
1778      ObjectName listenerName = new ObjectName("test:type=listener");
1779      server.registerMBean(listener, listenerName);
1780
1781      ObjectName broadcasterName = new ObjectName("test:type=Broadcaster");
1782      server.registerMBean(new Broadcaster(), broadcasterName);
1783      
1784      server.addNotificationListener(broadcasterName, listenerName, null, "handback1");
1785      server.removeNotificationListener(broadcasterName, listenerName, null, "handback1");
1786      server.unregisterMBean(broadcasterName);
1787
1788      Broadcaster broadcaster = new Broadcaster();
1789      server.registerMBean(broadcaster, broadcasterName);
1790      server.addNotificationListener(broadcasterName, listenerName, null, "handback2");
1791    
1792      // force notification
1793
broadcaster.doSomething();
1794      assertTrue("Listener should get a notification", listener.count == 1);
1795      assertTrue("Source should be the broadcaster", listener.source.equals(broadcasterName));
1796      assertTrue("Listener should get handback2", listener.handback.equals("handback2"));
1797   }
1798    
1799   /**
1800    * Tests removing a broadcaster
1801    */

1802   public synchronized void testMBeanRemoveBroadcaster()
1803      throws Exception
1804   {
1805      MBeanServer server = MBeanServerFactory.newMBeanServer();
1806      
1807      MBeanListener listener1 = new MBeanListener();
1808      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1809      server.registerMBean(listener1, listenerName1);
1810
1811      // Register the broadcaster
1812
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1813      Broadcaster broadcaster = new Broadcaster();
1814      server.registerMBean(broadcaster, broadcasterName);
1815      
1816      // Add the listener
1817
server.addNotificationListener(broadcasterName, listenerName1, null, null);
1818
1819      // Test we get a notification
1820
broadcaster.doSomething();
1821      assertEquals(1, listener1.count);
1822      assertEquals(broadcasterName, listener1.source);
1823
1824      // Remove the broadcaster
1825
server.unregisterMBean(broadcasterName);
1826      
1827      // This notification shouldn't work
1828
broadcaster.doSomething();
1829      try
1830      {
1831         assertEquals(1, listener1.count);
1832      }
1833      catch (AssertionFailedError e)
1834      {
1835         fail("FAILS IN RI: Removing a notification broadcaster does not " +
1836              "remove the listeners registered against the object name.");
1837      }
1838   }
1839    
1840   /**
1841    * Tests adding the listener to different broadcasters
1842    */

1843   public synchronized void testAddMBeanListenerToTwoBroadcasters()
1844      throws Exception
1845   {
1846      MBeanServer server = MBeanServerFactory.newMBeanServer();
1847      
1848      MBeanListener listener1 = new MBeanListener();
1849      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1850      server.registerMBean(listener1, listenerName1);
1851
1852      // Register the broadcaster
1853
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1854      Broadcaster broadcaster = new Broadcaster();
1855      server.registerMBean(broadcaster, broadcasterName);
1856      
1857      // Add the listener to the broadcaster
1858
server.addNotificationListener(broadcasterName, listenerName1, null, null);
1859      
1860      // Add the listener to the delegate
1861
ObjectName delegateName =
1862         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1863      server.addNotificationListener(delegateName,listenerName1, null, null);
1864
1865      // Test we get a notification from the broadcaster
1866
broadcaster.doSomething();
1867      assertEquals(1, listener1.count);
1868      assertEquals(broadcasterName, listener1.source);
1869
1870      try
1871      {
1872         // Test we get a notification from the delegate
1873
server.registerMBean(new Test(), new ObjectName("Test:foo=bar"));
1874         assertEquals(2, listener1.count);
1875         assertEquals(delegateName, listener1.source);
1876
1877         // Remove the broadcaster
1878
server.unregisterMBean(broadcasterName);
1879         assertEquals(3, listener1.count);
1880         assertEquals(delegateName, listener1.source);
1881
1882         // Make sure we are still listening to the delegate
1883
server.unregisterMBean(new ObjectName("Test:foo=bar"));
1884         assertEquals(4, listener1.count);
1885         assertEquals(delegateName, listener1.source);
1886      }
1887      catch (AssertionFailedError e)
1888      {
1889         fail("FAILS IN RI: Listener registered with ObjectName in MBeanServer " +
1890              "reports the wrong source for multiple broadcaster.");
1891      }
1892   }
1893    
1894   /**
1895    * Tests adding the listener to different broadcasters but remove one
1896    */

1897   public synchronized void testAddMBeanListenerToTwoBroadcastersRemoveOne()
1898      throws Exception
1899   {
1900      MBeanServer server = MBeanServerFactory.newMBeanServer();
1901      
1902      MBeanListener listener1 = new MBeanListener();
1903      ObjectName listenerName1 = new ObjectName("test:type=listener1");
1904      server.registerMBean(listener1, listenerName1);
1905
1906      // Register the broadcaster
1907
ObjectName broadcasterName = new ObjectName("test:type=broadcaster");
1908      Broadcaster broadcaster = new Broadcaster();
1909      server.registerMBean(broadcaster, broadcasterName);
1910      
1911      // Add the listener to the broadcaster
1912
server.addNotificationListener(broadcasterName, listenerName1, null, null);
1913      
1914      // Add the listener to the delegate
1915
ObjectName delegateName =
1916         new ObjectName("JMImplementation:type=MBeanServerDelegate");
1917      server.addNotificationListener(delegateName,listenerName1, null, null);
1918
1919      // Remove ourselves from the broadcaster
1920
server.removeNotificationListener(broadcasterName, listener1);
1921
1922      // Test we get a notification from the broadcaster
1923
broadcaster.doSomething();
1924      assertEquals(0, listener1.count);
1925
1926      // Test we get a notification from the delegate
1927
server.registerMBean(new Test(), new ObjectName("Test:foo=bar"));
1928      assertEquals(1, listener1.count);
1929      try
1930      {
1931         assertEquals(delegateName, listener1.source);
1932      }
1933      catch (AssertionFailedError e)
1934      {
1935         fail("FAILS IN RI: Listener registered with ObjectName in MBeanServer " +
1936              "reports the wrong source for multiple broadcaster, " +
1937              "even when the broadcaster it reports has been removed.");
1938      }
1939   }
1940    
1941   public void testGetDomains()
1942      throws Exception
1943   {
1944      MBeanServer server = MBeanServerFactory.newMBeanServer();
1945
1946      assertTrue("Only one domain at the start", server.getDomains().length == 1);
1947      assertEquals(server.getDomains()[0], "JMImplementation");
1948
1949      server.registerMBean(new Test(), new ObjectName("Domain1:test=test1"));
1950      server.registerMBean(new Test(), new ObjectName("Domain1:test=test2"));
1951      server.registerMBean(new Test(), new ObjectName("Domain2:test=test1"));
1952      server.registerMBean(new Test(), new ObjectName("Domain3:test=test1"));
1953
1954      assertTrue("Now four domains", server.getDomains().length == 4);
1955      List domains = Arrays.asList(server.getDomains());
1956      assertTrue("server has JMImplementation", domains.contains("JMImplementation"));
1957      assertTrue("server has Domain1", domains.contains("Domain1"));
1958      assertTrue("server has Domain2", domains.contains("Domain2"));
1959      assertTrue("server has Domain3", domains.contains("Domain3"));
1960
1961      server.unregisterMBean(new ObjectName("Domain3:test=test1"));
1962
1963      assertTrue("Now three domains", server.getDomains().length == 3);
1964      domains = Arrays.asList(server.getDomains());
1965      assertTrue("server has JMImplementation", domains.contains("JMImplementation"));
1966      assertTrue("server has Domain1", domains.contains("Domain1"));
1967      assertTrue("server has Domain2", domains.contains("Domain2"));
1968      assertTrue("server no longer has Domain3", domains.contains("Domain3") == false);
1969
1970      server.unregisterMBean(new ObjectName("Domain1:test=test1"));
1971
1972      assertTrue("Still three domains", server.getDomains().length == 3);
1973      domains = Arrays.asList(server.getDomains());
1974      assertTrue("server has JMImplementation", domains.contains("JMImplementation"));
1975      assertTrue("server still has Domain1", domains.contains("Domain1"));
1976      assertTrue("server has Domain2", domains.contains("Domain2"));
1977      assertTrue("server no longer has Domain3", domains.contains("Domain3") == false);
1978   }
1979
1980   public void testIsInstanceOf()
1981      throws Exception
1982   {
1983      MBeanServer server = MBeanServerFactory.newMBeanServer();
1984      ObjectName baseName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=Base");
1985      ObjectName derivedName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=Derived");
1986      ObjectName unrelatedName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=Unrelated");
1987
1988      server.registerMBean(new Base(), baseName);
1989      server.registerMBean(new Derived(), derivedName);
1990      server.registerMBean(new Unrelated(), unrelatedName);
1991
1992      assertTrue("Base is an instance Object",
1993         server.isInstanceOf(baseName, Object.class.getName()));
1994      assertTrue("Base is an instance BaseMBean",
1995         server.isInstanceOf(baseName, BaseMBean.class.getName()));
1996      assertTrue("Base is an instance Base",
1997         server.isInstanceOf(baseName, Base.class.getName()));
1998      assertTrue("Derived is an instance Object",
1999         server.isInstanceOf(derivedName, Object.class.getName()));
2000      assertTrue("Derived is an instance BaseMBean",
2001         server.isInstanceOf(derivedName, BaseMBean.class.getName()));
2002      assertTrue("Derived is an instance Base",
2003         server.isInstanceOf(derivedName, Base.class.getName()));
2004      assertTrue("Derived is an instance Derived",
2005         server.isInstanceOf(derivedName, Derived.class.getName()));
2006      assertTrue("Unrelated is an instance Object",
2007         server.isInstanceOf(unrelatedName, Object.class.getName()));
2008      assertTrue("Unrelated is an instance UnrelatedMBean",
2009         server.isInstanceOf(unrelatedName, UnrelatedMBean.class.getName()));
2010      assertTrue("Unrelated is an instance Unrelated",
2011         server.isInstanceOf(unrelatedName, Unrelated.class.getName()));
2012
2013      assertTrue("Base is an not instance Derived",
2014         server.isInstanceOf(baseName, Derived.class.getName()) == false);
2015      assertTrue("Base is an not instance UnrelatedMBean",
2016         server.isInstanceOf(baseName, UnrelatedMBean.class.getName()) == false);
2017      assertTrue("Base is an not instance Unrelated",
2018         server.isInstanceOf(baseName, Unrelated.class.getName()) == false);
2019      assertTrue("Derived is an not instance UnrelatedMBean",
2020         server.isInstanceOf(derivedName, UnrelatedMBean.class.getName()) == false);
2021      assertTrue("Dervied is an not instance Unrelated",
2022         server.isInstanceOf(derivedName, Unrelated.class.getName()) == false);
2023      assertTrue("Unrelated is an not instance BaseMBean",
2024         server.isInstanceOf(unrelatedName, BaseMBean.class.getName()) == false);
2025      assertTrue("Unrelated is an not instance Base",
2026         server.isInstanceOf(unrelatedName, Base.class.getName()) == false);
2027      assertTrue("Unrelated is an not instance Derived",
2028         server.isInstanceOf(unrelatedName, Derived.class.getName()) == false);
2029   }
2030
2031   public void testIsInstanceOfErrors()
2032      throws Exception
2033   {
2034      MBeanServer server = MBeanServerFactory.newMBeanServer();
2035      ObjectName baseName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=Base");
2036      ObjectName dynamicName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=Dynamic");
2037      ObjectName doesNotExistName = new ObjectName("MBeanServerTEST:type=testIsInstanceOf,name=DoesNotExist");
2038
2039      server.registerMBean(new Base(), baseName);
2040      server.registerMBean(new Dynamic(), dynamicName);
2041
2042      assertTrue("Base is not an instance of a class that does not exist",
2043         server.isInstanceOf(baseName, "does.not.exist") == false);
2044
2045      assertTrue("FAILS IN RI: Not an instance if the getMBeanInfo reports a class name that does not exist",
2046         server.isInstanceOf(dynamicName, Object.class.getName()) == false);
2047
2048      boolean caught = false;
2049      try
2050      {
2051         server.isInstanceOf(doesNotExistName, Object.class.getName());
2052      }
2053      catch (InstanceNotFoundException e)
2054      {
2055         caught = true;
2056      }
2057      assertTrue("Should get an instance not found for a non-existent mbean", caught);
2058   }
2059}
2060
Popular Tags