You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ProxyTester.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. package testproxy;
  2. import java.lang.reflect.Method;
  3. import java.lang.reflect.Constructor;
  4. import java.lang.reflect.Modifier;
  5. import org.junit.Assert;
  6. import java.lang.reflect.InvocationTargetException;
  7. import javassist.util.proxy.ProxyFactory;
  8. import javassist.util.proxy.MethodFilter;
  9. import javassist.util.proxy.MethodHandler;
  10. import javassist.util.proxy.ProxyObject;
  11. import javassist.util.proxy.Proxy;
  12. import junit.framework.TestCase;
  13. import java.io.*;
  14. @SuppressWarnings({"unchecked", "rawtypes","unused"})
  15. public class ProxyTester extends TestCase {
  16. public ProxyTester(String s) {
  17. super(s);
  18. }
  19. public ProxyTester() {
  20. this("proxy");
  21. }
  22. static class Interceptor1 implements MethodHandler {
  23. int counter = 0;
  24. public Object invoke(Object self, Method m, Method proceed,
  25. Object[] args) throws Exception {
  26. System.out.println("intercept: " + m + ", proceed: " + proceed);
  27. System.out.println(" modifier: "
  28. + Modifier.toString(proceed.getModifiers()));
  29. counter++;
  30. return proceed.invoke(self, args);
  31. }
  32. }
  33. static class Interceptor2 implements MethodHandler {
  34. int counter = 0;
  35. public Object invoke(Object self, Method m, Method proceed,
  36. Object[] args) throws Exception {
  37. System.out.println("intercept: " + m + ", proceed: " + proceed);
  38. counter++;
  39. if (proceed != null)
  40. return proceed.invoke(self, args);
  41. else
  42. if (m.getReturnType() == int.class)
  43. return Integer.valueOf(3);
  44. else
  45. return "OK";
  46. }
  47. }
  48. static MethodFilter finalizeRemover = new MethodFilter() {
  49. public boolean isHandled(Method m) {
  50. return !m.getName().equals("finalize");
  51. }
  52. };
  53. public void testTarget() throws Exception {
  54. ProxyFactory f = new ProxyFactory();
  55. f.setSuperclass(Target.class);
  56. Interceptor1 interceptor = new Interceptor1();
  57. // f.setHandler(interceptor);
  58. f.setFilter(finalizeRemover);
  59. f.writeDirectory = ".";
  60. Class c = f.createClass();
  61. Target obj = (Target)c.getConstructor().newInstance();
  62. ((Proxy)obj).setHandler(interceptor);
  63. obj.m();
  64. assertEquals(true, obj.m(true));
  65. assertEquals((byte)1, obj.m1((byte)1));
  66. assertEquals('a', obj.m2('a'));
  67. assertEquals((short)2, obj.m3((short)2));
  68. assertEquals(3, obj.m(3));
  69. assertEquals(4L, obj.m5(4L));
  70. assertTrue(5.0F == obj.m6(5.0F));
  71. assertTrue(6.0 == obj.m7(6.0));
  72. assertEquals("test", obj.m("test"));
  73. int[] ia = { 1, 2, 3 };
  74. assertEquals(ia, obj.m7(ia));
  75. String[] sa = { "1", "2" };
  76. assertEquals(sa, obj.m8(sa));
  77. assertEquals(obj, obj.m9(3, obj, null));
  78. assertEquals(14, interceptor.counter);
  79. }
  80. public void testTarget1() throws Exception {
  81. ProxyFactory f = new ProxyFactory();
  82. f.setSuperclass(Target1.class);
  83. Interceptor1 interceptor = new Interceptor1();
  84. // f.setHandler(interceptor);
  85. f.setFilter(finalizeRemover);
  86. Class c = f.createClass();
  87. Target1 obj = (Target1)c.getConstructor().newInstance();
  88. ((Proxy)obj).setHandler(interceptor);
  89. assertEquals(null, obj.m(null));
  90. assertEquals(1, interceptor.counter);
  91. }
  92. public void testObject() throws Exception {
  93. ProxyFactory f = new ProxyFactory();
  94. Interceptor1 interceptor = new Interceptor1();
  95. // f.setHandler(interceptor);
  96. f.setFilter(finalizeRemover);
  97. Class c = f.createClass();
  98. Object obj = (Object)c.getConstructor().newInstance();
  99. ((Proxy)obj).setHandler(interceptor);
  100. System.out.println(obj.toString());
  101. assertEquals(2, interceptor.counter);
  102. }
  103. public void testSetter() throws Exception {
  104. ProxyFactory f = new ProxyFactory();
  105. f.writeDirectory = ".";
  106. Interceptor1 interceptor = new Interceptor1();
  107. // f.setHandler(interceptor);
  108. f.setFilter(finalizeRemover);
  109. Class c = f.createClass();
  110. Object obj = (Object)c.getConstructor().newInstance();
  111. ((Proxy)obj).setHandler(interceptor);
  112. System.out.println("setter1: " + obj.toString());
  113. ((ProxyObject)obj).setHandler(new MethodHandler() {
  114. public Object invoke(Object self, Method m, Method proceed,
  115. Object[] args) throws Exception {
  116. System.out.print("intercept: " + m);
  117. return "OK";
  118. }
  119. });
  120. assertEquals("OK", obj.toString());
  121. }
  122. public void testString() throws Exception {
  123. ProxyFactory f = new ProxyFactory();
  124. Interceptor1 interceptor = new Interceptor1();
  125. // f.setHandler(interceptor);
  126. f.setFilter(finalizeRemover);
  127. f.setSuperclass(String.class);
  128. try {
  129. Class c = f.createClass();
  130. Assert.fail("String is final!");
  131. }
  132. catch (RuntimeException e) {
  133. System.out.println(e);
  134. }
  135. }
  136. public void testConstructor() throws Exception {
  137. ProxyFactory f = new ProxyFactory();
  138. Interceptor1 interceptor = new Interceptor1();
  139. // f.setHandler(interceptor);
  140. f.setFilter(finalizeRemover);
  141. f.setSuperclass(Target2.class);
  142. Class c = f.createClass();
  143. Constructor[] cons = c.getDeclaredConstructors();
  144. assertEquals(3, cons.length);
  145. Constructor con1 = c.getDeclaredConstructor(new Class[] { int.class });
  146. Constructor con2 = c.getDeclaredConstructor(new Class[] { int.class, int.class });
  147. Method m1 = c.getDeclaredMethod("get", new Class[0]);
  148. Method m2 = c.getDeclaredMethod("foo", new Class[0]);
  149. assertEquals(0, m1.getExceptionTypes().length);
  150. assertEquals("java.io.IOException", m2.getExceptionTypes()[0].getName());
  151. Target2 t2 = (Target2)con1.newInstance(new Object[] { Integer.valueOf(1) });
  152. ((Proxy)t2).setHandler(interceptor);
  153. System.out.println(t2.toString());
  154. assertEquals(2, interceptor.counter);
  155. interceptor.counter = 0;
  156. assertEquals(2, t2.foo());
  157. assertEquals(4, t2._dfoo());
  158. assertEquals(2, interceptor.counter);
  159. }
  160. public void testInterface() throws Exception {
  161. ProxyFactory f = new ProxyFactory();
  162. Interceptor2 interceptor2 = new Interceptor2();
  163. // f.setHandler(interceptor2);
  164. f.setFilter(finalizeRemover);
  165. f.setInterfaces(new Class[] { Target3.class });
  166. Class c = f.createClass();
  167. Target3 obj = (Target3)c.getConstructor().newInstance();
  168. ((Proxy)obj).setHandler(interceptor2);
  169. assertEquals("OK", obj.m());
  170. System.out.println(obj.toString());
  171. assertEquals(3, interceptor2.counter);
  172. }
  173. public void test2Interfaces() throws Exception {
  174. ProxyFactory f = new ProxyFactory();
  175. Interceptor2 interceptor2 = new Interceptor2();
  176. // f.setHandler(interceptor2);
  177. f.setFilter(finalizeRemover);
  178. f.setInterfaces(new Class[] { Target3.class, Target4.class });
  179. Class c = f.createClass();
  180. Target3 obj = (Target3)c.getConstructor().newInstance();
  181. ((Proxy)obj).setHandler(interceptor2);
  182. assertEquals("OK", obj.m());
  183. System.out.println(obj.toString());
  184. assertEquals(3, interceptor2.counter);
  185. interceptor2.counter = 0;
  186. Target4 obj4 = (Target4)c.getConstructor().newInstance();
  187. ((Proxy)obj4).setHandler(interceptor2);
  188. assertEquals(3, obj4.bar4());
  189. assertEquals(3, obj4.foo4());
  190. assertEquals(2, interceptor2.counter);
  191. }
  192. public void testFilter() throws Exception {
  193. ProxyFactory f = new ProxyFactory();
  194. Interceptor2 interceptor2 = new Interceptor2();
  195. // f.setHandler(interceptor2);
  196. f.setFilter(finalizeRemover);
  197. f.setInterfaces(new Class[] { Target3.class });
  198. f.setFilter(new MethodFilter() {
  199. public boolean isHandled(Method m) {
  200. return m.getDeclaringClass() != Object.class;
  201. }
  202. });
  203. Class c = f.createClass();
  204. Target3 obj = (Target3)c.getConstructor().newInstance();
  205. ((Proxy)obj).setHandler(interceptor2);
  206. assertEquals("OK", obj.m());
  207. System.out.println(obj.toString());
  208. assertEquals(1, interceptor2.counter);
  209. }
  210. public static boolean testInitFlag;
  211. public void testInit() throws Exception {
  212. ProxyFactory f = new ProxyFactory();
  213. f.setSuperclass(TargetInit.class);
  214. MethodHandler handler = new MethodHandler() {
  215. public Object invoke(Object self, Method m,
  216. Method proceed, Object[] args) throws Exception {
  217. System.out.println("testInit " + testInitFlag);
  218. return proceed.invoke(self, args);
  219. }
  220. };
  221. testInitFlag = false;
  222. Class c = f.createClass();
  223. assertTrue(testInitFlag); // since 3.12. Before then, this line was assertFalse(testInitFlag);
  224. System.out.println("testInit createClass(): " + testInitFlag);
  225. TargetInit obj = (TargetInit)c.getConstructor().newInstance();
  226. assertTrue(testInitFlag);
  227. System.out.println("testInit newInstance(): " + testInitFlag);
  228. ((ProxyObject)obj).setHandler(handler);
  229. assertEquals("OK", obj.m());
  230. }
  231. public void testCreate() throws Exception {
  232. ProxyFactory f = new ProxyFactory();
  233. f.setSuperclass(Target5.class);
  234. Interceptor1 interceptor = new Interceptor1();
  235. // f.setHandler(interceptor);
  236. f.setFilter(finalizeRemover);
  237. Class c = f.createClass();
  238. Target5 obj = (Target5)f.create(new Class[] { int.class }, new Object[] { Integer.valueOf(3) });
  239. ((Proxy)obj).setHandler(interceptor);
  240. assertEquals(3, obj.get());
  241. }
  242. public void testBridgeMethod() throws Exception {
  243. ProxyFactory f = new ProxyFactory();
  244. f.writeDirectory = ".";
  245. f.setSuperclass(BridgeMethod.class);
  246. Interceptor1 interceptor = new Interceptor1();
  247. // f.setHandler(interceptor);
  248. f.setFilter(finalizeRemover);
  249. Class c = f.createClass();
  250. BridgeMethod obj = (BridgeMethod)c.getConstructor().newInstance();
  251. ((Proxy)obj).setHandler(interceptor);
  252. Integer value = obj.m1();
  253. assertEquals(7, value.intValue());
  254. BridgeMethodInf inf = (BridgeMethodInf)obj;
  255. Number num = inf.m1();
  256. assertEquals(7, num.intValue());
  257. BridgeMethodSuper sup = obj;
  258. try {
  259. Object x = sup.id(new Object());
  260. fail("not cast error");
  261. }
  262. catch (ClassCastException e) {}
  263. catch (Exception e) {
  264. if (e instanceof InvocationTargetException)
  265. if (e.getCause() instanceof ClassCastException)
  266. return;
  267. throw e;
  268. }
  269. }
  270. public void testGetters() throws Exception {
  271. ProxyFactory f = new ProxyFactory();
  272. Class c = ProxyTester.class;
  273. f.setSuperclass(c);
  274. assertEquals(c, f.getSuperclass());
  275. Class i = java.io.Serializable.class;
  276. f.setInterfaces(new Class[] { i });
  277. assertEquals(i, f.getInterfaces()[0]);
  278. }
  279. static class ProxyFactory2 extends ProxyFactory {
  280. public ClassLoader getClassLoader2() {
  281. return getClassLoader();
  282. }
  283. }
  284. public void testProvider() throws Exception {
  285. ProxyFactory.ClassLoaderProvider cp = ProxyFactory.classLoaderProvider;
  286. try {
  287. final ClassLoader cl = Thread.currentThread().getContextClassLoader();
  288. ProxyFactory.classLoaderProvider = new ProxyFactory.ClassLoaderProvider() {
  289. public ClassLoader get(ProxyFactory pf) {
  290. return Thread.currentThread().getContextClassLoader();
  291. }
  292. };
  293. ProxyFactory2 pf = new ProxyFactory2();
  294. assertEquals(cl, pf.getClassLoader2());
  295. }
  296. finally {
  297. ProxyFactory.classLoaderProvider = cp;
  298. }
  299. }
  300. @SuppressWarnings("deprecation")
  301. public void testCache() throws Exception {
  302. boolean prev = ProxyFactory.useCache;
  303. ProxyFactory.useCache = true;
  304. ProxyFactory f = new ProxyFactory();
  305. f.setSuperclass(Cache1.class);
  306. Class c = f.createClass();
  307. ProxyFactory f2 = new ProxyFactory();
  308. f2.setSuperclass(Cache1.class);
  309. assertEquals(c, f2.createClass());
  310. ProxyFactory f3 = new ProxyFactory();
  311. f3.setSuperclass(Cache1.class);
  312. f3.setHandler(new Interceptor1()); // deprecated
  313. assertFalse(c == f3.createClass());
  314. ProxyFactory.useCache = true;
  315. ProxyFactory f4 = new ProxyFactory();
  316. f4.setSuperclass(Cache1.class);
  317. f4.setInterfaces(new Class[] { Cache2.class });
  318. Class c4 = f4.createClass();
  319. assertFalse(c == c4);
  320. ProxyFactory f5 = new ProxyFactory();
  321. f5.setSuperclass(Cache1.class);
  322. f5.setInterfaces(new Class[] { Cache2.class });
  323. assertEquals(c4, f5.createClass());
  324. ProxyFactory f6 = new ProxyFactory();
  325. f6.setInterfaces(new Class[] { Cache2.class });
  326. assertFalse(c4 == f6.createClass());
  327. ProxyFactory.useCache = prev;
  328. }
  329. public static class Cache1 {
  330. public int foo() { return 0; }
  331. }
  332. public static interface Cache2 {
  333. public int bar();
  334. }
  335. public void testReadWrite() throws Exception {
  336. final String fileName = "read-write.bin";
  337. ProxyFactory.ClassLoaderProvider cp = ProxyFactory.classLoaderProvider;
  338. try {
  339. ProxyFactory.classLoaderProvider = new ProxyFactory.ClassLoaderProvider() {
  340. public ClassLoader get(ProxyFactory pf) {
  341. /* If javassist.Loader is returned, the super type of ReadWriteData class,
  342. * which is Serializable, is loaded by javassist.Loader as well as ReadWriteData.
  343. * This breaks the implementation of the object serializer.
  344. */
  345. // return new javassist.Loader();
  346. return Thread.currentThread().getContextClassLoader();
  347. }
  348. };
  349. ProxyFactory pf = new ProxyFactory();
  350. pf.setSuperclass(ReadWriteData.class);
  351. Object data = pf.createClass().getConstructor().newInstance();
  352. //Object data = new ReadWriteData();
  353. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
  354. oos.writeObject(data);
  355. oos.close();
  356. }
  357. finally {
  358. ProxyFactory.classLoaderProvider = cp;
  359. }
  360. ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
  361. Object data2 = ois.readObject();
  362. ois.close();
  363. int i = ((ReadWriteData)data2).foo();
  364. assertEquals(4, i);
  365. }
  366. public static class ReadWriteData implements Serializable {
  367. /** default serialVersionUID */
  368. private static final long serialVersionUID = 1L;
  369. public int foo() { return 4; }
  370. }
  371. public void testWriteReplace() throws Exception {
  372. ProxyFactory pf = new ProxyFactory();
  373. pf.setSuperclass(WriteReplace.class);
  374. Object data = pf.createClass().getConstructor().newInstance();
  375. assertEquals(data, ((WriteReplace)data).writeReplace());
  376. ProxyFactory pf2 = new ProxyFactory();
  377. pf2.setSuperclass(WriteReplace2.class);
  378. Object data2 = pf2.createClass().getConstructor().newInstance();
  379. Method meth = data2.getClass().getDeclaredMethod("writeReplace", new Class[0]);
  380. assertEquals("javassist.util.proxy.SerializedProxy",
  381. meth.invoke(data2, new Object[0]).getClass().getName());
  382. }
  383. public static class WriteReplace implements Serializable {
  384. /** default serialVersionUID */
  385. private static final long serialVersionUID = 1L;
  386. public Object writeReplace() { return this; }
  387. }
  388. public static class WriteReplace2 implements Serializable {
  389. /** default serialVersionUID */
  390. private static final long serialVersionUID = 1L;
  391. public Object writeReplace(int i) { return Integer.valueOf(i); }
  392. }
  393. public static void testJIRA189() throws Exception {
  394. Class persistentClass = Target189.PublishedArticle.class;
  395. ProxyFactory factory = new ProxyFactory();
  396. //factory.writeDirectory = ".";
  397. factory.setUseCache(false);
  398. factory.setSuperclass(persistentClass);
  399. factory.setInterfaces(new Class[] { Target189.TestProxy.class });
  400. Class cl = factory.createClass();
  401. Object obj = cl.getConstructor().newInstance();
  402. System.out.println("JIRA189:" + obj.getClass().getClassLoader() + ", " + obj.getClass().getSuperclass().getName()
  403. + ", " + Target189.PublishedArticle.class.getClassLoader());
  404. Target189.TestProxy proxy = (Target189.TestProxy)cl.getConstructor().newInstance();
  405. Target189.TestMethodHandler methodHandler = new Target189.TestMethodHandler();
  406. ((ProxyObject)proxy).setHandler(methodHandler);
  407. ((Target189.Article)proxy).getIssue();
  408. assertTrue(methodHandler.wasInvokedOnce());
  409. methodHandler.reset();
  410. Target189.PublishedArticle article = (Target189.PublishedArticle)proxy;
  411. article.getIssue();
  412. assertTrue(methodHandler.wasInvokedOnce());
  413. }
  414. public void testJIRA127() throws Exception {
  415. ProxyFactory proxyFactory = new ProxyFactory();
  416. // proxyFactory.writeDirectory = ".";
  417. proxyFactory.setInterfaces(new Class[]{ Target127.Sub.class });
  418. Target127.Sub proxy = (Target127.Sub)proxyFactory.create(new Class[0], new Object[0], new MethodHandler() {
  419. public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable {
  420. return null;
  421. }
  422. });
  423. ((Target127.Super)proxy).item(); // proxyFactory must generate a bridge method.
  424. ((Target127.Sub)proxy).item();
  425. }
  426. public static void main(String[] args) {
  427. // javassist.bytecode.ClassFile.MAJOR_VERSION = javassist.bytecode.ClassFile.JAVA_6;
  428. junit.textui.TestRunner.run(ProxyTester.class);
  429. }
  430. }