KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > sf > cglib > proxy > TestEnhancer


1 /*
2  * Copyright 2002,2003,2004 The Apache Software Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package net.sf.cglib.proxy;
17
18 import java.io.*;
19 import java.lang.reflect.*;
20 import junit.framework.*;
21 import net.sf.cglib.CodeGenTestCase;
22 import net.sf.cglib.core.ReflectUtils;
23 import net.sf.cglib.reflect.FastClass;
24
25 /**
26  *@author Juozas Baliuka <a HREF="mailto:baliuka@mwm.lt">
27  * baliuka@mwm.lt</a>
28  *@version $Id: TestEnhancer.java,v 1.53 2005/06/09 09:22:04 baliuka Exp $
29  */

30 public class TestEnhancer extends CodeGenTestCase {
31     private static final MethodInterceptor TEST_INTERCEPTOR = new TestInterceptor();
32     
33     private static final Class JavaDoc [] EMPTY_ARG = new Class JavaDoc[]{};
34     
35     private boolean invokedProtectedMethod = false;
36     
37     private boolean invokedPackageMethod = false;
38     
39     private boolean invokedAbstractMethod = false;
40     
41     public TestEnhancer(String JavaDoc testName) {
42         super(testName);
43     }
44     
45     
46     
47     public static Test suite() {
48         return new TestSuite(TestEnhancer.class);
49     }
50     
51     public static void main(String JavaDoc args[]) {
52         String JavaDoc[] testCaseName = {TestEnhancer.class.getName()};
53         junit.textui.TestRunner.main(testCaseName);
54     }
55
56     public void testEnhance()throws Throwable JavaDoc{
57         
58         java.util.Vector JavaDoc vector1 = (java.util.Vector JavaDoc)Enhancer.create(
59         java.util.Vector JavaDoc.class,
60         new Class JavaDoc[]{java.util.List JavaDoc.class}, TEST_INTERCEPTOR );
61         
62         java.util.Vector JavaDoc vector2 = (java.util.Vector JavaDoc)Enhancer.create(
63         java.util.Vector JavaDoc.class,
64         new Class JavaDoc[]{java.util.List JavaDoc.class}, TEST_INTERCEPTOR );
65         
66         
67         
68         
69         assertTrue("Cache failed",vector1.getClass() == vector2.getClass());
70     }
71     
72    
73     public void testMethods()throws Throwable JavaDoc{
74         
75         MethodInterceptor interceptor =
76         new TestInterceptor(){
77             
78             public Object JavaDoc afterReturn( Object JavaDoc obj, Method method,
79             Object JavaDoc args[],
80             boolean invokedSuper, Object JavaDoc retValFromSuper,
81             java.lang.Throwable JavaDoc e )throws java.lang.Throwable JavaDoc{
82                 
83                 int mod = method.getModifiers();
84                 
85                 if( Modifier.isProtected( mod ) ){
86                     invokedProtectedMethod = true;
87                 }
88                 
89                 if( Modifier.isAbstract(mod) ){
90                     invokedAbstractMethod = true;
91                 }
92                 
93                 
94                 if( ! ( Modifier.isProtected( mod ) || Modifier.isPublic( mod ) )){
95                     invokedPackageMethod = true;
96                 }
97                 
98                 return retValFromSuper;//return the same as supper
99
}
100             
101         };
102         
103         
104         Source source = (Source)Enhancer.create(
105         Source.class,
106         null,interceptor );
107         
108         source.callAll();
109         assertTrue("protected", invokedProtectedMethod );
110         assertTrue("package", invokedPackageMethod );
111         assertTrue("abstract", invokedAbstractMethod );
112     }
113     
114     public void testEnhanced()throws Throwable JavaDoc{
115         
116         Source source = (Source)Enhancer.create(
117         Source.class,
118         null, TEST_INTERCEPTOR );
119         
120         
121         TestCase.assertTrue("enhance", Source.class != source.getClass() );
122         
123     }
124
125     public void testEnhanceObject() throws Throwable JavaDoc {
126         EA obj = new EA();
127         EA save = obj;
128         obj.setName("herby");
129         EA proxy = (EA)Enhancer.create( EA.class, new DelegateInterceptor(save) );
130      
131         assertTrue(proxy.getName().equals("herby"));
132
133         Factory factory = (Factory)proxy;
134         assertTrue(((EA)factory.newInstance(factory.getCallbacks())).getName().equals("herby"));
135     }
136
137     class DelegateInterceptor implements MethodInterceptor {
138       Object JavaDoc delegate;
139         DelegateInterceptor(Object JavaDoc delegate){
140           this.delegate = delegate;
141         }
142         public Object JavaDoc intercept(Object JavaDoc obj, java.lang.reflect.Method JavaDoc method, Object JavaDoc[] args, MethodProxy proxy) throws Throwable JavaDoc {
143             return proxy.invoke(delegate,args);
144         }
145         
146     }
147     public void testEnhanceObjectDelayed() throws Throwable JavaDoc {
148         
149         DelegateInterceptor mi = new DelegateInterceptor(null);
150         EA proxy = (EA)Enhancer.create( EA.class, mi);
151         EA obj = new EA();
152         obj.setName("herby");
153         mi.delegate = obj;
154        assertTrue(proxy.getName().equals("herby"));
155     }
156     
157     
158     public void testTypes()throws Throwable JavaDoc{
159         
160         Source source = (Source)Enhancer.create(
161         Source.class,
162         null, TEST_INTERCEPTOR );
163         TestCase.assertTrue("intType", 1 == source.intType(1));
164         TestCase.assertTrue("longType", 1L == source.longType(1L));
165         TestCase.assertTrue("floatType", 1.1f == source.floatType(1.1f));
166         TestCase.assertTrue("doubleType",1.1 == source.doubleType(1.1));
167         TestCase.assertEquals("objectType","1", source.objectType("1") );
168         TestCase.assertEquals("objectType","", source.toString() );
169         source.arrayType( new int[]{} );
170         
171     }
172     
173
174     public void testModifiers()throws Throwable JavaDoc{
175         
176         Source source = (Source)Enhancer.create(
177         Source.class,
178         null, TEST_INTERCEPTOR );
179         
180         Class JavaDoc enhancedClass = source.getClass();
181         
182         assertTrue("isProtected" , Modifier.isProtected( enhancedClass.getDeclaredMethod("protectedMethod", EMPTY_ARG ).getModifiers() ));
183         int mod = enhancedClass.getDeclaredMethod("packageMethod", EMPTY_ARG ).getModifiers() ;
184         assertTrue("isPackage" , !( Modifier.isProtected(mod)|| Modifier.isPublic(mod) ) );
185         
186         //not sure about this (do we need it for performace ?)
187
assertTrue("isFinal" , Modifier.isFinal( mod ) );
188         
189         mod = enhancedClass.getDeclaredMethod("synchronizedMethod", EMPTY_ARG ).getModifiers() ;
190         assertTrue("isSynchronized" , !Modifier.isSynchronized( mod ) );
191         
192         
193     }
194     
195     public void testObject()throws Throwable JavaDoc{
196         
197         Object JavaDoc source = Enhancer.create(
198         null,
199         null, TEST_INTERCEPTOR );
200         
201         assertTrue("parent is object",
202         source.getClass().getSuperclass() == Object JavaDoc.class );
203         
204     }
205
206     public void testSystemClassLoader()throws Throwable JavaDoc{
207         
208         Object JavaDoc source = enhance(
209         null,
210         null, TEST_INTERCEPTOR , ClassLoader.getSystemClassLoader());
211         source.toString();
212         assertTrue("SystemClassLoader",
213         source.getClass().getClassLoader()
214         == ClassLoader.getSystemClassLoader() );
215         
216     }
217     
218     
219     
220     public void testCustomClassLoader()throws Throwable JavaDoc{
221         
222         ClassLoader JavaDoc custom = new ClassLoader JavaDoc(this.getClass().getClassLoader()){};
223         
224         Object JavaDoc source = enhance( null, null, TEST_INTERCEPTOR, custom);
225         source.toString();
226         assertTrue("Custom classLoader", source.getClass().getClassLoader() == custom );
227         
228         custom = new ClassLoader JavaDoc(){};
229         
230         source = enhance( null, null, TEST_INTERCEPTOR, custom);
231         source.toString();
232         assertTrue("Custom classLoader", source.getClass().getClassLoader() == custom );
233         
234         
235     }
236
237     public void testRuntimException()throws Throwable JavaDoc{
238     
239         Source source = (Source)Enhancer.create(
240         Source.class,
241         null, TEST_INTERCEPTOR );
242         
243         try{
244             
245             source.throwIndexOutOfBoundsException();
246             fail("must throw an exception");
247             
248         }catch( IndexOutOfBoundsException JavaDoc ok ){
249             
250         }
251     
252     }
253     
254   static abstract class CastTest{
255      CastTest(){}
256     abstract int getInt();
257   }
258   
259   class CastTestInterceptor implements MethodInterceptor{
260      
261       public Object JavaDoc intercept(Object JavaDoc obj, java.lang.reflect.Method JavaDoc method, Object JavaDoc[] args, MethodProxy proxy) throws Throwable JavaDoc {
262           return new Short JavaDoc((short)0);
263       }
264       
265   }
266   
267     
268   public void testCast()throws Throwable JavaDoc{
269     
270     CastTest castTest = (CastTest)Enhancer.create(CastTest.class, null, new CastTestInterceptor());
271   
272     assertTrue(castTest.getInt() == 0);
273     
274   }
275   
276    public void testABC() throws Throwable JavaDoc{
277        Enhancer.create(EA.class, null, TEST_INTERCEPTOR);
278        Enhancer.create(EC1.class, null, TEST_INTERCEPTOR).toString();
279        ((EB)Enhancer.create(EB.class, null, TEST_INTERCEPTOR)).finalTest();
280        assertTrue("abstract method",( (EC1)Enhancer.create(EC1.class,
281                      null, TEST_INTERCEPTOR) ).compareTo( new EC1() ) == -1 );
282        Enhancer.create(ED.class, null, TEST_INTERCEPTOR).toString();
283        Enhancer.create(ClassLoader JavaDoc.class, null, TEST_INTERCEPTOR).toString();
284    }
285
286     public static class AroundDemo {
287         public String JavaDoc getFirstName() {
288             return "Chris";
289         }
290         public String JavaDoc getLastName() {
291             return "Nokleberg";
292         }
293     }
294
295     public void testAround() throws Throwable JavaDoc {
296         AroundDemo demo = (AroundDemo)Enhancer.create(AroundDemo.class, null, new MethodInterceptor() {
297                 public Object JavaDoc intercept(Object JavaDoc obj, Method method, Object JavaDoc[] args,
298                                            MethodProxy proxy) throws Throwable JavaDoc {
299                     if (method.getName().equals("getFirstName")) {
300                         return "Christopher";
301                     }
302                     return proxy.invokeSuper(obj, args);
303                 }
304             });
305         assertTrue(demo.getFirstName().equals("Christopher"));
306         assertTrue(demo.getLastName().equals("Nokleberg"));
307     }
308  
309     
310     public static interface TestClone extends Cloneable JavaDoc{
311      public Object JavaDoc clone()throws java.lang.CloneNotSupportedException JavaDoc;
312
313     }
314     public static class TestCloneImpl implements TestClone{
315      public Object JavaDoc clone()throws java.lang.CloneNotSupportedException JavaDoc{
316          return super.clone();
317      }
318     }
319
320     public void testClone() throws Throwable JavaDoc{
321     
322       TestClone testClone = (TestClone)Enhancer.create( TestCloneImpl.class,
323                                                           TEST_INTERCEPTOR );
324       assertTrue( testClone.clone() != null );
325       
326             
327       testClone = (TestClone)Enhancer.create( TestClone.class,
328          new MethodInterceptor(){
329       
330            public Object JavaDoc intercept(Object JavaDoc obj, java.lang.reflect.Method JavaDoc method, Object JavaDoc[] args,
331                         MethodProxy proxy) throws Throwable JavaDoc{
332                      return proxy.invokeSuper(obj, args);
333            }
334   
335       
336       } );
337
338       assertTrue( testClone.clone() != null );
339       
340       
341     }
342     
343     public void testSamples() throws Throwable JavaDoc{
344         samples.Trace.main(new String JavaDoc[]{});
345         samples.Beans.main(new String JavaDoc[]{});
346     }
347
348     public static interface FinalA {
349         void foo();
350     }
351
352     public static class FinalB implements FinalA {
353         final public void foo() { }
354     }
355
356     public void testFinal() throws Throwable JavaDoc {
357         ((FinalA)Enhancer.create(FinalB.class, TEST_INTERCEPTOR)).foo();
358     }
359
360     public static interface ConflictA {
361         int foo();
362     }
363
364     public static interface ConflictB {
365         String JavaDoc foo();
366     }
367
368     public void testConflict() throws Throwable JavaDoc {
369         Object JavaDoc foo =
370             Enhancer.create(Object JavaDoc.class, new Class JavaDoc[]{ ConflictA.class, ConflictB.class }, TEST_INTERCEPTOR);
371         ((ConflictA)foo).foo();
372         ((ConflictB)foo).foo();
373     }
374
375     // TODO: make this work again
376
public void testArgInit() throws Throwable JavaDoc{
377
378          Enhancer e = new Enhancer();
379          e.setSuperclass(ArgInit.class);
380          e.setCallbackType(MethodInterceptor.class);
381          Class JavaDoc f = e.createClass();
382          ArgInit a = (ArgInit)ReflectUtils.newInstance(f,
383                                                        new Class JavaDoc[]{ String JavaDoc.class },
384                                                        new Object JavaDoc[]{ "test" });
385          assertEquals("test", a.toString());
386          ((Factory)a).setCallback(0, TEST_INTERCEPTOR);
387          assertEquals("test", a.toString());
388
389          Callback[] callbacks = new Callback[]{ TEST_INTERCEPTOR };
390          ArgInit b = (ArgInit)((Factory)a).newInstance(new Class JavaDoc[]{ String JavaDoc.class },
391                                                        new Object JavaDoc[]{ "test2" },
392                                                        callbacks);
393          assertEquals("test2", b.toString());
394          try{
395              ((Factory)a).newInstance(new Class JavaDoc[]{ String JavaDoc.class, String JavaDoc.class },
396                                       new Object JavaDoc[]{"test"},
397                                       callbacks);
398              fail("must throw exception");
399          }catch( IllegalArgumentException JavaDoc iae ){
400          
401          }
402     }
403
404     public static class Signature {
405         public int interceptor() {
406             return 42;
407         }
408     }
409
410     public void testSignature() throws Throwable JavaDoc {
411         Signature sig = (Signature)Enhancer.create(Signature.class, TEST_INTERCEPTOR);
412         assertTrue(((Factory)sig).getCallback(0) == TEST_INTERCEPTOR);
413         assertTrue(sig.interceptor() == 42);
414     }
415
416     public abstract static class AbstractMethodCallInConstructor {
417     public AbstractMethodCallInConstructor() {
418         foo();
419     }
420
421     public abstract void foo();
422     }
423
424     public void testAbstractMethodCallInConstructor() throws Throwable JavaDoc {
425     AbstractMethodCallInConstructor obj = (AbstractMethodCallInConstructor)
426         Enhancer.create(AbstractMethodCallInConstructor.class,
427                  TEST_INTERCEPTOR);
428     obj.foo();
429     }
430
431     public void testProxyIface() throws Throwable JavaDoc {
432         final DI1 other = new DI1() {
433                 public String JavaDoc herby() {
434                     return "boop";
435                 }
436             };
437         DI1 d = (DI1)Enhancer.create(DI1.class, new MethodInterceptor() {
438                 public Object JavaDoc intercept(Object JavaDoc obj, java.lang.reflect.Method JavaDoc method, Object JavaDoc[] args,
439                                         MethodProxy proxy) throws Throwable JavaDoc {
440                     return proxy.invoke(other, args);
441                 }
442             });
443         assertTrue("boop".equals(d.herby()));
444     }
445
446     public static Object JavaDoc enhance(Class JavaDoc cls, Class JavaDoc interfaces[], Callback callback, ClassLoader JavaDoc loader) {
447         Enhancer e = new Enhancer();
448         e.setSuperclass(cls);
449         e.setInterfaces(interfaces);
450         e.setCallback(callback);
451         e.setClassLoader(loader);
452         return e.create();
453     }
454
455     public interface PublicClone extends Cloneable JavaDoc {
456         Object JavaDoc clone() throws CloneNotSupportedException JavaDoc;
457     }
458
459     public void testNoOpClone() throws Exception JavaDoc {
460         Enhancer enhancer = new Enhancer();
461         enhancer.setSuperclass(PublicClone.class);
462         enhancer.setCallback(NoOp.INSTANCE);
463         ((PublicClone)enhancer.create()).clone();
464     }
465
466     public void testNoFactory() throws Exception JavaDoc {
467         noFactoryHelper();
468         noFactoryHelper();
469     }
470
471     private void noFactoryHelper() {
472         MethodInterceptor mi = new MethodInterceptor() {
473             public Object JavaDoc intercept(Object JavaDoc obj, Method method, Object JavaDoc[] args, MethodProxy proxy) throws Throwable JavaDoc {
474                 return "Foo";
475             }
476         };
477         Enhancer enhancer = new Enhancer();
478         enhancer.setUseFactory(false);
479         enhancer.setSuperclass(AroundDemo.class);
480         enhancer.setCallback(mi);
481         AroundDemo obj = (AroundDemo)enhancer.create();
482         assertTrue(obj.getFirstName().equals("Foo"));
483         assertTrue(!(obj instanceof Factory));
484     }
485
486     interface MethDec {
487         void foo();
488     }
489     
490     abstract static class MethDecImpl implements MethDec {
491     }
492
493     public void testMethodDeclarer() throws Exception JavaDoc {
494         final boolean[] result = new boolean[]{ false };
495         Enhancer enhancer = new Enhancer();
496         enhancer.setSuperclass(MethDecImpl.class);
497         enhancer.setCallback(new MethodInterceptor() {
498             public Object JavaDoc intercept(Object JavaDoc obj, Method method, Object JavaDoc[] args, MethodProxy proxy) throws Throwable JavaDoc {
499                 
500                 result[0] = method.getDeclaringClass().getName().equals(MethDec.class.getName());
501                 return null;
502             }
503         });
504         ((MethDecImpl)enhancer.create()).foo();
505         assertTrue(result[0]);
506     }
507
508
509     interface ClassOnlyX { }
510     public void testClassOnlyFollowedByInstance() {
511         Enhancer enhancer = new Enhancer();
512         enhancer.setSuperclass(ClassOnlyX.class);
513         enhancer.setCallbackType(NoOp.class);
514         Class JavaDoc type = enhancer.createClass();
515
516         enhancer = new Enhancer();
517         enhancer.setSuperclass(ClassOnlyX.class);
518         enhancer.setCallback(NoOp.INSTANCE);
519         Object JavaDoc instance = enhancer.create();
520
521         assertTrue(instance instanceof ClassOnlyX);
522         assertTrue(instance.getClass().equals(type));
523     }
524
525      public void testSql() {
526          Enhancer.create(null, new Class JavaDoc[]{ java.sql.PreparedStatement JavaDoc.class }, TEST_INTERCEPTOR);
527      }
528
529     public void testEquals() throws Exception JavaDoc {
530         final boolean[] result = new boolean[]{ false };
531         EqualsInterceptor intercept = new EqualsInterceptor();
532         Object JavaDoc obj = Enhancer.create(null, intercept);
533         obj.equals(obj);
534         assertTrue(intercept.called);
535     }
536
537     public static class EqualsInterceptor implements MethodInterceptor {
538         final static Method EQUALS_METHOD = ReflectUtils.findMethod("Object.equals(Object)");
539         boolean called;
540
541         public Object JavaDoc intercept(Object JavaDoc obj,
542                                 Method method,
543                                 Object JavaDoc[] args,
544                                 MethodProxy proxy) throws Throwable JavaDoc {
545             if (method.equals(EQUALS_METHOD)) {
546                 return proxy.invoke(this, args);
547             } else {
548                 return proxy.invokeSuper(obj, args);
549             }
550         }
551
552         public boolean equals(Object JavaDoc other) {
553             called = true;
554             return super.equals(other);
555         }
556     }
557
558     private static interface ExceptionThrower {
559         void throwsThrowable(int arg) throws Throwable JavaDoc;
560         void throwsException(int arg) throws Exception JavaDoc;
561         void throwsNothing(int arg);
562     }
563
564     private static class MyThrowable extends Throwable JavaDoc { }
565     private static class MyException extends Exception JavaDoc { }
566     private static class MyRuntimeException extends RuntimeException JavaDoc { }
567     
568     public void testExceptions() {
569         Enhancer e = new Enhancer();
570         e.setSuperclass(ExceptionThrower.class);
571         e.setCallback(new MethodInterceptor() {
572             public Object JavaDoc intercept(Object JavaDoc obj,
573                                     Method method,
574                                     Object JavaDoc[] args,
575                                     MethodProxy proxy) throws Throwable JavaDoc {
576                 switch (((Integer JavaDoc)args[0]).intValue()) {
577                 case 1:
578                     throw new MyThrowable();
579                 case 2:
580                     throw new MyException();
581                 case 3:
582                     throw new MyRuntimeException();
583                 default:
584                     return null;
585                 }
586             }
587         });
588         ExceptionThrower et = (ExceptionThrower)e.create();
589         try { et.throwsThrowable(1); } catch (MyThrowable t) { } catch (Throwable JavaDoc t) { fail(); }
590         try { et.throwsThrowable(2); } catch (MyException t) { } catch (Throwable JavaDoc t) { fail(); }
591         try { et.throwsThrowable(3); } catch (MyRuntimeException t) { } catch (Throwable JavaDoc t) { fail(); }
592
593         try { et.throwsException(1); } catch (Throwable JavaDoc t) { assertTrue(t instanceof MyThrowable); }
594         try { et.throwsException(2); } catch (MyException t) { } catch (Throwable JavaDoc t) { fail(); }
595         try { et.throwsException(3); } catch (MyRuntimeException t) { } catch (Throwable JavaDoc t) { fail(); }
596         try { et.throwsException(4); } catch (Throwable JavaDoc t) { fail(); }
597
598         try { et.throwsNothing(1); } catch (Throwable JavaDoc t) { assertTrue(t instanceof MyThrowable); }
599         try { et.throwsNothing(2); } catch (Exception JavaDoc t) { assertTrue(t instanceof MyException); }
600         try { et.throwsNothing(3); } catch (MyRuntimeException t) { } catch (Throwable JavaDoc t) { fail(); }
601         try { et.throwsNothing(4); } catch (Throwable JavaDoc t) { fail(); }
602     }
603
604     public void testUnusedCallback() {
605         Enhancer e = new Enhancer();
606         e.setCallbackTypes(new Class JavaDoc[]{ MethodInterceptor.class, NoOp.class });
607         e.setCallbackFilter(new CallbackFilter() {
608             public int accept(Method method) {
609                 return 0;
610             }
611         });
612         e.createClass();
613     }
614
615     private static ArgInit newArgInit(Class JavaDoc clazz, String JavaDoc value) {
616         return (ArgInit)ReflectUtils.newInstance(clazz,
617                                                  new Class JavaDoc[]{ String JavaDoc.class },
618                                                  new Object JavaDoc[]{ value });
619     }
620
621     private static class StringValue
622     implements MethodInterceptor
623     {
624         private String JavaDoc value;
625
626         public StringValue(String JavaDoc value) {
627             this.value = value;
628         }
629         public Object JavaDoc intercept(Object JavaDoc obj, Method method, Object JavaDoc[] args, MethodProxy proxy) {
630             return value;
631         }
632     }
633
634     public void testRegisterCallbacks()
635     throws InterruptedException JavaDoc
636     {
637          Enhancer e = new Enhancer();
638          e.setSuperclass(ArgInit.class);
639          e.setCallbackType(MethodInterceptor.class);
640          e.setUseFactory(false);
641          final Class JavaDoc clazz = e.createClass();
642
643          assertTrue(!Factory.class.isAssignableFrom(clazz));
644          assertEquals("test", newArgInit(clazz, "test").toString());
645
646          Enhancer.registerCallbacks(clazz, new Callback[]{ new StringValue("fizzy") });
647          assertEquals("fizzy", newArgInit(clazz, "test").toString());
648          assertEquals("fizzy", newArgInit(clazz, "test").toString());
649
650          Enhancer.registerCallbacks(clazz, new Callback[]{ null });
651          assertEquals("test", newArgInit(clazz, "test").toString());
652
653          Enhancer.registerStaticCallbacks(clazz, new Callback[]{ new StringValue("soda") });
654          assertEquals("test", newArgInit(clazz, "test").toString());
655
656          Enhancer.registerCallbacks(clazz, null);
657          assertEquals("soda", newArgInit(clazz, "test").toString());
658          
659          Thread JavaDoc thread = new Thread JavaDoc(){
660              public void run() {
661                  assertEquals("soda", newArgInit(clazz, "test").toString());
662              }
663          };
664          thread.start();
665          thread.join();
666     }
667     
668    public void perform(ClassLoader JavaDoc loader) throws Exception JavaDoc{
669     
670            enhance( Source.class , null, TEST_INTERCEPTOR, loader);
671     
672     }
673     
674    public void testFailOnMemoryLeak() throws Throwable JavaDoc{
675          if( leaks() ){
676            fail("Memory leak caused by Enhancer");
677          }
678     }
679
680     public void testCallbackHelper() {
681         final ArgInit delegate = new ArgInit("helper");
682         Class JavaDoc sc = ArgInit.class;
683         Class JavaDoc[] interfaces = new Class JavaDoc[]{ DI1.class, DI2.class };
684
685         CallbackHelper helper = new CallbackHelper(sc, interfaces) {
686             protected Object JavaDoc getCallback(final Method method) {
687                 return new FixedValue() {
688                     public Object JavaDoc loadObject() {
689                         return "You called method " + method.getName();
690                     }
691                 };
692             }
693         };
694
695         Enhancer e = new Enhancer();
696         e.setSuperclass(sc);
697         e.setInterfaces(interfaces);
698         e.setCallbacks(helper.getCallbacks());
699         e.setCallbackFilter(helper);
700
701         ArgInit proxy = (ArgInit)e.create(new Class JavaDoc[]{ String JavaDoc.class }, new Object JavaDoc[]{ "whatever" });
702         assertEquals("You called method toString", proxy.toString());
703         assertEquals("You called method herby", ((DI1)proxy).herby());
704         assertEquals("You called method derby", ((DI2)proxy).derby());
705     }
706
707     public void testSerialVersionUID() throws Exception JavaDoc {
708         Long JavaDoc suid = new Long JavaDoc(0xABBADABBAD00L);
709
710         Enhancer e = new Enhancer();
711         e.setSerialVersionUID(suid);
712         e.setCallback(NoOp.INSTANCE);
713         Object JavaDoc obj = e.create();
714
715         Field field = obj.getClass().getDeclaredField("serialVersionUID");
716         field.setAccessible(true);
717         assertEquals(suid, field.get(obj));
718     }
719
720     interface ReturnTypeA { int foo(String JavaDoc x); }
721     interface ReturnTypeB { String JavaDoc foo(String JavaDoc x); }
722     public void testMethodsDifferingByReturnTypeOnly() throws IOException {
723         Enhancer e = new Enhancer();
724         e.setInterfaces(new Class JavaDoc[]{ ReturnTypeA.class, ReturnTypeB.class });
725         e.setCallback(new MethodInterceptor() {
726             public Object JavaDoc intercept(Object JavaDoc obj, Method method, Object JavaDoc[] args, MethodProxy proxy) throws Throwable JavaDoc {
727                 if (method.getReturnType().equals(String JavaDoc.class))
728                     return "hello";
729                 return new Integer JavaDoc(42);
730             }
731         });
732         Object JavaDoc obj = e.create();
733         assertEquals(42, ((ReturnTypeA)obj).foo("foo"));
734         assertEquals("hello", ((ReturnTypeB)obj).foo("foo"));
735         assertEquals(-1, FastClass.create(obj.getClass()).getIndex("foo", new Class JavaDoc[]{ String JavaDoc.class }));
736     }
737
738
739     public static class ConstructorCall
740     {
741         private String JavaDoc x;
742         public ConstructorCall() {
743             x = toString();
744         }
745         public String JavaDoc toString() {
746             return "foo";
747         }
748     }
749     
750     public void testInterceptDuringConstruction() {
751         FixedValue fixedValue = new FixedValue() {
752             public Object JavaDoc loadObject() {
753                 return "bar";
754             }
755         };
756
757         Enhancer e = new Enhancer();
758         e.setSuperclass(ConstructorCall.class);
759         e.setCallback(fixedValue);
760         assertEquals("bar", ((ConstructorCall)e.create()).x);
761
762         e = new Enhancer();
763         e.setSuperclass(ConstructorCall.class);
764         e.setCallback(fixedValue);
765         e.setInterceptDuringConstruction(false);
766         assertEquals("foo", ((ConstructorCall)e.create()).x);
767     }
768 }
769
Popular Tags