cglib3-3.1+dfsg/0000755000175000017500000000000012253447310012766 5ustar miguelmiguelcglib3-3.1+dfsg/README0000644000175000017500000000077010256200374013650 0ustar miguelmiguel CGLIB is distributed in binary and source form cglib-2.1_x.jar binary distribution, CGLIB classes only, it must be used to extend cglib classes dependant on ASM API cglib-nodep-2.1_x.jar binary distribution, CGLIB and renamed ASM classes, not extendable cglib-src-2.1_x.jar source distribution with all runtime dependancies cglib-docs-2.1_x.jar HTML API documentation Use Apache Ant to build CGLIB from source code : http://jakarta.apache.org/ant cglib3-3.1+dfsg/src/0000755000175000017500000000000012250627450013557 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/0000755000175000017500000000000012250627450014536 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/0000755000175000017500000000000012250627450015324 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/0000755000175000017500000000000012250627450015734 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/0000755000175000017500000000000012250627450017014 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/util/0000755000175000017500000000000012250627450017771 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/util/words.txt0000644000175000017500000000105707731402554021677 0ustar miguelmiguelCasuarinaceae hylomorphic granitize biddably repulsive amphimictical trio toxodont nonreigning dragbar Moronidae unlanguishing metabolizable Osmerus goran spiritfulness tetrachloromethane baobab caroline radioconductor imband crinoline circummundane incontractile forerank modernization meal fishman underbuy pertain equiped cockal unshrined Harb heterotaxis commensurableness baggy sarcophilous tankard acervuline unverifiably premidnight strangles vitellus Socratean flock scourage feverlike citharist harn cglib3-3.1+dfsg/src/test/net/sf/cglib/util/TestParallelSorter.java0000644000175000017500000000660310066633122024430 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import net.sf.cglib.CodeGenTestCase; import java.io.*; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: TestParallelSorter.java,v 1.4 2004/06/24 21:15:13 herbyderby Exp $ */ public class TestParallelSorter extends CodeGenTestCase { public void testSorts() throws Throwable { Object[] data1 = getTestData(); Object[] data2 = copy(data1); Object[] data3 = copy(data1); int[] idx1 = getIndexes(data1.length); int[] idx2 = getIndexes(data1.length); int[] idx3 = getIndexes(data1.length); ParallelSorter p1 = ParallelSorter.create(new Object[]{ data1, idx1 }); ParallelSorter p2 = ParallelSorter.create(new Object[]{ data2, idx2 }); p1.quickSort(0); p2.mergeSort(0); compare(data1, data2); compare(idx1, idx2); p1.quickSort(1); compare(idx1, idx3); compare(data1, data3); } private void compare(Object[] data1, Object[] data2) { assertTrue(data1.length == data2.length); for (int i = 0; i < data1.length; i++) { assertTrue(data1[i].equals(data2[i])); } } private void compare(int[] data1, int[] data2) { assertTrue(data1.length == data2.length); for (int i = 0; i < data1.length; i++) { assertTrue(data1[i] == data2[i]); } } private int[] getIndexes(int len) { int[] idx = new int[len]; for (int i = 0; i < len; i++) { idx[i] = i; } return idx; } private Object[] getTestData() throws IOException { InputStream in = getClass().getResourceAsStream("words.txt"); BufferedReader r = new BufferedReader(new InputStreamReader(in)); List list = new ArrayList(); String line; int c = 0; while ((line = r.readLine()) != null) { list.add(line); if (c++ == 20) break; } return list.toArray(); } private Object[] copy(Object[] data) { Object[] copy = new Object[data.length]; System.arraycopy(data, 0, copy, 0, data.length); return copy; } public TestParallelSorter(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestParallelSorter.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/util/TestXmlParsing.java0000644000175000017500000002470510066633122023564 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import net.sf.cglib.CodeGenTestCase; import junit.framework.*; public class TestXmlParsing extends CodeGenTestCase { private static final String ATTRIBUTE_STR = "attribute"; private static final String ATTRIBUTE_DIRECTIVE_STR = "directive.attribute"; private static final String BODY_STR = "body"; private static final String DECLARATION_STR = "declaration"; private static final String DOBODY_STR = "doBody"; private static final String ELEMENT_STR = "element"; private static final String FALLBACK_STR = "fallback"; private static final String FORWARD_STR = "forward"; private static final String GET_PROPERTY_STR = "getProperty"; private static final String INCLUDE_STR = "include"; private static final String INCLUDE_DIRECTIVE_STR = "directive.include"; private static final String INVOKE_STR = "invoke"; private static final String OUTPUT_STR = "output"; private static final String PAGE_DIRECTIVE_STR = "directive.page"; private static final String PARAMS_STR = "params"; private static final String PARAM_STR = "param"; private static final String PLUGIN_STR = "plugin"; private static final String ROOT_STR = "root"; private static final String SET_PROPERTY_STR = "setProperty"; private static final String TAG_DIRECTIVE_STR = "directive.tag"; private static final String TEXT_STR = "text"; private static final String USE_BEAN_STR = "useBean"; private static final String VARIABLE_DIRECTIVE_STR = "variable"; private static final int ATTRIBUTE_IDX = 0; private static final int ATTRIBUTE_DIRECTIVE_IDX = 1; private static final int BODY_IDX = 2; private static final int DECLARATION_IDX = 3; private static final int DOBODY_IDX = 4; private static final int ELEMENT_IDX = 5; private static final int FALLBACK_IDX = 6; private static final int FORWARD_IDX = 7; private static final int GET_PROPERTY_IDX = 8; private static final int INCLUDE_IDX = 9; private static final int INCLUDE_DIRECTIVE_IDX = 10; private static final int INVOKE_IDX = 11; private static final int OUTPUT_IDX = 12; private static final int PAGE_DIRECTIVE_IDX = 13; private static final int PARAMS_IDX = 14; private static final int PARAM_IDX = 15; private static final int PLUGIN_IDX = 16; private static final int ROOT_IDX = 17; private static final int SET_PROPERTY_IDX = 18; private static final int TAG_DIRECTIVE_IDX = 19; private static final int TEXT_IDX = 20; private static final int USE_BEAN_IDX = 21; private static final int VARIABLE_DIRECTIVE_IDX = 22; private static final String[] M1 = { ATTRIBUTE_STR, ATTRIBUTE_DIRECTIVE_STR, BODY_STR, DECLARATION_STR, DOBODY_STR, ELEMENT_STR, FALLBACK_STR, FORWARD_STR, GET_PROPERTY_STR, INCLUDE_STR, INCLUDE_DIRECTIVE_STR, INVOKE_STR, OUTPUT_STR, PAGE_DIRECTIVE_STR, PARAMS_STR, PARAM_STR, PLUGIN_STR, ROOT_STR, SET_PROPERTY_STR, TAG_DIRECTIVE_STR, TEXT_STR, USE_BEAN_STR, VARIABLE_DIRECTIVE_STR }; private static final int[] M2 = { ATTRIBUTE_IDX, ATTRIBUTE_DIRECTIVE_IDX, BODY_IDX, DECLARATION_IDX, DOBODY_IDX, ELEMENT_IDX, FALLBACK_IDX, FORWARD_IDX, GET_PROPERTY_IDX, INCLUDE_IDX, INCLUDE_DIRECTIVE_IDX, INVOKE_IDX, OUTPUT_IDX, PAGE_DIRECTIVE_IDX, PARAMS_IDX, PARAM_IDX, PLUGIN_IDX, ROOT_IDX, SET_PROPERTY_IDX, TAG_DIRECTIVE_IDX, TEXT_IDX, USE_BEAN_IDX, VARIABLE_DIRECTIVE_IDX }; private static final StringSwitcher SWITCHER = StringSwitcher.create(M1, M2, true); public int switcher(String s) { return SWITCHER.intValue(s); } public int interned(String s) { if (s == ATTRIBUTE_STR) { return ATTRIBUTE_IDX; } else if (s == ATTRIBUTE_DIRECTIVE_STR) { return ATTRIBUTE_DIRECTIVE_IDX; } else if (s == BODY_STR) { return BODY_IDX; } else if (s == DECLARATION_STR) { return DECLARATION_IDX; } else if (s == DOBODY_STR) { return DOBODY_IDX; } else if (s == ELEMENT_STR) { return ELEMENT_IDX; } else if (s == FALLBACK_STR) { return FALLBACK_IDX; } else if (s == FORWARD_STR) { return FORWARD_IDX; } else if (s == GET_PROPERTY_STR) { return GET_PROPERTY_IDX; } else if (s == INCLUDE_STR) { return INCLUDE_IDX; } else if (s == INCLUDE_DIRECTIVE_STR) { return INCLUDE_DIRECTIVE_IDX; } else if (s == INVOKE_STR) { return INVOKE_IDX; } else if (s == OUTPUT_STR) { return OUTPUT_IDX; } else if (s == PAGE_DIRECTIVE_STR) { return PAGE_DIRECTIVE_IDX; } else if (s == PARAMS_STR) { return PARAMS_IDX; } else if (s == PARAM_STR) { return PARAM_IDX; } else if (s == PLUGIN_STR) { return PLUGIN_IDX; } else if (s == ROOT_STR) { return ROOT_IDX; } else if (s == SET_PROPERTY_STR) { return SET_PROPERTY_IDX; } else if (s == TAG_DIRECTIVE_STR) { return TAG_DIRECTIVE_IDX; } else if (s == TEXT_STR) { return TEXT_IDX; } else if (s == USE_BEAN_STR) { return USE_BEAN_IDX; } else if (s == VARIABLE_DIRECTIVE_STR) { return VARIABLE_DIRECTIVE_IDX; } return -1; } public int elseIf(String s) { if (s.equals(ATTRIBUTE_STR)) { return ATTRIBUTE_IDX; } else if (s.equals(ATTRIBUTE_DIRECTIVE_STR)) { return ATTRIBUTE_DIRECTIVE_IDX; } else if (s.equals(BODY_STR)) { return BODY_IDX; } else if (s.equals(DECLARATION_STR)) { return DECLARATION_IDX; } else if (s.equals(DOBODY_STR)) { return DOBODY_IDX; } else if (s.equals(ELEMENT_STR)) { return ELEMENT_IDX; } else if (s.equals(FALLBACK_STR)) { return FALLBACK_IDX; } else if (s.equals(FORWARD_STR)) { return FORWARD_IDX; } else if (s.equals(GET_PROPERTY_STR)) { return GET_PROPERTY_IDX; } else if (s.equals(INCLUDE_STR)) { return INCLUDE_IDX; } else if (s.equals(INCLUDE_DIRECTIVE_STR)) { return INCLUDE_DIRECTIVE_IDX; } else if (s.equals(INVOKE_STR)) { return INVOKE_IDX; } else if (s.equals(OUTPUT_STR)) { return OUTPUT_IDX; } else if (s.equals(PAGE_DIRECTIVE_STR)) { return PAGE_DIRECTIVE_IDX; } else if (s.equals(PARAMS_STR)) { return PARAMS_IDX; } else if (s.equals(PARAM_STR)) { return PARAM_IDX; } else if (s.equals(PLUGIN_STR)) { return PLUGIN_IDX; } else if (s.equals(ROOT_STR)) { return ROOT_IDX; } else if (s.equals(SET_PROPERTY_STR)) { return SET_PROPERTY_IDX; } else if (s.equals(TAG_DIRECTIVE_STR)) { return TAG_DIRECTIVE_IDX; } else if (s.equals(TEXT_STR)) { return TEXT_IDX; } else if (s.equals(USE_BEAN_STR)) { return USE_BEAN_IDX; } else if (s.equals(VARIABLE_DIRECTIVE_STR)) { return VARIABLE_DIRECTIVE_IDX; } return -1; } public void testStartElement() throws Throwable { int numWords = 10000; int reps = 1000; String[] words = new String[numWords]; String[] interned = new String[numWords]; for (int i = 0; i < words.length; i++) { interned[i] = M1[(int)(Math.random() * M1.length)].intern(); words[i] = new String(interned[i]); } long total1 = 0; long total2 = 0; long total3 = 0; // warm-up for (int i = 0; i < reps; i++) { for (int j = 0; j < numWords; j++) { total1 += elseIf(words[j]); total2 += interned(interned[j]); total3 += switcher(words[j]); } } if (total1 != total2 || total1 != total3) { fail("totals are not equal"); } long t0 = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { for (int j = 0; j < numWords; j++) { elseIf(words[j]); } } long t1 = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { for (int j = 0; j < numWords; j++) { interned(interned[j]); } } long t2 = System.currentTimeMillis(); for (int i = 0; i < reps; i++) { for (int j = 0; j < numWords; j++) { switcher(words[j]); } } long t3 = System.currentTimeMillis(); System.err.println("elseif: " + (t1 - t0) + "ms"); System.err.println("intern: " + (t2 - t1) + "ms"); System.err.println("switch: " + (t3 - t2) + "ms"); } public TestXmlParsing(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestXmlParsing.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/TestGenerator.java0000644000175000017500000000247010066633126022450 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib; import net.sf.cglib.core.AbstractClassGenerator; import net.sf.cglib.core.ReflectUtils; abstract public class TestGenerator extends AbstractClassGenerator { private static int counter; public TestGenerator(Source source) { super(source); } protected ClassLoader getDefaultClassLoader() { return null; } protected Object firstInstance(Class type) throws Exception { return ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) throws Exception { return instance; } public Object create() { return create(new Integer(counter++)); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/TestAll.java0000644000175000017500000000663210162421562021232 0ustar miguelmiguel/* * Copyright 2002,2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib; import junit.framework.*; import net.sf.cglib.beans.*; import net.sf.cglib.core.*; import net.sf.cglib.proxy.*; import net.sf.cglib.reflect.*; import net.sf.cglib.transform.*; import net.sf.cglib.transform.impl.*; import net.sf.cglib.util.*; /** *@author Gerhard Froehlich * g-froehlich@gmx.de *@version $Id: TestAll.java,v 1.66 2004/12/23 03:46:25 herbyderby Exp $ */ public class TestAll extends TestCase { public static String DEFAULT_DEBUG_LOACATION = System.getProperty("user.home") + System.getProperty("file.separator") + "cglib-debug"; public TestAll(String testName) { super(testName); } public static Test suite() throws Exception{ System.getProperties().list(System.out); TestSuite suite = new TestSuite(); //security // proxy suite.addTest(TestEnhancer.suite()); suite.addTest(TestProxy.suite()); suite.addTest(TestDispatcher.suite()); suite.addTest(TestProxyRefDispatcher.suite()); suite.addTest(TestLazyLoader.suite()); suite.addTest(TestNoOp.suite()); suite.addTest(TestMixin.suite()); suite.addTest(TestInterfaceMaker.suite()); // beans suite.addTest(TestBulkBean.suite()); suite.addTest(TestBeanMap.suite()); suite.addTest(TestImmutableBean.suite()); suite.addTest(TestBeanCopier.suite()); suite.addTest(TestBeanGenerator.suite()); // reflect suite.addTest(TestDelegates.suite()); suite.addTest(TestFastClass.suite()); // core suite.addTest(TestKeyFactory.suite()); suite.addTest(TestTinyBitSet.suite()); // util suite.addTest(TestParallelSorter.suite()); // transform suite.addTest(TestTransformingLoader.suite()); suite.addTest(TestAddClassInit.suite()); suite.addTest(TestProvideFields.suite()); suite.addTest(TestAddDelegate.suite()); suite.addTest(TestInterceptFields.suite()); suite.addTest(TestDemo.suite()); // performance // suite.addTest(TestReflectPerf.suite()); // suite.addTest(TestXmlParsing.suite()); return suite; } public static void main(String args[])throws Exception { if(System.getProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY) == null){ System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,DEFAULT_DEBUG_LOACATION); } String[] testCaseName = {TestAll.class.getName()}; junit.textui.TestRunner.main(testCaseName); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/0000755000175000017500000000000012250627450020175 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/D1.java0000644000175000017500000000016707747615702021324 0ustar miguelmiguelpackage net.sf.cglib.proxy; class D1 implements DI1 { public String herby() { return "D1"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DI1.java0000644000175000017500000000012607747615702021430 0ustar miguelmiguelpackage net.sf.cglib.proxy; public interface DI1 { public String herby(); } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/EB.java0000644000175000017500000000041107747615702021336 0ustar miguelmiguelpackage net.sf.cglib.proxy; public class EB extends EA implements Comparable{ private int count; public int getCount() { return count; } public void setCount(int count) { this.count = count; } public final void finalTest(){} } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DBean1.java0000644000175000017500000000027510005022346022063 0ustar miguelmiguelpackage net.sf.cglib.proxy; class DBean1 implements DI1 { public String getName() { return "Chris"; } public String herby() { return "Herby"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestInterfaceMaker.java0000644000175000017500000000466310402432046024561 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.*; import junit.framework.*; import net.sf.cglib.CodeGenTestCase; public class TestInterfaceMaker extends CodeGenTestCase { public void testStandalone() throws Exception { InterfaceMaker im = new InterfaceMaker(); im.add(D1.class); im.add(D2.class); Class iface = im.create(); Method[] methods = iface.getMethods(); assertTrue(methods.length == 2); String name1 = methods[0].getName(); String name2 = methods[1].getName(); assertTrue(("herby".equals(name1) && "derby".equals(name2)) || ("herby".equals(name2) && "derby".equals(name1))); } public void testEnhancer() throws Exception { InterfaceMaker im = new InterfaceMaker(); im.add(D1.class); im.add(D2.class); Class iface = im.create(); Object obj = Enhancer.create(Object.class, new Class[]{ iface }, new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { return "test"; } }); Method method = obj.getClass().getMethod("herby", (Class[])null); assertTrue("test".equals(method.invoke(obj, (Object[])null))); } public TestInterfaceMaker(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestInterfaceMaker.class); } public static void main(String args[]) { String[] testCaseName = {TestInterfaceMaker.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DBean2.java0000644000175000017500000000015007747615702022103 0ustar miguelmiguelpackage net.sf.cglib.proxy; class DBean2 { public int getAge() { return 18; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestLazyLoader.java0000644000175000017500000000320010066633124023737 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.lang.reflect.*; import java.util.*; import junit.framework.*; public class TestLazyLoader extends CodeGenTestCase { public void testLazyLoader() { LazyLoader loader = new LazyLoader() { public Object loadObject() { System.err.println("loading object"); return "foo"; } }; Object obj = Enhancer.create(Object.class, loader); assertTrue("foo".equals(obj.toString())); } public TestLazyLoader(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestLazyLoader.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/EC2.java0000644000175000017500000000034107747615702021423 0ustar miguelmiguelpackage net.sf.cglib.proxy; public class EC2 extends EB { private String address; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/D4.java0000644000175000017500000000037407747615702021327 0ustar miguelmiguelpackage net.sf.cglib.proxy; class D4 implements DI1, DI3 { public String herby() { return "D4"; } public String derby() { return "D4"; } public String extra() { return "D4"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/D2.java0000644000175000017500000000016707747615702021325 0ustar miguelmiguelpackage net.sf.cglib.proxy; class D2 implements DI2 { public String derby() { return "D2"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DI2.java0000644000175000017500000000012607747615702021431 0ustar miguelmiguelpackage net.sf.cglib.proxy; public interface DI2 { public String derby(); } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestProxy.java0000644000175000017500000001566112250620402023020 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import net.sf.cglib.proxysample.ProxySampleInterface_ReturnsBasic; import junit.framework.*; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: TestProxy.java,v 1.6 2012/07/27 16:02:49 baliuka Exp $ */ public class TestProxy extends CodeGenTestCase { private class SimpleInvocationHandler implements InvocationHandler { Object o = null; public SimpleInvocationHandler(Object o) { this.o = o; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { System.out.println("invoking " + m + " on " + o + " with " + args); Object r = m.invoke(o, args); System.out.println("done: " + m + " on " + o + " with " + args + ", result is " + r); return r; } } public void testGetProxyClassAndConstructor() throws Exception { HashMap map = new HashMap(); map.put("test", "test"); InvocationHandler handler = new SimpleInvocationHandler(map); Class proxyClass = Proxy.getProxyClass(TestProxy.class.getClassLoader(), new Class[] { Map.class }); Map proxyMap = (Map) proxyClass.getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler }); assertEquals("proxy delegation not correct", map.get("test"), proxyMap.get("test")); } public void testGetProxyInstance() throws Exception { HashMap map = new HashMap(); map.put("test", "test"); InvocationHandler handler = new SimpleInvocationHandler(map); Map proxyMap = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { Map.class }, handler); assertEquals("proxy delegation not correct", map.get("test"), proxyMap.get("test")); } public void testIsProxyClass() throws Exception { HashMap map = new HashMap(); map.put("test", "test"); InvocationHandler handler = new SimpleInvocationHandler(map); Map proxyMap = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { Map.class }, handler); assertTrue("real proxy not accepted", Proxy.isProxyClass(proxyMap.getClass())); } private class FakeProxy extends Proxy { public FakeProxy(InvocationHandler ih) { super(ih); } } public void testIsNotProxyClass() throws Exception { assertTrue("fake proxy accepted as real", !Proxy.isProxyClass(FakeProxy.class)); } private static class ReturnNullHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return null; } } public void testReturnNull() throws Exception { System.err.println("hello"); ProxySampleInterface_ReturnsBasic rb = (ProxySampleInterface_ReturnsBasic) Proxy.newProxyInstance(null, new Class[]{ ProxySampleInterface_ReturnsBasic.class }, new ReturnNullHandler()); try { int result = rb.getKala(11); fail("must throw an exception, but returned " + result); } catch (NullPointerException ignore) { } } public void testGetInvocationHandler() throws Exception { HashMap map = new HashMap(); map.put("test", "test"); InvocationHandler handler = new InvocationHandler() { public Object invoke(Object o, Method method, Object[] args) throws Exception { throw new Exception("test!"); } }; Map proxyMap = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { Map.class }, handler); assertSame("should be the same handler", handler, Proxy.getInvocationHandler(proxyMap)); } public void testException() throws Exception { HashMap map = new HashMap(); map.put("test", "test"); InvocationHandler handler = new InvocationHandler() { public Object invoke(Object o, Method method, Object[] args) throws Exception { throw new Exception("test!"); } }; Map proxyMap = (Map) Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { Map.class }, handler); try { proxyMap.get("test"); //should throw exception fail("proxy exception handling not correct, should throw exception"); } catch (UndeclaredThrowableException e) { System.out.println("exception: " + e); } catch (Exception e) { fail("proxy exception handling not correct, threw wrong exception: " + e); } } public void testEquals() throws Exception { final Object k1 = new Object(); final Object k2 = new Object(); InvocationHandler handler = new InvocationHandler() { public Object invoke(Object o, Method method, Object[] args) throws Exception { if (method.getName().equals("equals")) { return (args[0] == k1) ? Boolean.TRUE : Boolean.FALSE; } return null; } }; Object proxy = Proxy.newProxyInstance(TestProxy.class.getClassLoader(), new Class[] { Map.class }, handler); assertTrue(proxy.equals(k1)); assertTrue(!proxy.equals(k2)); } public TestProxy(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestProxy.class); } public void perform(ClassLoader loader) throws Throwable { InvocationHandler handler = new InvocationHandler() { public Object invoke(Object o, Method method, Object[] args) throws Exception { throw new Exception("test!"); } }; Proxy.newProxyInstance(loader, new Class[] { Map.class }, handler); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/Source.java0000644000175000017500000000540610066633126022305 0ustar miguelmiguel/* * Copyright 2002,2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; public abstract class Source implements java.io.Serializable{ public static class CheckedException extends Exception{} public static class UndeclaredException extends Exception{} public String toString(){ return ""; } public Source() { } public void callAll(){ protectedMethod(); packageMethod(); abstractMethod(); synchronizedMethod(); finalMethod(); intType(1); longType(1L); floatType(1f); doubleType(1.0); objectType("1") ; voidType(); multiArg(1,1,1,1,"","",""); } protected void protectedMethod(){} void packageMethod(){} abstract void abstractMethod(); public void throwChecked()throws CheckedException{ throw new CheckedException(); } public void throwIndexOutOfBoundsException(){ throw new IndexOutOfBoundsException(); } public void throwAbstractMethodError(){ throw new AbstractMethodError(); } public synchronized void synchronizedMethod(){} public final void finalMethod(){ } public int intType(int val){ return val; } public long longType(long val){ return val; } public double doubleType(double val){ return val; } public float floatType(float val){ return val; } public boolean booleanType(boolean val){ return val; } public short shortType(short val){ return val; } public char charType(char val){ return val; } public byte byteType(byte val){ return val; } public int [] arrayType(int val[]){ return val; } public String [] arrayType(String val[]){ return val; } public Object objectType(Object val){ return val; } public void voidType(){ } public void multiArg( int arg1, long arg2, double arg3, float arg4, Object arg5, Object arg6, Object arg7 ){ } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/EC1.java0000644000175000017500000000054507747615702021430 0ustar miguelmiguelpackage net.sf.cglib.proxy; public class EC1 extends EB implements Comparable{ private String address; private ED ed; public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public ED getED() { return ed; } public void setED(ED ed) { this.ed = ed; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DI3.java0000644000175000017500000000013307747615702021430 0ustar miguelmiguelpackage net.sf.cglib.proxy; interface DI3 extends DI2 { public String extra(); } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/D3.java0000644000175000017500000000020207747615702021314 0ustar miguelmiguelpackage net.sf.cglib.proxy; class D3 extends D2 implements DI3 { public String extra() { return "D3"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestProxyRefDispatcher.java0000644000175000017500000000656610156243314025476 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.beans.*; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; /** * @author Chris Nokleberg, Bob Lee * @version $Id: TestProxyRefDispatcher.java,v 1.1 2004/12/10 08:48:43 herbyderby Exp $ */ public class TestProxyRefDispatcher extends CodeGenTestCase { interface Foo { String foo(); } interface Bar { String bar(); } public void testSimple() throws Exception { final Object[] impls = new Object[]{ new Foo() { public String foo() { return "foo1"; } }, new Bar() { public String bar() { return "bar1"; } } }; final Object[] proxyReference = new Object[1]; Callback[] callbacks = new Callback[]{ new ProxyRefDispatcher() { public Object loadObject(Object proxy) { proxyReference[0] = proxy; return impls[0]; } }, new ProxyRefDispatcher() { public Object loadObject(Object proxy) { proxyReference[0] = proxy; return impls[1]; } } }; Enhancer e = new Enhancer(); e.setInterfaces(new Class[]{ Foo.class, Bar.class }); e.setCallbacks(callbacks); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return (method.getDeclaringClass().equals(Foo.class)) ? 0 : 1; } }); Object obj = e.create(); assertNull(proxyReference[0]); assertTrue(((Foo)obj).foo().equals("foo1")); assertSame(obj, proxyReference[0]); proxyReference[0] = null; assertTrue(((Bar)obj).bar().equals("bar1")); assertSame(obj, proxyReference[0]); proxyReference[0] = null; impls[0] = new Foo() { public String foo() { return "foo2"; } }; assertTrue(((Foo)obj).foo().equals("foo2")); assertSame(obj, proxyReference[0]); } public TestProxyRefDispatcher(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestProxyRefDispatcher.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestDispatcher.java0000644000175000017500000000563010066633126023772 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.beans.*; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; /** * @author Chris Nokleberg * @version $Id: TestDispatcher.java,v 1.6 2004/06/24 21:15:17 herbyderby Exp $ */ public class TestDispatcher extends CodeGenTestCase { interface Foo { String foo(); } interface Bar { String bar(); } public void testSimple() throws Exception { final Object[] impls = new Object[]{ new Foo() { public String foo() { return "foo1"; } }, new Bar() { public String bar() { return "bar1"; } } }; Callback[] callbacks = new Callback[]{ new Dispatcher() { public Object loadObject() { return impls[0]; } }, new Dispatcher() { public Object loadObject() { return impls[1]; } } }; Enhancer e = new Enhancer(); e.setInterfaces(new Class[]{ Foo.class, Bar.class }); e.setCallbacks(callbacks); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return (method.getDeclaringClass().equals(Foo.class)) ? 0 : 1; } }); Object obj = e.create(); assertTrue(((Foo)obj).foo().equals("foo1")); assertTrue(((Bar)obj).bar().equals("bar1")); impls[0] = new Foo() { public String foo() { return "foo2"; } }; assertTrue(((Foo)obj).foo().equals("foo2")); } public TestDispatcher(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestDispatcher.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestMixin.java0000644000175000017500000001146712250620402022763 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.beans.*; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; /** * @author Chris Nokleberg * @version $Id: TestMixin.java,v 1.6 2012/07/27 16:02:49 baliuka Exp $ */ public class TestMixin extends CodeGenTestCase { public void testSimple() throws Exception { Object obj = Mixin.create(new Class[]{ DI1.class, DI2.class }, new Object[]{ new D1(), new D2() }); assertTrue(((DI1)obj).herby().equals("D1")); assertTrue(((DI2)obj).derby().equals("D2")); } public void testDetermineInterfaces() throws Exception { Object obj = Mixin.create(new Object[]{ new D1(), new D2() }); assertTrue(((DI1)obj).herby().equals("D1")); assertTrue(((DI2)obj).derby().equals("D2")); } public void testOverride() throws Exception { Object obj = Mixin.create(new Object[]{ new D1(), new D4() }); assertTrue(((DI1)obj).herby().equals("D1")); assertTrue(((DI2)obj).derby().equals("D4")); } public void testNonOverride() throws Exception { Object obj = Mixin.create(new Object[]{ new D4(), new D1() }); assertTrue(((DI1)obj).herby().equals("D4")); assertTrue(((DI2)obj).derby().equals("D4")); } public void testSubclass() throws Exception { Object obj = Mixin.create(new Object[]{ new D3(), new D1() }); assertTrue(((DI1)obj).herby().equals("D1")); assertTrue(((DI2)obj).derby().equals("D2")); assertTrue(((DI3)obj).extra().equals("D3")); } public void testBeans() throws Exception { Object obj = Mixin.createBean(new Object[]{ new DBean1(), new DBean2() }); Set getters = getGetters(obj.getClass()); assertTrue(getters.size() == 3); // name, age, class assertTrue(getters.contains("name")); assertTrue(getters.contains("age")); assertTrue(!(obj instanceof DI1)); } public void testEverything() throws Exception { Mixin.Generator gen = new Mixin.Generator(); gen.setStyle(Mixin.STYLE_EVERYTHING); gen.setDelegates(new Object[]{ new DBean1(), new DBean2() }); Object obj = gen.create(); Set getters = getGetters(obj.getClass()); assertTrue(getters.size() == 3); // name, age, class assertTrue(obj instanceof DI1); assertTrue(new DBean1().herby().equals(((DI1)obj).herby())); } public void testNullDelegates() throws Exception { Mixin.Generator gen = new Mixin.Generator(); gen.setStyle(Mixin.STYLE_BEANS); gen.setClasses(new Class[]{ DBean1.class, DBean2.class }); Mixin mixin = gen.create(); Object obj = mixin.newInstance(new Object[]{ new DBean1(), new DBean2() }); } private static Set getGetters(Class beanClass) throws Exception { Set getters = new HashSet(); PropertyDescriptor[] descriptors = Introspector.getBeanInfo(beanClass).getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { if (descriptors[i].getReadMethod() != null) { getters.add(descriptors[i].getName()); } } return getters; } private static PropertyDescriptor getProperty(Class beanClass, String property) throws Exception { Set getters = new HashSet(); PropertyDescriptor[] descriptors = Introspector.getBeanInfo(beanClass).getPropertyDescriptors(); for (int i = 0; i < descriptors.length; i++) { if (descriptors[i].getName().equals(property)) return descriptors[i]; } return null; } public TestMixin(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestMixin.class); } public void perform(ClassLoader loader) throws Throwable { Mixin.createBean(loader, new Object[]{ new DBean1(), new DBean2() }); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestEnhancer.java0000644000175000017500000011344512250620402023421 0ustar miguelmiguel/* * Copyright 2002,2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.io.*; import java.lang.reflect.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import junit.framework.*; import net.sf.cglib.CodeGenTestCase; import net.sf.cglib.core.DefaultNamingPolicy; import net.sf.cglib.core.ReflectUtils; import net.sf.cglib.reflect.FastClass; /** *@author Juozas Baliuka * baliuka@mwm.lt *@version $Id: TestEnhancer.java,v 1.58 2012/07/27 16:02:49 baliuka Exp $ */ public class TestEnhancer extends CodeGenTestCase { private static final MethodInterceptor TEST_INTERCEPTOR = new TestInterceptor(); private static final Class [] EMPTY_ARG = new Class[]{}; private boolean invokedProtectedMethod = false; private boolean invokedPackageMethod = false; private boolean invokedAbstractMethod = false; public TestEnhancer(String testName) { super(testName); } public static Test suite() { return new TestSuite(TestEnhancer.class); } public static void main(String args[]) { String[] testCaseName = {TestEnhancer.class.getName()}; junit.textui.TestRunner.main(testCaseName); } public void testEnhance()throws Throwable{ java.util.Vector vector1 = (java.util.Vector)Enhancer.create( java.util.Vector.class, new Class[]{java.util.List.class}, TEST_INTERCEPTOR ); java.util.Vector vector2 = (java.util.Vector)Enhancer.create( java.util.Vector.class, new Class[]{java.util.List.class}, TEST_INTERCEPTOR ); assertTrue("Cache failed",vector1.getClass() == vector2.getClass()); } public void testMethods()throws Throwable{ MethodInterceptor interceptor = new TestInterceptor(){ public Object afterReturn( Object obj, Method method, Object args[], boolean invokedSuper, Object retValFromSuper, java.lang.Throwable e )throws java.lang.Throwable{ int mod = method.getModifiers(); if( Modifier.isProtected( mod ) ){ invokedProtectedMethod = true; } if( Modifier.isAbstract(mod) ){ invokedAbstractMethod = true; } if( ! ( Modifier.isProtected( mod ) || Modifier.isPublic( mod ) )){ invokedPackageMethod = true; } return retValFromSuper;//return the same as supper } }; Source source = (Source)Enhancer.create( Source.class, null,interceptor ); source.callAll(); assertTrue("protected", invokedProtectedMethod ); assertTrue("package", invokedPackageMethod ); assertTrue("abstract", invokedAbstractMethod ); } public void testEnhanced()throws Throwable{ Source source = (Source)Enhancer.create( Source.class, null, TEST_INTERCEPTOR ); TestCase.assertTrue("enhance", Source.class != source.getClass() ); } public void testEnhanceObject() throws Throwable { EA obj = new EA(); EA save = obj; obj.setName("herby"); EA proxy = (EA)Enhancer.create( EA.class, new DelegateInterceptor(save) ); assertTrue(proxy.getName().equals("herby")); Factory factory = (Factory)proxy; assertTrue(((EA)factory.newInstance(factory.getCallbacks())).getName().equals("herby")); } class DelegateInterceptor implements MethodInterceptor { Object delegate; DelegateInterceptor(Object delegate){ this.delegate = delegate; } public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable { return proxy.invoke(delegate,args); } } public void testEnhanceObjectDelayed() throws Throwable { DelegateInterceptor mi = new DelegateInterceptor(null); EA proxy = (EA)Enhancer.create( EA.class, mi); EA obj = new EA(); obj.setName("herby"); mi.delegate = obj; assertTrue(proxy.getName().equals("herby")); } public void testTypes()throws Throwable{ Source source = (Source)Enhancer.create( Source.class, null, TEST_INTERCEPTOR ); TestCase.assertTrue("intType", 1 == source.intType(1)); TestCase.assertTrue("longType", 1L == source.longType(1L)); TestCase.assertTrue("floatType", 1.1f == source.floatType(1.1f)); TestCase.assertTrue("doubleType",1.1 == source.doubleType(1.1)); TestCase.assertEquals("objectType","1", source.objectType("1") ); TestCase.assertEquals("objectType","", source.toString() ); source.arrayType( new int[]{} ); } public void testModifiers()throws Throwable{ Source source = (Source)Enhancer.create( Source.class, null, TEST_INTERCEPTOR ); Class enhancedClass = source.getClass(); assertTrue("isProtected" , Modifier.isProtected( enhancedClass.getDeclaredMethod("protectedMethod", EMPTY_ARG ).getModifiers() )); int mod = enhancedClass.getDeclaredMethod("packageMethod", EMPTY_ARG ).getModifiers() ; assertTrue("isPackage" , !( Modifier.isProtected(mod)|| Modifier.isPublic(mod) ) ); //not sure about this (do we need it for performace ?) assertTrue("isFinal" , Modifier.isFinal( mod ) ); mod = enhancedClass.getDeclaredMethod("synchronizedMethod", EMPTY_ARG ).getModifiers() ; assertTrue("isSynchronized" , !Modifier.isSynchronized( mod ) ); } public void testObject()throws Throwable{ Object source = Enhancer.create( null, null, TEST_INTERCEPTOR ); assertTrue("parent is object", source.getClass().getSuperclass() == Object.class ); } public void testSystemClassLoader()throws Throwable{ Object source = enhance( null, null, TEST_INTERCEPTOR , ClassLoader.getSystemClassLoader()); source.toString(); assertTrue("SystemClassLoader", source.getClass().getClassLoader() == ClassLoader.getSystemClassLoader() ); } public void testCustomClassLoader()throws Throwable{ ClassLoader custom = new ClassLoader(this.getClass().getClassLoader()){}; Object source = enhance( null, null, TEST_INTERCEPTOR, custom); source.toString(); assertTrue("Custom classLoader", source.getClass().getClassLoader() == custom ); custom = new ClassLoader(){}; source = enhance( null, null, TEST_INTERCEPTOR, custom); source.toString(); assertTrue("Custom classLoader", source.getClass().getClassLoader() == custom ); } public void testRuntimException()throws Throwable{ Source source = (Source)Enhancer.create( Source.class, null, TEST_INTERCEPTOR ); try{ source.throwIndexOutOfBoundsException(); fail("must throw an exception"); }catch( IndexOutOfBoundsException ok ){ } } static abstract class CastTest{ CastTest(){} abstract int getInt(); } class CastTestInterceptor implements MethodInterceptor{ public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable { return new Short((short)0); } } public void testCast()throws Throwable{ CastTest castTest = (CastTest)Enhancer.create(CastTest.class, null, new CastTestInterceptor()); assertTrue(castTest.getInt() == 0); } public void testABC() throws Throwable{ Enhancer.create(EA.class, null, TEST_INTERCEPTOR); Enhancer.create(EC1.class, null, TEST_INTERCEPTOR).toString(); ((EB)Enhancer.create(EB.class, null, TEST_INTERCEPTOR)).finalTest(); assertTrue("abstract method",( (EC1)Enhancer.create(EC1.class, null, TEST_INTERCEPTOR) ).compareTo( new EC1() ) == -1 ); Enhancer.create(ED.class, null, TEST_INTERCEPTOR).toString(); Enhancer.create(ClassLoader.class, null, TEST_INTERCEPTOR).toString(); } public static class AroundDemo { public String getFirstName() { return "Chris"; } public String getLastName() { return "Nokleberg"; } } public void testAround() throws Throwable { AroundDemo demo = (AroundDemo)Enhancer.create(AroundDemo.class, null, new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getName().equals("getFirstName")) { return "Christopher"; } return proxy.invokeSuper(obj, args); } }); assertTrue(demo.getFirstName().equals("Christopher")); assertTrue(demo.getLastName().equals("Nokleberg")); } public static interface TestClone extends Cloneable{ public Object clone()throws java.lang.CloneNotSupportedException; } public static class TestCloneImpl implements TestClone{ public Object clone()throws java.lang.CloneNotSupportedException{ return super.clone(); } } public void testClone() throws Throwable{ TestClone testClone = (TestClone)Enhancer.create( TestCloneImpl.class, TEST_INTERCEPTOR ); assertTrue( testClone.clone() != null ); testClone = (TestClone)Enhancer.create( TestClone.class, new MethodInterceptor(){ public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable{ return proxy.invokeSuper(obj, args); } } ); assertTrue( testClone.clone() != null ); } public void testSamples() throws Throwable{ samples.Trace.main(new String[]{}); samples.Beans.main(new String[]{}); } public static interface FinalA { void foo(); } public static class FinalB implements FinalA { final public void foo() { } } public void testFinal() throws Throwable { ((FinalA)Enhancer.create(FinalB.class, TEST_INTERCEPTOR)).foo(); } public static interface ConflictA { int foo(); } public static interface ConflictB { String foo(); } public void testConflict() throws Throwable { Object foo = Enhancer.create(Object.class, new Class[]{ ConflictA.class, ConflictB.class }, TEST_INTERCEPTOR); ((ConflictA)foo).foo(); ((ConflictB)foo).foo(); } // TODO: make this work again public void testArgInit() throws Throwable{ Enhancer e = new Enhancer(); e.setSuperclass(ArgInit.class); e.setCallbackType(MethodInterceptor.class); Class f = e.createClass(); ArgInit a = (ArgInit)ReflectUtils.newInstance(f, new Class[]{ String.class }, new Object[]{ "test" }); assertEquals("test", a.toString()); ((Factory)a).setCallback(0, TEST_INTERCEPTOR); assertEquals("test", a.toString()); Callback[] callbacks = new Callback[]{ TEST_INTERCEPTOR }; ArgInit b = (ArgInit)((Factory)a).newInstance(new Class[]{ String.class }, new Object[]{ "test2" }, callbacks); assertEquals("test2", b.toString()); try{ ((Factory)a).newInstance(new Class[]{ String.class, String.class }, new Object[]{"test"}, callbacks); fail("must throw exception"); }catch( IllegalArgumentException iae ){ } } public static class Signature { public int interceptor() { return 42; } } public void testSignature() throws Throwable { Signature sig = (Signature)Enhancer.create(Signature.class, TEST_INTERCEPTOR); assertTrue(((Factory)sig).getCallback(0) == TEST_INTERCEPTOR); assertTrue(sig.interceptor() == 42); } public abstract static class AbstractMethodCallInConstructor { public AbstractMethodCallInConstructor() { foo(); } public abstract void foo(); } public void testAbstractMethodCallInConstructor() throws Throwable { AbstractMethodCallInConstructor obj = (AbstractMethodCallInConstructor) Enhancer.create(AbstractMethodCallInConstructor.class, TEST_INTERCEPTOR); obj.foo(); } public void testProxyIface() throws Throwable { final DI1 other = new DI1() { public String herby() { return "boop"; } }; DI1 d = (DI1)Enhancer.create(DI1.class, new MethodInterceptor() { public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable { return proxy.invoke(other, args); } }); assertTrue("boop".equals(d.herby())); } static class NamingPolicyDummy {} public void testNamingPolicy() throws Throwable { Enhancer e = new Enhancer(); e.setSuperclass(NamingPolicyDummy.class); e.setUseCache(false); e.setUseFactory(false); e.setNamingPolicy(new DefaultNamingPolicy() { public String getTag() { return "ByHerby"; } public String toString() { return getTag(); } }); e.setCallbackType(MethodInterceptor.class); Class proxied = e.createClass(); final boolean[] ran = new boolean[1]; Enhancer.registerStaticCallbacks(proxied, new Callback[]{ new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { ran[0] = true; assertTrue(proxy.getSuperFastClass().getClass().getName().indexOf("$FastClassByHerby$") >= 0); return proxy.invokeSuper(obj, args); } } }); NamingPolicyDummy dummy = (NamingPolicyDummy) proxied.newInstance(); dummy.toString(); assertTrue(ran[0]); } public static Object enhance(Class cls, Class interfaces[], Callback callback, ClassLoader loader) { Enhancer e = new Enhancer(); e.setSuperclass(cls); e.setInterfaces(interfaces); e.setCallback(callback); e.setClassLoader(loader); return e.create(); } public interface PublicClone extends Cloneable { Object clone() throws CloneNotSupportedException; } public void testNoOpClone() throws Exception { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(PublicClone.class); enhancer.setCallback(NoOp.INSTANCE); ((PublicClone)enhancer.create()).clone(); } public void testNoFactory() throws Exception { noFactoryHelper(); noFactoryHelper(); } private void noFactoryHelper() { MethodInterceptor mi = new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { return "Foo"; } }; Enhancer enhancer = new Enhancer(); enhancer.setUseFactory(false); enhancer.setSuperclass(AroundDemo.class); enhancer.setCallback(mi); AroundDemo obj = (AroundDemo)enhancer.create(); assertTrue(obj.getFirstName().equals("Foo")); assertTrue(!(obj instanceof Factory)); } interface MethDec { void foo(); } abstract static class MethDecImpl implements MethDec { } public void testMethodDeclarer() throws Exception { final boolean[] result = new boolean[]{ false }; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(MethDecImpl.class); enhancer.setCallback(new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { result[0] = method.getDeclaringClass().getName().equals(MethDec.class.getName()); return null; } }); ((MethDecImpl)enhancer.create()).foo(); assertTrue(result[0]); } interface ClassOnlyX { } public void testClassOnlyFollowedByInstance() { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(ClassOnlyX.class); enhancer.setCallbackType(NoOp.class); Class type = enhancer.createClass(); enhancer = new Enhancer(); enhancer.setSuperclass(ClassOnlyX.class); enhancer.setCallback(NoOp.INSTANCE); Object instance = enhancer.create(); assertTrue(instance instanceof ClassOnlyX); assertTrue(instance.getClass().equals(type)); } public void testSql() { Enhancer.create(null, new Class[]{ java.sql.PreparedStatement.class }, TEST_INTERCEPTOR); } public void testEquals() throws Exception { final boolean[] result = new boolean[]{ false }; EqualsInterceptor intercept = new EqualsInterceptor(); Object obj = Enhancer.create(null, intercept); obj.equals(obj); assertTrue(intercept.called); } public static class EqualsInterceptor implements MethodInterceptor { final static Method EQUALS_METHOD = ReflectUtils.findMethod("Object.equals(Object)"); boolean called; public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.equals(EQUALS_METHOD)) { return proxy.invoke(this, args); } else { return proxy.invokeSuper(obj, args); } } public boolean equals(Object other) { called = true; return super.equals(other); } } private static interface ExceptionThrower { void throwsThrowable(int arg) throws Throwable; void throwsException(int arg) throws Exception; void throwsNothing(int arg); } private static class MyThrowable extends Throwable { } private static class MyException extends Exception { } private static class MyRuntimeException extends RuntimeException { } public void testExceptions() { Enhancer e = new Enhancer(); e.setSuperclass(ExceptionThrower.class); e.setCallback(new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { switch (((Integer)args[0]).intValue()) { case 1: throw new MyThrowable(); case 2: throw new MyException(); case 3: throw new MyRuntimeException(); default: return null; } } }); ExceptionThrower et = (ExceptionThrower)e.create(); try { et.throwsThrowable(1); } catch (MyThrowable t) { } catch (Throwable t) { fail(); } try { et.throwsThrowable(2); } catch (MyException t) { } catch (Throwable t) { fail(); } try { et.throwsThrowable(3); } catch (MyRuntimeException t) { } catch (Throwable t) { fail(); } try { et.throwsException(1); } catch (Throwable t) { assertTrue(t instanceof MyThrowable); } try { et.throwsException(2); } catch (MyException t) { } catch (Throwable t) { fail(); } try { et.throwsException(3); } catch (MyRuntimeException t) { } catch (Throwable t) { fail(); } try { et.throwsException(4); } catch (Throwable t) { fail(); } try { et.throwsNothing(1); } catch (Throwable t) { assertTrue(t instanceof MyThrowable); } try { et.throwsNothing(2); } catch (Exception t) { assertTrue(t instanceof MyException); } try { et.throwsNothing(3); } catch (MyRuntimeException t) { } catch (Throwable t) { fail(); } try { et.throwsNothing(4); } catch (Throwable t) { fail(); } } public void testUnusedCallback() { Enhancer e = new Enhancer(); e.setCallbackTypes(new Class[]{ MethodInterceptor.class, NoOp.class }); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return 0; } }); e.createClass(); } private static ArgInit newArgInit(Class clazz, String value) { return (ArgInit)ReflectUtils.newInstance(clazz, new Class[]{ String.class }, new Object[]{ value }); } private static class StringValue implements MethodInterceptor { private String value; public StringValue(String value) { this.value = value; } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) { return value; } } public void testRegisterCallbacks() throws InterruptedException { Enhancer e = new Enhancer(); e.setSuperclass(ArgInit.class); e.setCallbackType(MethodInterceptor.class); e.setUseFactory(false); final Class clazz = e.createClass(); assertTrue(!Factory.class.isAssignableFrom(clazz)); assertEquals("test", newArgInit(clazz, "test").toString()); Enhancer.registerCallbacks(clazz, new Callback[]{ new StringValue("fizzy") }); assertEquals("fizzy", newArgInit(clazz, "test").toString()); assertEquals("fizzy", newArgInit(clazz, "test").toString()); Enhancer.registerCallbacks(clazz, new Callback[]{ null }); assertEquals("test", newArgInit(clazz, "test").toString()); Enhancer.registerStaticCallbacks(clazz, new Callback[]{ new StringValue("soda") }); assertEquals("test", newArgInit(clazz, "test").toString()); Enhancer.registerCallbacks(clazz, null); assertEquals("soda", newArgInit(clazz, "test").toString()); Thread thread = new Thread(){ public void run() { assertEquals("soda", newArgInit(clazz, "test").toString()); } }; thread.start(); thread.join(); } public void perform(ClassLoader loader) throws Exception{ enhance( Source.class , null, TEST_INTERCEPTOR, loader); } public void testCallbackHelper() { final ArgInit delegate = new ArgInit("helper"); Class sc = ArgInit.class; Class[] interfaces = new Class[]{ DI1.class, DI2.class }; CallbackHelper helper = new CallbackHelper(sc, interfaces) { protected Object getCallback(final Method method) { return new FixedValue() { public Object loadObject() { return "You called method " + method.getName(); } }; } }; Enhancer e = new Enhancer(); e.setSuperclass(sc); e.setInterfaces(interfaces); e.setCallbacks(helper.getCallbacks()); e.setCallbackFilter(helper); ArgInit proxy = (ArgInit)e.create(new Class[]{ String.class }, new Object[]{ "whatever" }); assertEquals("You called method toString", proxy.toString()); assertEquals("You called method herby", ((DI1)proxy).herby()); assertEquals("You called method derby", ((DI2)proxy).derby()); } public void testSerialVersionUID() throws Exception { Long suid = new Long(0xABBADABBAD00L); Enhancer e = new Enhancer(); e.setSerialVersionUID(suid); e.setCallback(NoOp.INSTANCE); Object obj = e.create(); Field field = obj.getClass().getDeclaredField("serialVersionUID"); field.setAccessible(true); assertEquals(suid, field.get(obj)); } interface ReturnTypeA { int foo(String x); } interface ReturnTypeB { String foo(String x); } public void testMethodsDifferingByReturnTypeOnly() throws IOException { Enhancer e = new Enhancer(); e.setInterfaces(new Class[]{ ReturnTypeA.class, ReturnTypeB.class }); e.setCallback(new MethodInterceptor() { public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { if (method.getReturnType().equals(String.class)) return "hello"; return new Integer(42); } }); Object obj = e.create(); assertEquals(42, ((ReturnTypeA)obj).foo("foo")); assertEquals("hello", ((ReturnTypeB)obj).foo("foo")); assertEquals(-1, FastClass.create(obj.getClass()).getIndex("foo", new Class[]{ String.class })); } public static class ConstructorCall { private String x; public ConstructorCall() { x = toString(); } public String toString() { return "foo"; } } public void testInterceptDuringConstruction() { FixedValue fixedValue = new FixedValue() { public Object loadObject() { return "bar"; } }; Enhancer e = new Enhancer(); e.setSuperclass(ConstructorCall.class); e.setCallback(fixedValue); assertEquals("bar", ((ConstructorCall)e.create()).x); e = new Enhancer(); e.setSuperclass(ConstructorCall.class); e.setCallback(fixedValue); e.setInterceptDuringConstruction(false); assertEquals("foo", ((ConstructorCall)e.create()).x); } void assertThreadLocalCallbacks(Class cls)throws Exception{ Field field = cls.getDeclaredField("CGLIB$THREAD_CALLBACKS"); field.setAccessible(true); assertNull(((ThreadLocal) field.get(null)).get()); } public void testThreadLocalCleanup1()throws Exception{ Enhancer e = new Enhancer(); e.setUseCache(false); e.setCallbackType(NoOp.class); Class cls = e.createClass(); assertThreadLocalCallbacks(cls); } public void testThreadLocalCleanup2()throws Exception{ Enhancer e = new Enhancer(); e.setCallback(NoOp.INSTANCE); Object obj = e.create(); assertThreadLocalCallbacks(obj.getClass()); } public void testThreadLocalCleanup3()throws Exception{ Enhancer e = new Enhancer(); e.setCallback(NoOp.INSTANCE); Factory obj = (Factory) e.create(); obj.newInstance(NoOp.INSTANCE); assertThreadLocalCallbacks(obj.getClass()); } public void testBridgeForcesInvokeVirtual() { List retTypes = new ArrayList(); List paramTypes = new ArrayList(); Interceptor interceptor = new Interceptor(retTypes, paramTypes); Enhancer e = new Enhancer(); e.setSuperclass(Impl.class); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return method.getDeclaringClass() != Object.class ? 0 : 1; } }); e.setCallbacks(new Callback[] { interceptor, NoOp.INSTANCE }); // We expect the bridge ('ret') to be called & forward us to the non-bridge 'erased' Interface intf = (Interface)e.create(); intf.aMethod(null); // Make sure the right things got called in the right order: assertEquals(Arrays.asList(RetType.class, ErasedType.class), retTypes); // Validate calling the refined just gives us that. retTypes.clear(); Impl impl = (Impl)intf; impl.aMethod((Refined)null); assertEquals(Arrays.asList(Refined.class), retTypes); // When calling from the impl, we are dispatched directly to the non-bridge, // because that's just how it works. retTypes.clear(); impl.aMethod((RetType)null); assertEquals(Arrays.asList(ErasedType.class), retTypes); // Do a whole bunch of checks for the other methods too paramTypes.clear(); intf.intReturn(null); assertEquals(Arrays.asList(RetType.class, ErasedType.class), paramTypes); paramTypes.clear(); intf.voidReturn(null); assertEquals(Arrays.asList(RetType.class, ErasedType.class), paramTypes); paramTypes.clear(); intf.widenReturn(null); assertEquals(Arrays.asList(RetType.class, ErasedType.class), paramTypes); } public void testBridgeForcesInvokeVirtualEvenWithoutInterceptingBridge() { List retTypes = new ArrayList(); Interceptor interceptor = new Interceptor(retTypes); Enhancer e = new Enhancer(); e.setSuperclass(Impl.class); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { // Ideally this would be: // return !method.isBridge() && method.getDeclaringClass() != Object.class ? 0 : 1; // But Eclipse sometimes labels the wrong things as bridge methods, so we're more // explicit: return method.getDeclaringClass() != Object.class && method.getReturnType() != RetType.class ? 0 : 1; } }); e.setCallbacks(new Callback[] { interceptor, NoOp.INSTANCE }); // We expect the bridge ('ret') to be called & forward us to non-bridge ('erased'), // and we only intercept on the non-bridge. Interface intf = (Interface)e.create(); intf.aMethod(null); assertEquals(Arrays.asList(ErasedType.class), retTypes); // Validate calling the refined just gives us that. retTypes.clear(); Impl impl = (Impl)intf; impl.aMethod((Refined)null); assertEquals(Arrays.asList(Refined.class), retTypes); // Make sure we still get our non-bride interception if we didn't intercept the bridge. retTypes.clear(); impl.aMethod((RetType)null); assertEquals(Arrays.asList(ErasedType.class), retTypes); } public void testReverseBridge() { List retTypes = new ArrayList(); Interceptor interceptor = new Interceptor(retTypes); Enhancer e = new Enhancer(); e.setSuperclass(ReverseImpl.class); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return method.getDeclaringClass() != Object.class ? 0 : 1; } }); e.setCallbacks(new Callback[] { interceptor, NoOp.INSTANCE }); // We expect the bridge ('erased') to be called & forward us to 'ret' (non-bridge) ReverseSuper superclass = (ReverseSuper)e.create(); superclass.aMethod(null, null, null, null); assertEquals(Arrays.asList(ErasedType.class, RetType.class), retTypes); // Calling the Refined type gives us just that. retTypes.clear(); ReverseImpl impl2 = (ReverseImpl)superclass; impl2.aMethod(null, (Refined)null, null, null); assertEquals(Arrays.asList(Refined.class), retTypes); retTypes.clear(); impl2.aMethod(null, (RetType)null, null, null); assertEquals(Arrays.asList(RetType.class), retTypes); } public void testBridgeForMoreViz() { List retTypes = new ArrayList(); List paramTypes = new ArrayList(); Interceptor interceptor = new Interceptor(retTypes, paramTypes); Enhancer e = new Enhancer(); e.setSuperclass(PublicViz.class); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return method.getDeclaringClass() != Object.class ? 0 : 1; } }); e.setCallbacks(new Callback[] { interceptor, NoOp.INSTANCE }); VizIntf intf = (VizIntf)e.create(); intf.aMethod(null); assertEquals(Arrays.asList(Concrete.class), paramTypes); } static class ErasedType {} static class RetType extends ErasedType {} static class Refined extends RetType {} static abstract class Superclass { // Check narrowing return value & parameters public T aMethod(T t) { return null; } // Check void return value public void voidReturn(T t) { } // Check primitive return value public int intReturn(T t) { return 1; } // Check widening return value public RetType widenReturn(T t) { return null; } } public interface Interface { // the usage of the interface forces the bridge RetType aMethod(RetType obj); void voidReturn(RetType obj); int intReturn(RetType obj); // a wider type than in superclass ErasedType widenReturn(RetType obj); } public static class Impl extends Superclass implements Interface { // An even more narrowed type, just to make sure // it doesn't confuse us. public Refined aMethod(Refined obj) { return null; } } // Another set of classes -- this time with the bridging in reverse, // to make sure that if we define the concrete type, a bridge // is created to call it from an erased type. static abstract class ReverseSuper { // the various parameters are to make sure we only // change signature when we have to -- only 'c' goes // from ErasedType -> RetType public T aMethod(Concrete b, T c, RetType d, ErasedType e) { return null; } } static class Concrete {} static class ReverseImpl extends ReverseSuper { public Refined aMethod(Concrete b, Refined c, RetType d, ErasedType e) { return null; } public RetType aMethod(Concrete b, RetType c, RetType d, ErasedType e) { return null; } } public interface VizIntf { public void aMethod(Concrete a); } static abstract class PackageViz implements VizIntf { public void aMethod(Concrete e) { } } // inherits aMethod from PackageViz, but bridges to make it // publicly accessible. the bridge here has the same // target signature, so it absolutely requires invokespecial, // otherwise we recurse forever. public static class PublicViz extends PackageViz implements VizIntf {} private static class Interceptor implements MethodInterceptor { private final List retList; private final List paramList; public Interceptor(List retList) { this(retList, new ArrayList()); } public Interceptor(List retList, List paramList) { this.retList = retList; this.paramList = paramList; } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { retList.add(method.getReturnType()); if (method.getParameterTypes().length > 0) { paramList.add(method.getParameterTypes()[0]); } return proxy.invokeSuper(obj, args); } } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestNoOp.java0000644000175000017500000000303510066633124022552 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.CodeGenTestCase; import java.lang.reflect.*; import java.util.*; import junit.framework.*; public class TestNoOp extends CodeGenTestCase { private static class Foo { public Foo() { } public String toString() { return "foo"; } } public void testNoOp() { Object obj = Enhancer.create(Foo.class, NoOp.INSTANCE); assertTrue("foo".equals(obj.toString())); } public TestNoOp(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestNoOp.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/EA.java0000644000175000017500000000107007747615702021337 0ustar miguelmiguelpackage net.sf.cglib.proxy; import java.io.ObjectStreamException; public class EA { private Long id; private String name; public Long getId() { return id; } public String getName() { return name; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } protected Object writeReplace() throws ObjectStreamException { return null; } protected void finalTest(){} public int compareTo(Object obj) { return -1; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/ED.java0000644000175000017500000000050007747615702021337 0ustar miguelmiguelpackage net.sf.cglib.proxy; public class ED { private Long id; private float amount; public float getAmount() { return amount; } public Long getId() { return id; } public void setAmount(float amount) { this.amount = amount; } public void setId(Long id) { this.id = id; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/ArgInit.java0000644000175000017500000000047207747615702022414 0ustar miguelmiguel package net.sf.cglib.proxy; /** * * @author baliuka */ public class ArgInit { final private String value; /** Creates a new instance of ArgInit */ public ArgInit(String value) { this.value = value; } public String toString(){ return value; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/TestInterceptor.java0000644000175000017500000000475610066633124024210 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Modifier; /** *@author Juozas Baliuka baliuka@mwm.lt *@version $Id: TestInterceptor.java,v 1.3 2004/06/24 21:15:16 herbyderby Exp $ */ public class TestInterceptor implements MethodInterceptor, Serializable { String value; public String getValue() { return value; } public TestInterceptor(String ser) { value = ser; } public TestInterceptor() { } public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println( method ); Throwable e = null; boolean invokedSuper = false; Object retValFromSuper = null; if (!Modifier.isAbstract(method.getModifiers()) && invokeSuper(obj, method, args)) { invokedSuper = true; try { retValFromSuper = proxy.invokeSuper(obj, args); } catch (Throwable t) { e = t; } } return afterReturn(obj, method, args, invokedSuper, retValFromSuper, e); } public boolean invokeSuper(Object obj, Method method, Object[] args) throws Throwable { return true; } public Object afterReturn(Object obj, Method method, Object[] args, boolean invokedSuper, Object retValFromSuper, Throwable e) throws Throwable { if (e != null) throw e.fillInStackTrace(); return retValFromSuper; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxy/DBean3.java0000644000175000017500000000032107747615702022104 0ustar miguelmiguelpackage net.sf.cglib.proxy; public class DBean3 { private int age; public void setAge(int age) { this.age = age; } public int getAge() { return age; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/0000755000175000017500000000000012250627450020440 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/TestFastClass.java0000644000175000017500000010642612250620402024025 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; import net.sf.cglib.core.ClassGenerator; import net.sf.cglib.core.DefaultGeneratorStrategy; import net.sf.cglib.transform.ClassTransformerTee; import net.sf.cglib.transform.TransformingClassGenerator; public class TestFastClass extends net.sf.cglib.CodeGenTestCase { public static class Simple { } public static class ThrowsSomething { public void foo() throws IOException { throw new IOException("hello"); } } public void testSimple() throws Throwable { FastClass.create(Simple.class).newInstance(); FastClass.create(Simple.class).newInstance(); } public void testException() throws Throwable { FastClass fc = FastClass.create(ThrowsSomething.class); ThrowsSomething ts = new ThrowsSomething(); try { fc.invoke("foo", new Class[0], ts, new Object[0]); fail("expected exception"); } catch (InvocationTargetException e) { assertTrue(e.getTargetException() instanceof IOException); } } public static class Child extends net.sf.cglib.reflect.sub.Parent { } public void testSuperclass() throws Throwable { FastClass fc = FastClass.create(Child.class); assertEquals("dill", new Child().getHerb()); assertEquals("dill", fc.invoke("getHerb", new Class[0], new Child(), new Object[0])); } public void testTypeMismatch() throws Throwable { FastClass fc = FastClass.create(ThrowsSomething.class); ThrowsSomething ts = new ThrowsSomething(); try { fc.invoke("foo", new Class[]{ Integer.TYPE }, ts, new Object[0]); fail("expected exception"); } catch (IllegalArgumentException ignore) { } } public void testComplex() throws Throwable { FastClass fc = FastClass.create(MemberSwitchBean.class); MemberSwitchBean bean = (MemberSwitchBean)fc.newInstance(); assertTrue(bean.init == 0); assertTrue(fc.getName().equals("net.sf.cglib.reflect.MemberSwitchBean")); assertTrue(fc.getJavaClass() == MemberSwitchBean.class); assertTrue(fc.getMaxIndex() == 19); Constructor c1 = MemberSwitchBean.class.getConstructor(new Class[0]); FastConstructor fc1 = fc.getConstructor(c1); assertTrue(((MemberSwitchBean)fc1.newInstance()).init == 0); assertTrue(fc1.toString().equals("public net.sf.cglib.reflect.MemberSwitchBean()")); Method m1 = MemberSwitchBean.class.getMethod("foo", new Class[]{ Integer.TYPE, String.class }); assertTrue(fc.getMethod(m1).invoke(bean, new Object[]{ new Integer(0), "" }).equals(new Integer(6))); // TODO: should null be allowed here? Method m2 = MemberSwitchBean.class.getDeclaredMethod("pkg", (Class[])null); assertTrue(fc.getMethod(m2).invoke(bean, null).equals(new Integer(9))); } public void testStatic() throws Throwable { FastClass fc = FastClass.create(MemberSwitchBean.class); // MemberSwitchBean bean = (MemberSwitchBean)fc.newInstance(); assertTrue(fc.invoke("staticMethod", new Class[0], null, null).equals(new Integer(10))); } private static abstract class ReallyBigClass { public ReallyBigClass() { } abstract public void method1(int i, short s, float f); abstract public void method1(int i, byte d, float f); abstract public void method2(int i, short s, float f); abstract public void method2(int i, byte d, float f); abstract public void method3(int i, short s, float f); abstract public void method3(int i, byte d, float f); abstract public void method4(int i, short s, float f); abstract public void method4(int i, byte d, float f); abstract public void method5(int i, short s, float f); abstract public void method5(int i, byte d, float f); abstract public void method6(int i, short s, float f); abstract public void method6(int i, byte d, float f); abstract public void method7(int i, short s, float f); abstract public void method7(int i, byte d, float f); abstract public void method8(int i, short s, float f); abstract public void method8(int i, byte d, float f); abstract public void method9(int i, short s, float f); abstract public void method9(int i, byte d, float f); abstract public void method10(int i, short s, float f); abstract public void method10(int i, byte d, float f); abstract public void method11(int i, short s, float f); abstract public void method11(int i, byte d, float f); abstract public void method12(int i, short s, float f); abstract public void method12(int i, byte d, float f); abstract public void method13(int i, short s, float f); abstract public void method13(int i, byte d, float f); abstract public void method14(int i, short s, float f); abstract public void method14(int i, byte d, float f); abstract public void method15(int i, short s, float f); abstract public void method15(int i, byte d, float f); abstract public void method16(int i, short s, float f); abstract public void method16(int i, byte d, float f); abstract public void method17(int i, short s, float f); abstract public void method17(int i, byte d, float f); abstract public void method18(int i, short s, float f); abstract public void method18(int i, byte d, float f); abstract public void method19(int i, short s, float f); abstract public void method19(int i, byte d, float f); abstract public void method20(int i, short s, float f); abstract public void method20(int i, byte d, float f); abstract public void method21(int i, short s, float f); abstract public void method21(int i, byte d, float f); abstract public void method22(int i, short s, float f); abstract public void method22(int i, byte d, float f); abstract public void method23(int i, short s, float f); abstract public void method23(int i, byte d, float f); abstract public void method24(int i, short s, float f); abstract public void method24(int i, byte d, float f); abstract public void method25(int i, short s, float f); abstract public void method25(int i, byte d, float f); abstract public void method26(int i, short s, float f); abstract public void method26(int i, byte d, float f); abstract public void method27(int i, short s, float f); abstract public void method27(int i, byte d, float f); abstract public void method28(int i, short s, float f); abstract public void method28(int i, byte d, float f); abstract public void method29(int i, short s, float f); abstract public void method29(int i, byte d, float f); abstract public void method30(int i, short s, float f); abstract public void method30(int i, byte d, float f); abstract public void method31(int i, short s, float f); abstract public void method31(int i, byte d, float f); abstract public void method32(int i, short s, float f); abstract public void method32(int i, byte d, float f); abstract public void method33(int i, short s, float f); abstract public void method33(int i, byte d, float f); abstract public void method34(int i, short s, float f); abstract public void method34(int i, byte d, float f); abstract public void method35(int i, short s, float f); abstract public void method35(int i, byte d, float f); abstract public void method36(int i, short s, float f); abstract public void method36(int i, byte d, float f); abstract public void method37(int i, short s, float f); abstract public void method37(int i, byte d, float f); abstract public void method38(int i, short s, float f); abstract public void method38(int i, byte d, float f); abstract public void method39(int i, short s, float f); abstract public void method39(int i, byte d, float f); abstract public void method40(int i, short s, float f); abstract public void method40(int i, byte d, float f); abstract public void method41(int i, short s, float f); abstract public void method41(int i, byte d, float f); abstract public void method42(int i, short s, float f); abstract public void method42(int i, byte d, float f); abstract public void method43(int i, short s, float f); abstract public void method43(int i, byte d, float f); abstract public void method44(int i, short s, float f); abstract public void method44(int i, byte d, float f); abstract public void method45(int i, short s, float f); abstract public void method45(int i, byte d, float f); abstract public void method46(int i, short s, float f); abstract public void method46(int i, byte d, float f); abstract public void method47(int i, short s, float f); abstract public void method47(int i, byte d, float f); abstract public void method48(int i, short s, float f); abstract public void method48(int i, byte d, float f); abstract public void method49(int i, short s, float f); abstract public void method49(int i, byte d, float f); abstract public void method50(int i, short s, float f); abstract public void method50(int i, byte d, float f); abstract public void method51(int i, short s, float f); abstract public void method51(int i, byte d, float f); abstract public void method52(int i, short s, float f); abstract public void method52(int i, byte d, float f); abstract public void method53(int i, short s, float f); abstract public void method53(int i, byte d, float f); abstract public void method54(int i, short s, float f); abstract public void method54(int i, byte d, float f); abstract public void method55(int i, short s, float f); abstract public void method55(int i, byte d, float f); abstract public void method56(int i, short s, float f); abstract public void method56(int i, byte d, float f); abstract public void method57(int i, short s, float f); abstract public void method57(int i, byte d, float f); abstract public void method58(int i, short s, float f); abstract public void method58(int i, byte d, float f); abstract public void method59(int i, short s, float f); abstract public void method59(int i, byte d, float f); abstract public void method60(int i, short s, float f); abstract public void method60(int i, byte d, float f); abstract public void method61(int i, short s, float f); abstract public void method61(int i, byte d, float f); abstract public void method62(int i, short s, float f); abstract public void method62(int i, byte d, float f); abstract public void method63(int i, short s, float f); abstract public void method63(int i, byte d, float f); abstract public void method64(int i, short s, float f); abstract public void method64(int i, byte d, float f); abstract public void method65(int i, short s, float f); abstract public void method65(int i, byte d, float f); abstract public void method66(int i, short s, float f); abstract public void method66(int i, byte d, float f); abstract public void method67(int i, short s, float f); abstract public void method67(int i, byte d, float f); abstract public void method68(int i, short s, float f); abstract public void method68(int i, byte d, float f); abstract public void method69(int i, short s, float f); abstract public void method69(int i, byte d, float f); abstract public void method70(int i, short s, float f); abstract public void method70(int i, byte d, float f); abstract public void method71(int i, short s, float f); abstract public void method71(int i, byte d, float f); abstract public void method72(int i, short s, float f); abstract public void method72(int i, byte d, float f); abstract public void method73(int i, short s, float f); abstract public void method73(int i, byte d, float f); abstract public void method74(int i, short s, float f); abstract public void method74(int i, byte d, float f); abstract public void method75(int i, short s, float f); abstract public void method75(int i, byte d, float f); abstract public void method76(int i, short s, float f); abstract public void method76(int i, byte d, float f); abstract public void method77(int i, short s, float f); abstract public void method77(int i, byte d, float f); abstract public void method78(int i, short s, float f); abstract public void method78(int i, byte d, float f); abstract public void method79(int i, short s, float f); abstract public void method79(int i, byte d, float f); abstract public void method80(int i, short s, float f); abstract public void method80(int i, byte d, float f); abstract public void method81(int i, short s, float f); abstract public void method81(int i, byte d, float f); abstract public void method82(int i, short s, float f); abstract public void method82(int i, byte d, float f); abstract public void method83(int i, short s, float f); abstract public void method83(int i, byte d, float f); abstract public void method84(int i, short s, float f); abstract public void method84(int i, byte d, float f); abstract public void method85(int i, short s, float f); abstract public void method85(int i, byte d, float f); abstract public void method86(int i, short s, float f); abstract public void method86(int i, byte d, float f); abstract public void method87(int i, short s, float f); abstract public void method87(int i, byte d, float f); abstract public void method88(int i, short s, float f); abstract public void method88(int i, byte d, float f); abstract public void method89(int i, short s, float f); abstract public void method89(int i, byte d, float f); abstract public void method90(int i, short s, float f); abstract public void method90(int i, byte d, float f); abstract public void method91(int i, short s, float f); abstract public void method91(int i, byte d, float f); abstract public void method92(int i, short s, float f); abstract public void method92(int i, byte d, float f); abstract public void method93(int i, short s, float f); abstract public void method93(int i, byte d, float f); abstract public void method94(int i, short s, float f); abstract public void method94(int i, byte d, float f); abstract public void method95(int i, short s, float f); abstract public void method95(int i, byte d, float f); abstract public void method96(int i, short s, float f); abstract public void method96(int i, byte d, float f); abstract public void method97(int i, short s, float f); abstract public void method97(int i, byte d, float f); abstract public void method98(int i, short s, float f); abstract public void method98(int i, byte d, float f); abstract public void method99(int i, short s, float f); abstract public void method99(int i, byte d, float f); abstract public void method100(int i, short s, float f); abstract public void method100(int i, byte d, float f); abstract public void method101(int i, short s, float f); abstract public void method101(int i, byte d, float f); abstract public void method102(int i, short s, float f); abstract public void method102(int i, byte d, float f); abstract public void method103(int i, short s, float f); abstract public void method103(int i, byte d, float f); abstract public void method104(int i, short s, float f); abstract public void method104(int i, byte d, float f); abstract public void method105(int i, short s, float f); abstract public void method105(int i, byte d, float f); abstract public void method106(int i, short s, float f); abstract public void method106(int i, byte d, float f); abstract public void method107(int i, short s, float f); abstract public void method107(int i, byte d, float f); abstract public void method108(int i, short s, float f); abstract public void method108(int i, byte d, float f); abstract public void method109(int i, short s, float f); abstract public void method109(int i, byte d, float f); abstract public void method110(int i, short s, float f); abstract public void method110(int i, byte d, float f); abstract public void method111(int i, short s, float f); abstract public void method111(int i, byte d, float f); abstract public void method112(int i, short s, float f); abstract public void method112(int i, byte d, float f); abstract public void method113(int i, short s, float f); abstract public void method113(int i, byte d, float f); abstract public void method114(int i, short s, float f); abstract public void method114(int i, byte d, float f); abstract public void method115(int i, short s, float f); abstract public void method115(int i, byte d, float f); abstract public void method116(int i, short s, float f); abstract public void method116(int i, byte d, float f); abstract public void method117(int i, short s, float f); abstract public void method117(int i, byte d, float f); abstract public void method118(int i, short s, float f); abstract public void method118(int i, byte d, float f); abstract public void method119(int i, short s, float f); abstract public void method119(int i, byte d, float f); abstract public void method120(int i, short s, float f); abstract public void method120(int i, byte d, float f); abstract public void methodB1(int i, short s, float f); abstract public void methodB1(int i, byte d, float f); abstract public void methodB2(int i, short s, float f); abstract public void methodB2(int i, byte d, float f); abstract public void methodB3(int i, short s, float f); abstract public void methodB3(int i, byte d, float f); abstract public void methodB4(int i, short s, float f); abstract public void methodB4(int i, byte d, float f); abstract public void methodB5(int i, short s, float f); abstract public void methodB5(int i, byte d, float f); abstract public void methodB6(int i, short s, float f); abstract public void methodB6(int i, byte d, float f); abstract public void methodB7(int i, short s, float f); abstract public void methodB7(int i, byte d, float f); abstract public void methodB8(int i, short s, float f); abstract public void methodB8(int i, byte d, float f); abstract public void methodB9(int i, short s, float f); abstract public void methodB9(int i, byte d, float f); abstract public void methodB10(int i, short s, float f); abstract public void methodB10(int i, byte d, float f); abstract public void methodB11(int i, short s, float f); abstract public void methodB11(int i, byte d, float f); abstract public void methodB12(int i, short s, float f); abstract public void methodB12(int i, byte d, float f); abstract public void methodB13(int i, short s, float f); abstract public void methodB13(int i, byte d, float f); abstract public void methodB14(int i, short s, float f); abstract public void methodB14(int i, byte d, float f); abstract public void methodB15(int i, short s, float f); abstract public void methodB15(int i, byte d, float f); abstract public void methodB16(int i, short s, float f); abstract public void methodB16(int i, byte d, float f); abstract public void methodB17(int i, short s, float f); abstract public void methodB17(int i, byte d, float f); abstract public void methodB18(int i, short s, float f); abstract public void methodB18(int i, byte d, float f); abstract public void methodB19(int i, short s, float f); abstract public void methodB19(int i, byte d, float f); abstract public void methodB20(int i, short s, float f); abstract public void methodB20(int i, byte d, float f); abstract public void methodB21(int i, short s, float f); abstract public void methodB21(int i, byte d, float f); abstract public void methodB22(int i, short s, float f); abstract public void methodB22(int i, byte d, float f); abstract public void methodB23(int i, short s, float f); abstract public void methodB23(int i, byte d, float f); abstract public void methodB24(int i, short s, float f); abstract public void methodB24(int i, byte d, float f); abstract public void methodB25(int i, short s, float f); abstract public void methodB25(int i, byte d, float f); abstract public void methodB26(int i, short s, float f); abstract public void methodB26(int i, byte d, float f); abstract public void methodB27(int i, short s, float f); abstract public void methodB27(int i, byte d, float f); abstract public void methodB28(int i, short s, float f); abstract public void methodB28(int i, byte d, float f); abstract public void methodB29(int i, short s, float f); abstract public void methodB29(int i, byte d, float f); abstract public void methodB30(int i, short s, float f); abstract public void methodB30(int i, byte d, float f); abstract public void methodB31(int i, short s, float f); abstract public void methodB31(int i, byte d, float f); abstract public void methodB32(int i, short s, float f); abstract public void methodB32(int i, byte d, float f); abstract public void methodB33(int i, short s, float f); abstract public void methodB33(int i, byte d, float f); abstract public void methodB34(int i, short s, float f); abstract public void methodB34(int i, byte d, float f); abstract public void methodB35(int i, short s, float f); abstract public void methodB35(int i, byte d, float f); abstract public void methodB36(int i, short s, float f); abstract public void methodB36(int i, byte d, float f); abstract public void methodB37(int i, short s, float f); abstract public void methodB37(int i, byte d, float f); abstract public void methodB38(int i, short s, float f); abstract public void methodB38(int i, byte d, float f); abstract public void methodB39(int i, short s, float f); abstract public void methodB39(int i, byte d, float f); abstract public void methodB40(int i, short s, float f); abstract public void methodB40(int i, byte d, float f); abstract public void methodB41(int i, short s, float f); abstract public void methodB41(int i, byte d, float f); abstract public void methodB42(int i, short s, float f); abstract public void methodB42(int i, byte d, float f); abstract public void methodB43(int i, short s, float f); abstract public void methodB43(int i, byte d, float f); abstract public void methodB44(int i, short s, float f); abstract public void methodB44(int i, byte d, float f); abstract public void methodB45(int i, short s, float f); abstract public void methodB45(int i, byte d, float f); abstract public void methodB46(int i, short s, float f); abstract public void methodB46(int i, byte d, float f); abstract public void methodB47(int i, short s, float f); abstract public void methodB47(int i, byte d, float f); abstract public void methodB48(int i, short s, float f); abstract public void methodB48(int i, byte d, float f); abstract public void methodB49(int i, short s, float f); abstract public void methodB49(int i, byte d, float f); abstract public void methodB50(int i, short s, float f); abstract public void methodB50(int i, byte d, float f); abstract public void methodB51(int i, short s, float f); abstract public void methodB51(int i, byte d, float f); abstract public void methodB52(int i, short s, float f); abstract public void methodB52(int i, byte d, float f); abstract public void methodB53(int i, short s, float f); abstract public void methodB53(int i, byte d, float f); abstract public void methodB54(int i, short s, float f); abstract public void methodB54(int i, byte d, float f); abstract public void methodB55(int i, short s, float f); abstract public void methodB55(int i, byte d, float f); abstract public void methodB56(int i, short s, float f); abstract public void methodB56(int i, byte d, float f); abstract public void methodB57(int i, short s, float f); abstract public void methodB57(int i, byte d, float f); abstract public void methodB58(int i, short s, float f); abstract public void methodB58(int i, byte d, float f); abstract public void methodB59(int i, short s, float f); abstract public void methodB59(int i, byte d, float f); abstract public void methodB60(int i, short s, float f); abstract public void methodB60(int i, byte d, float f); abstract public void methodB61(int i, short s, float f); abstract public void methodB61(int i, byte d, float f); abstract public void methodB62(int i, short s, float f); abstract public void methodB62(int i, byte d, float f); abstract public void methodB63(int i, short s, float f); abstract public void methodB63(int i, byte d, float f); abstract public void methodB64(int i, short s, float f); abstract public void methodB64(int i, byte d, float f); abstract public void methodB65(int i, short s, float f); abstract public void methodB65(int i, byte d, float f); abstract public void methodB66(int i, short s, float f); abstract public void methodB66(int i, byte d, float f); abstract public void methodB67(int i, short s, float f); abstract public void methodB67(int i, byte d, float f); abstract public void methodB68(int i, short s, float f); abstract public void methodB68(int i, byte d, float f); abstract public void methodB69(int i, short s, float f); abstract public void methodB69(int i, byte d, float f); abstract public void methodB70(int i, short s, float f); abstract public void methodB70(int i, byte d, float f); abstract public void methodB71(int i, short s, float f); abstract public void methodB71(int i, byte d, float f); abstract public void methodB72(int i, short s, float f); abstract public void methodB72(int i, byte d, float f); abstract public void methodB73(int i, short s, float f); abstract public void methodB73(int i, byte d, float f); abstract public void methodB74(int i, short s, float f); abstract public void methodB74(int i, byte d, float f); abstract public void methodB75(int i, short s, float f); abstract public void methodB75(int i, byte d, float f); abstract public void methodB76(int i, short s, float f); abstract public void methodB76(int i, byte d, float f); abstract public void methodB77(int i, short s, float f); abstract public void methodB77(int i, byte d, float f); abstract public void methodB78(int i, short s, float f); abstract public void methodB78(int i, byte d, float f); abstract public void methodB79(int i, short s, float f); abstract public void methodB79(int i, byte d, float f); abstract public void methodB80(int i, short s, float f); abstract public void methodB80(int i, byte d, float f); abstract public void methodB81(int i, short s, float f); abstract public void methodB81(int i, byte d, float f); abstract public void methodB82(int i, short s, float f); abstract public void methodB82(int i, byte d, float f); abstract public void methodB83(int i, short s, float f); abstract public void methodB83(int i, byte d, float f); abstract public void methodB84(int i, short s, float f); abstract public void methodB84(int i, byte d, float f); abstract public void methodB85(int i, short s, float f); abstract public void methodB85(int i, byte d, float f); abstract public void methodB86(int i, short s, float f); abstract public void methodB86(int i, byte d, float f); abstract public void methodB87(int i, short s, float f); abstract public void methodB87(int i, byte d, float f); abstract public void methodB88(int i, short s, float f); abstract public void methodB88(int i, byte d, float f); abstract public void methodB89(int i, short s, float f); abstract public void methodB89(int i, byte d, float f); abstract public void methodB90(int i, short s, float f); abstract public void methodB90(int i, byte d, float f); abstract public void methodB91(int i, short s, float f); abstract public void methodB91(int i, byte d, float f); abstract public void methodB92(int i, short s, float f); abstract public void methodB92(int i, byte d, float f); abstract public void methodB93(int i, short s, float f); abstract public void methodB93(int i, byte d, float f); abstract public void methodB94(int i, short s, float f); abstract public void methodB94(int i, byte d, float f); abstract public void methodB95(int i, short s, float f); abstract public void methodB95(int i, byte d, float f); abstract public void methodB96(int i, short s, float f); abstract public void methodB96(int i, byte d, float f); abstract public void methodB97(int i, short s, float f); abstract public void methodB97(int i, byte d, float f); abstract public void methodB98(int i, short s, float f); abstract public void methodB98(int i, byte d, float f); abstract public void methodB99(int i, short s, float f); abstract public void methodB99(int i, byte d, float f); abstract public void methodB100(int i, short s, float f); abstract public void methodB100(int i, byte d, float f); abstract public void methodB101(int i, short s, float f); abstract public void methodB101(int i, byte d, float f); abstract public void methodB102(int i, short s, float f); abstract public void methodB102(int i, byte d, float f); abstract public void methodB103(int i, short s, float f); abstract public void methodB103(int i, byte d, float f); abstract public void methodB104(int i, short s, float f); abstract public void methodB104(int i, byte d, float f); abstract public void methodB105(int i, short s, float f); abstract public void methodB105(int i, byte d, float f); abstract public void methodB106(int i, short s, float f); abstract public void methodB106(int i, byte d, float f); abstract public void methodB107(int i, short s, float f); abstract public void methodB107(int i, byte d, float f); abstract public void methodB108(int i, short s, float f); abstract public void methodB108(int i, byte d, float f); abstract public void methodB109(int i, short s, float f); abstract public void methodB109(int i, byte d, float f); abstract public void methodB110(int i, short s, float f); abstract public void methodB110(int i, byte d, float f); abstract public void methodB111(int i, short s, float f); abstract public void methodB111(int i, byte d, float f); abstract public void methodB112(int i, short s, float f); abstract public void methodB112(int i, byte d, float f); abstract public void methodB113(int i, short s, float f); abstract public void methodB113(int i, byte d, float f); abstract public void methodB114(int i, short s, float f); abstract public void methodB114(int i, byte d, float f); abstract public void methodB115(int i, short s, float f); abstract public void methodB115(int i, byte d, float f); abstract public void methodB116(int i, short s, float f); abstract public void methodB116(int i, byte d, float f); abstract public void methodB117(int i, short s, float f); abstract public void methodB117(int i, byte d, float f); abstract public void methodB118(int i, short s, float f); abstract public void methodB118(int i, byte d, float f); abstract public void methodB119(int i, short s, float f); abstract public void methodB119(int i, byte d, float f); abstract public void methodB120(int i, short s, float f); abstract public void methodB120(int i, byte d, float f); } public void testReallyBigClass() throws IOException { FastClass.Generator gen = new FastClass.Generator(); gen.setType(ReallyBigClass.class); FastClass fc = gen.create(); } public TestFastClass(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestFastClass.class); } public void perform(ClassLoader loader) throws Throwable { FastClass.create(loader,Simple.class).newInstance(); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/MemberSwitchBean.java0000644000175000017500000000330410066633124024460 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; public class MemberSwitchBean { public int init = -1; public MemberSwitchBean() { init = 0; } public MemberSwitchBean(double foo) { init = 1; } public MemberSwitchBean(int foo) { init = 2; } public MemberSwitchBean(int foo, String bar, String baz) { init = 3; } public MemberSwitchBean(int foo, String bar, double baz) { init = 4; } public MemberSwitchBean(int foo, short bar, long baz) { init = 5; } public MemberSwitchBean(int foo, String bar) { init = 6; } public int foo() { return 0; } public int foo(double foo) { return 1; } public int foo(int foo) { return 2; } public int foo(int foo, String bar, String baz) { return 3; } public int foo(int foo, String bar, double baz) { return 4; } public int foo(int foo, short bar, long baz) { return 5; } public int foo(int foo, String bar) { return 6; } public int bar() { return 7; } public int bar(double foo) { return 8; } int pkg() { return 9; } public static int staticMethod() { return 10; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/TestReflectPerf.java0000644000175000017500000001013110066633124024336 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; public class TestReflectPerf extends net.sf.cglib.CodeGenTestCase { public interface IndexOf { int indexOf(String s, int start); } public void testReflectPerf() throws Throwable { int iterations = 1000000; System.out.println(); System.out.println("iteration count: " + iterations); String test = "abcabcabc"; Class[] types = new Class[]{ String.class, Integer.TYPE }; Method indexOf = String.class.getDeclaredMethod("indexOf", types); FastClass fc = FastClass.create(String.class); FastMethod fm = fc.getMethod("indexOf", types); int fidx = fm.getIndex(); Object[] args = new Object[]{ "ab", new Integer(1) }; IndexOf fast = (IndexOf)MethodDelegate.create(test, "indexOf", IndexOf.class); int result; long t1 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = ((Integer)fc.invoke("indexOf", types, test, args)).intValue(); } long t2 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { args = new Object[]{ "ab", new Integer(1) }; result = ((Integer)indexOf.invoke(test, args)).intValue(); } long t3 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = ((Integer)indexOf.invoke(test, args)).intValue(); } long t4 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { args = new Object[]{ "ab", new Integer(1) }; result = ((Integer)fm.invoke(test, args)).intValue(); } long t5 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = ((Integer)fm.invoke(test, args)).intValue(); } long t6 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = ((Integer)fc.invoke(fidx, test, args)).intValue(); } long t7 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = fast.indexOf("ab", 1); } long t8 = System.currentTimeMillis(); for (int i = 0; i < iterations; i++) { result = test.indexOf("ab", 1); } long t9 = System.currentTimeMillis(); System.out.println("fc = " + (t2 - t1) + "\n" + "reflect+args = " + (t3 - t2) + "\n" + "reflect = " + (t4 - t3) + "\n" + "fm+args = " + (t5 - t4) + "\n" + "fm = " + (t6 - t5) + "\n" + "fc w/idx = " + (t7 - t6) + "\n" + "delegate = " + (t8 - t7) + "\n" + "raw = " + (t9 - t8)); } public TestReflectPerf(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestReflectPerf.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/TestDelegates.java0000644000175000017500000001321010066633124024033 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.Method; import junit.framework.*; /** * @version $Id: TestDelegates.java,v 1.4 2004/06/24 21:15:16 herbyderby Exp $ */ public class TestDelegates extends net.sf.cglib.CodeGenTestCase { public interface StringMaker { Object newInstance(char[] buf, int offset, int count); } public void testConstructor() throws Throwable { StringMaker maker = (StringMaker)ConstructorDelegate.create(String.class, StringMaker.class); assertTrue("nil".equals(maker.newInstance("vanilla".toCharArray(), 2, 3))); } public interface Substring { String substring(int start, int end); } public interface Substring2 { Object anyNameAllowed(int start, int end); } public interface IndexOf { int indexOf(String str, int fromIndex); } public void testFancy() throws Throwable { Substring delegate = (Substring)MethodDelegate.create("CGLIB", "substring", Substring.class); assertTrue("LI".equals(delegate.substring(2, 4))); } public void testFancyNames() throws Throwable { Substring2 delegate = (Substring2)MethodDelegate.create("CGLIB", "substring", Substring2.class); assertTrue("LI".equals(delegate.anyNameAllowed(2, 4))); } public void testFancyTypes() throws Throwable { String test = "abcabcabc"; IndexOf delegate = (IndexOf)MethodDelegate.create(test, "indexOf", IndexOf.class); assertTrue(delegate.indexOf("ab", 1) == test.indexOf("ab", 1)); } public void testEquals() throws Throwable { String test = "abc"; MethodDelegate mc1 = MethodDelegate.create(test, "indexOf", IndexOf.class); MethodDelegate mc2 = MethodDelegate.create(test, "indexOf", IndexOf.class); MethodDelegate mc3 = MethodDelegate.create("other", "indexOf", IndexOf.class); MethodDelegate mc4 = MethodDelegate.create(test, "substring", Substring.class); MethodDelegate mc5 = MethodDelegate.create(test, "substring", Substring2.class); assertTrue(mc1.equals(mc2)); assertTrue(!mc1.equals(mc3)); assertTrue(!mc1.equals(mc4)); assertTrue(mc4.equals(mc5)); } public static interface MainDelegate { int main(String[] args); } public static class MainTest { public static int alternateMain(String[] args) { return 7; } } public void testStaticDelegate() throws Throwable { MainDelegate start = (MainDelegate)MethodDelegate.createStatic(MainTest.class, "alternateMain", MainDelegate.class); assertTrue(start.main(null) == 7); } public static interface Listener { public void onEvent(); } public static class Publisher { public int test = 0; private MulticastDelegate event = MulticastDelegate.create(Listener.class); public void addListener(Listener listener) { event = event.add(listener); } public void removeListener(Listener listener) { event = event.remove(listener); } public void fireEvent() { ((Listener)event).onEvent(); } } public void testPublisher() throws Throwable { final Publisher p = new Publisher(); Listener l1 = new Listener() { public void onEvent() { p.test++; } }; p.addListener(l1); p.addListener(l1); p.fireEvent(); assertTrue(p.test == 2); p.removeListener(l1); p.fireEvent(); assertTrue(p.test == 3); } public static interface SuperSimple { public int execute(); } public void testMulticastReturnValue() throws Throwable { SuperSimple ss1 = new SuperSimple() { public int execute() { return 1; } }; SuperSimple ss2 = new SuperSimple() { public int execute() { return 2; } }; MulticastDelegate multi = MulticastDelegate.create(SuperSimple.class); multi = multi.add(ss1); multi = multi.add(ss2); assertTrue(((SuperSimple)multi).execute() == 2); multi = multi.remove(ss1); multi = multi.add(ss1); assertTrue(((SuperSimple)multi).execute() == 1); } public TestDelegates(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestDelegates.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/sub/0000755000175000017500000000000012250627450021231 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/sub/Parent.java0000644000175000017500000000013110400676550023320 0ustar miguelmiguelpackage net.sf.cglib.reflect.sub; abstract public class Parent extends GrandParent { } cglib3-3.1+dfsg/src/test/net/sf/cglib/reflect/sub/GrandParent.java0000644000175000017500000000020210400676550024273 0ustar miguelmiguelpackage net.sf.cglib.reflect.sub; abstract class GrandParent { public String getHerb() { return "dill"; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/0000755000175000017500000000000012250627450021027 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/transform/AbstractTransformTest.java0000644000175000017500000000432110066633124026167 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import junit.framework.*; import net.sf.cglib.core.CodeGenerationException; /** * @author baliuka * $Id: AbstractTransformTest.java,v 1.8 2004/06/24 21:15:16 herbyderby Exp $ */ abstract public class AbstractTransformTest extends TestCase { /** Creates a new instance of AbstractTransformTest */ public AbstractTransformTest() { super(null); } /** Creates a new instance of AbstractTransformTest */ public AbstractTransformTest(String s) { super(s); } protected abstract ClassTransformerFactory getTransformer() throws Exception; public Class transform() throws Exception { ClassLoader loader = new TransformingClassLoader(AbstractTransformTest.class.getClassLoader(), new ClassFilter(){ public boolean accept(String name){ return !(name.startsWith("java") || name.startsWith("junit") || name.endsWith("Exclude")); } }, getTransformer()); try { return loader.loadClass(getClass().getName()); } catch (Exception e) { e.printStackTrace(System.err); throw e; } } protected void postProcess(Class c) { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/DumpFieldsTask.java0000644000175000017500000000713112250620402024541 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import java.io.*; import org.apache.tools.ant.BuildException; import org.objectweb.asm.*; public class DumpFieldsTask extends AbstractProcessTask { private File outfile; private PrintStream out; public void setOutputFile(File outfile) { this.outfile = outfile; } public void execute() throws BuildException { try { out = new PrintStream(new FileOutputStream(outfile)); try{ super.execute(); }finally{ out.close(); } } catch (IOException e) { throw new BuildException(e); } } static class EmptyVisitor extends ClassVisitor { AnnotationVisitor av = new AnnotationVisitor(Opcodes.ASM4) { public AnnotationVisitor visitAnnotation( String name, String desc) { return this; } public AnnotationVisitor visitArray(String name) { return this; } }; public EmptyVisitor() { super(Opcodes.ASM4); } public AnnotationVisitor visitAnnotation( String desc, boolean visible) { return av; } public FieldVisitor visitField( int access, String name, String desc, String signature, Object value) { return new FieldVisitor(Opcodes.ASM4) { public AnnotationVisitor visitAnnotation( String desc, boolean visible) { return av; } }; } @Override public MethodVisitor visitMethod( int access, String name, String desc, String signature, String[] exceptions) { return new MethodVisitor(Opcodes.ASM4) { public AnnotationVisitor visitAnnotationDefault() { return av; } public AnnotationVisitor visitAnnotation( String desc, boolean visible) { return av; } public AnnotationVisitor visitParameterAnnotation( int parameter, String desc, boolean visible) { return av; } }; } } protected void processFile(File file) throws Exception { InputStream in = new BufferedInputStream(new FileInputStream(file)); ClassReader r = new ClassReader(in); r.accept(new EmptyVisitor() { private String className; public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { className = name.replace('/', '.'); } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { out.println("class=" + className + ", field=" + name); return null; } }, ClassReader.SKIP_DEBUG); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/0000755000175000017500000000000012250627450021770 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/MA.java0000644000175000017500000000453310255460316023134 0ustar miguelmiguelpackage net.sf.cglib.transform.impl; import java.io.ObjectStreamException; public class MA extends Base{ private Long id; private String name; private String privateName; private int intP; private long longP; private boolean booleanP; private char charP; private byte byteP; private short shortP; private float floatP; private double doubleP; private String stringP; public String publicField; public Long getId() { return id; } public String getName() { return name; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } protected Object writeReplace() throws ObjectStreamException { return null; } /* package */ String getPrivateName() { return privateName; } /* package */ void setPrivateName(String name) { this.privateName = name; } public int getIntP() { return this.intP; } public void setIntP(int intP) { this.intP = intP; } public long getLongP() { return this.longP; } public void setLongP(long longP) { this.longP = longP; } public boolean isBooleanP() { return this.booleanP; } public void setBooleanP(boolean booleanP) { this.booleanP = booleanP; } public char getCharP() { return this.charP; } public void setCharP(char charP) { this.charP = charP; } public byte getByteP() { return this.byteP; } public void setByteP(byte byteP) { this.byteP = byteP; } public short getShortP() { return this.shortP; } public void setShortP(short shortP) { this.shortP = shortP; } public float getFloatP() { return this.floatP; } public void setFloatP(float floatP) { this.floatP = floatP; } public double getDoubleP() { return this.doubleP; } public void setDoubleP(double doubleP) { this.doubleP = doubleP; } public String getStringP() { return this.stringP; } public void setStringP(String stringP) { this.stringP = stringP; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestAddDelegate.java0000644000175000017500000000447710066633124025630 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import junit.framework.*; /** * * @author baliuka */ public class TestAddDelegate extends AbstractTransformTest { /** Creates a new instance of TestAddDelegate */ public TestAddDelegate(String name) { super(name); } public interface Interface { Object getDelegte(); Object getTarget(); } public void test(){ Interface i = (Interface)this; assertEquals(i.getTarget(),this); } public static class ImplExclude implements Interface { private Object target; public ImplExclude(Object target){ this.target = target; } public Object getDelegte() { return this; } public Object getTarget(){ return target; } } public TestAddDelegate() { super(null); } protected ClassTransformerFactory getTransformer() throws Exception { return new ClassTransformerFactory(){ public ClassTransformer newInstance(){ return new AddDelegateTransformer(new Class[]{Interface.class} , ImplExclude.class ); } }; } public static void main(String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception{ return new TestSuite( new TestAddDelegate().transform() ); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestInterceptFieldsSubclass.java0000644000175000017500000000400310255460316030253 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import junit.framework.Test; import junit.framework.TestSuite; /** * @author Juozas * */ public class TestInterceptFieldsSubclass extends TestInterceptFields { private boolean readTest = false; private boolean writeTest = false; public TestInterceptFieldsSubclass() { super(); } public TestInterceptFieldsSubclass(String name) { super(name); } public void testSubClass(){ super.test(); assertTrue( "super class read field", readTest ); assertTrue( "super class write field", readTest ); } public Object readObject(Object _this, String name, Object oldValue) { if(name.equals("field")){ readTest = true; } return super.readObject(_this, name, oldValue); } public Object writeObject(Object _this, String name, Object oldValue, Object newValue) { if(name.equals("field")){ writeTest = true; } return super.writeObject(_this, name, oldValue, newValue); } public static void main(String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception{ return new TestSuite( new TestInterceptFieldsSubclass( ).transform() ); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/Base.java0000644000175000017500000000057510255460316023513 0ustar miguelmiguelpackage net.sf.cglib.transform.impl; public class Base { private String baseTest; /** * @return Returns the baseTest. */ public String getBaseTest() { return baseTest; } /** * @param baseTest The baseTest to set. */ public void setBaseTest(String baseTest) { this.baseTest = baseTest; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestDemo.java0000644000175000017500000000111007756353372024366 0ustar miguelmiguel package net.sf.cglib.transform.impl; import junit.framework.*; /** * * @author baliuka */ public class TestDemo extends TestCase{ /** Creates a new instance of AbstractTransformTest */ public TestDemo(String s) { super(s); } public void test()throws Exception{ TransformDemo.main( null ); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestDemo.class); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/PersistenceCapableImpl.java0000644000175000017500000000131607756353372027230 0ustar miguelmiguel package net.sf.cglib.transform.impl; /** * * @author baliuka */ public class PersistenceCapableImpl implements PersistenceCapable { Object persistenceManager; Object pc;//transformed class instance /** Creates a new instance of PersistenceCapableImpl, transformed class uses this constructor */ public PersistenceCapableImpl(Object _this) { this.pc = _this; } public void setPersistenceManager( Object manager){ persistenceManager = manager; System.out.println("setPersistenceManager:" + manager); } public Object getPersistenceManager(){ return persistenceManager; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestTransformingLoader.java0000644000175000017500000001202710402432046027265 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import net.sf.cglib.core.Constants; import net.sf.cglib.core.ReflectUtils; import net.sf.cglib.beans.*; import java.util.*; import java.lang.reflect.Method; import junit.framework.*; import org.objectweb.asm.Type; /** * @version $Id: TestTransformingLoader.java,v 1.6 2006/03/05 02:43:17 herbyderby Exp $ */ public class TestTransformingLoader extends net.sf.cglib.CodeGenTestCase { private static final ClassFilter TEST_FILTER = new ClassFilter() { public boolean accept(String name) { System.err.println("Loading " + name); return name.startsWith("net.sf.cglib."); } }; private ClassTransformer getExampleTransformer(String name, Type type) { return new AddPropertyTransformer(new String[]{ name }, new Type[]{ type }); } public void testExample() throws Exception { ClassTransformer t1 = getExampleTransformer("herby", Constants.TYPE_STRING); ClassTransformer t2 = getExampleTransformer("derby", Type.DOUBLE_TYPE); ClassTransformer chain = new ClassTransformerChain(new ClassTransformer[]{ t1, t2 }); Class loaded = loadHelper(chain, Example.class); Object obj = loaded.newInstance(); String value = "HELLO"; loaded.getMethod("setHerby", new Class[]{ String.class }).invoke(obj, new Object[]{ value }); assertTrue(value.equals(loaded.getMethod("getHerby", (Class[])null).invoke(obj, (Object[])null))); loaded.getMethod("setDerby", new Class[]{ Double.TYPE }).invoke(obj, new Object[]{ new Double(1.23456789d) }); } private static Class inited; public static void initStatic(Class foo) { System.err.println("INITING: " + foo); } public void testAddStatic() throws Exception { Method m = ReflectUtils.findMethod("net.sf.cglib.transform.impl.TestTransformingLoader.initStatic(Class)"); ClassTransformer t = new AddStaticInitTransformer(m); // t = new ClassTransformerChain(new ClassTransformer[]{ t, new ClassTransformerTee(new org.objectweb.asm.util.TraceClassVisitor(null, new java.io.PrintWriter(System.out))) }); Class loaded = loadHelper(t, Example.class); Object obj = loaded.newInstance(); // TODO } public void testInterceptField() throws Exception { ClassTransformer t = new InterceptFieldTransformer(new InterceptFieldFilter() { public boolean acceptRead(Type owner, String name) { return true; } public boolean acceptWrite(Type owner, String name) { return true; } }); Class loaded = loadHelper(t, Example.class); // TODO } public void testFieldProvider() throws Exception { ClassTransformer t = new FieldProviderTransformer(); Class loaded = loadHelper(t, Example.class); // TODO // FieldProvider fp = (FieldProvider)loaded.newInstance(); // assertTrue(((Integer)fp.getField("example")).intValue() == 42); // fp.setField("example", new Integer(6)); // assertTrue(((Integer)fp.getField("example")).intValue() == 6); // assertTrue(fp.getField("example") == null); // try { // fp.getField("dsfjkl"); // fail("expected exception"); // } catch (IllegalArgumentException ignore) { } } private static Class loadHelper( final ClassTransformer t, Class target) throws ClassNotFoundException { ClassLoader parent = TestTransformingLoader.class.getClassLoader(); TransformingClassLoader loader = new TransformingClassLoader(parent, TEST_FILTER, new ClassTransformerFactory(){ public ClassTransformer newInstance(){ return t; } } ); return loader.loadClass(target.getName()); } public TestTransformingLoader(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestTransformingLoader.class); } public void perform(ClassLoader loader) throws Throwable { } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestInterceptFields.java0000644000175000017500000001151510066633124026560 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import junit.framework.*; import org.objectweb.asm.*; /** * * @author baliuka */ public class TestInterceptFields extends AbstractTransformTest implements InterceptFieldCallback{ static Object TEST_VALUE = "test1"; String field; /** Creates a new instance of TestInterceptFields */ public TestInterceptFields() { } /** Creates a new instance of TestInterceptFields */ public TestInterceptFields(String name) { super(name); } public void test(){ InterceptFieldEnabled e = (InterceptFieldEnabled)this; e.setInterceptFieldCallback( this ); field = "test"; assertEquals(TEST_VALUE,field); } protected ClassTransformerFactory getTransformer() throws Exception { return new ClassTransformerFactory(){ public ClassTransformer newInstance(){ return new InterceptFieldTransformer( new InterceptFieldFilter(){ public boolean acceptRead(Type owner, String name){ return true; } public boolean acceptWrite(Type owner, String name){ return true; } } ); } }; } public boolean readBoolean(Object _this, String name, boolean oldValue) { return oldValue; } public byte readByte(Object _this, String name, byte oldValue) { return oldValue; } public char readChar(Object _this, String name, char oldValue) { return oldValue; } public double readDouble(Object _this, String name, double oldValue) { return oldValue; } public float readFloat(Object _this, String name, float oldValue) { return oldValue; } public int readInt(Object _this, String name, int oldValue) { return oldValue; } public long readLong(Object _this, String name, long oldValue) { return oldValue; } public Object readObject(Object _this, String name, Object oldValue) { return TEST_VALUE; } public short readShort(Object _this, String name, short oldValue) { return oldValue; } public boolean writeBoolean(Object _this, String name, boolean oldValue, boolean newValue) { return newValue; } public byte writeByte(Object _this, String name, byte oldValue, byte newValue) { return newValue; } public char writeChar(Object _this, String name, char oldValue, char newValue) { return newValue; } public double writeDouble(Object _this, String name, double oldValue, double newValue) { return newValue; } public float writeFloat(Object _this, String name, float oldValue, float newValue) { return newValue; } public int writeInt(Object _this, String name, int oldValue, int newValue) { return newValue; } public long writeLong(Object _this, String name, long oldValue, long newValue) { return newValue; } public Object writeObject(Object _this, String name, Object oldValue, Object newValue) { return newValue; } public short writeShort(Object _this, String name, short oldValue, short newValue) { return newValue; } public static void main(String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception{ return new TestSuite( new TestInterceptFields( ).transform() ); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestProvideFields.java0000644000175000017500000000371110066633124026232 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import junit.framework.*; /** * * @author baliuka */ public class TestProvideFields extends AbstractTransformTest{ String field = "test"; /** Creates a new instance of TestProvideFields */ public TestProvideFields() { } /** Creates a new instance of TestProvideFields */ public TestProvideFields(String name) { super(name); } public void test(){ FieldProvider provider = (FieldProvider)this; assertEquals(field,provider.getField("field")); String value = "tst2"; provider.setField("field", value ); assertEquals(field,value); } protected ClassTransformerFactory getTransformer() throws Exception { return new ClassTransformerFactory (){ public ClassTransformer newInstance(){ return new FieldProviderTransformer(); } }; } public static void main(String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception{ return new TestSuite( new TestProvideFields( ).transform() ); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TestAddClassInit.java0000644000175000017500000000433110066633124025774 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import junit.framework.*; import java.util.*; import net.sf.cglib.core.*; /** * * @author baliuka */ public class TestAddClassInit extends AbstractTransformTest{ static Class registred; static int i = 0; static { i = 11; } public static void register(Class cls){ registred = cls; } public TestAddClassInit(){ } public void testInitTransform(){ assertEquals(i,11); } public void testRegistred(){ assertNotNull(registred); } public TestAddClassInit(String s){ super(s); } protected ClassTransformerFactory getTransformer() throws Exception{ return new ClassTransformerFactory (){ public ClassTransformer newInstance(){ try{ return new AddStaticInitTransformer( TestAddClassInit.class. getMethod("register",new Class[]{Class.class}) ); }catch(Exception e){ throw new CodeGenerationException(e); } } }; } public static void main(String[] args) throws Exception{ junit.textui.TestRunner.run(suite()); } public static Test suite() throws Exception{ return new TestSuite( new TestAddClassInit( ).transform() ); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/TransformDemo.java0000644000175000017500000002010310402432046025377 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import net.sf.cglib.core.*; import java.util.*; /** * * @author baliuka */ public class TransformDemo { public static void register(Class cls){ System.out.println("register " + cls); } public static void start(){ MA ma = new MA(); makePersistent(ma); ma.setCharP('A'); ma.getCharP(); ma.setDoubleP(554); ma.setDoubleP(1.2); ma.getFloatP(); ma.setName("testName"); ma.publicField = "set value"; ma.publicField = ma.publicField + " append value"; ma.setBaseTest("base test field"); ma.getBaseTest(); } public static void makePersistent(Object obj){ System.out.println( "makePersistent " + obj.getClass() + " " + Arrays.asList(obj.getClass().getInterfaces()) ); InterceptFieldEnabled t = (InterceptFieldEnabled)obj; t.setInterceptFieldCallback( new StateManager()); FieldProvider provider = (FieldProvider)obj; System.out.println("Field Names " + Arrays.asList(provider.getFieldNames()) ); System.out.println("Field Types " + Arrays.asList(provider.getFieldTypes()) ); PersistenceCapable pc = (PersistenceCapable)obj; pc.setPersistenceManager("Manager"); } public static void main( String args [] )throws Exception{ ClassTransformerFactory transformation = new ClassTransformerFactory (){ public ClassTransformer newInstance(){ try{ InterceptFieldTransformer t1 = new InterceptFieldTransformer( new Filter() ); AddStaticInitTransformer t2 = new AddStaticInitTransformer( TransformDemo.class.getMethod("register",new Class[]{Class.class}) ); AddDelegateTransformer t3 = new AddDelegateTransformer( new Class[]{PersistenceCapable.class}, PersistenceCapableImpl.class ); FieldProviderTransformer t4 = new FieldProviderTransformer(); return new ClassTransformerChain( new ClassTransformer[]{t4,t1,t2,t3} ); }catch(Exception e){ throw new CodeGenerationException(e); } } }; TransformingClassLoader loader = new TransformingClassLoader( TransformDemo.class.getClassLoader(), new ClassFilter(){ public boolean accept(String name){ System.out.println("load : " + name); boolean f = Base.class.getName().equals(name) || MA.class.getName().equals(name) || TransformDemo.class.getName().equals(name); if(f){ System.out.println("transforming " + name); } return f; } }, transformation ); loader.loadClass(TransformDemo.class.getName()).getMethod("start",new Class[]{}).invoke(null, (Object[])null); } public static class Filter implements InterceptFieldFilter{ public boolean acceptRead(org.objectweb.asm.Type owner, String name) { return true; } public boolean acceptWrite(org.objectweb.asm.Type owner, String name) { return true; } }; public static class StateManager implements InterceptFieldCallback{ public boolean readBoolean(Object _this, String name, boolean oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public byte readByte(Object _this, String name, byte oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public char readChar(Object _this, String name, char oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public double readDouble(Object _this, String name, double oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public float readFloat(Object _this, String name, float oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public int readInt(Object _this, String name, int oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public long readLong(Object _this, String name, long oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public Object readObject(Object _this, String name, Object oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public short readShort(Object _this, String name, short oldValue) { System.out.println("read " + name + " = " + oldValue); return oldValue; } public boolean writeBoolean(Object _this, String name, boolean oldValue, boolean newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public byte writeByte(Object _this, String name, byte oldValue, byte newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public char writeChar(Object _this, String name, char oldValue, char newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public double writeDouble(Object _this, String name, double oldValue, double newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public float writeFloat(Object _this, String name, float oldValue, float newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public int writeInt(Object _this, String name, int oldValue, int newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public long writeLong(Object _this, String name, long oldValue, long newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public Object writeObject(Object _this, String name, Object oldValue, Object newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } public short writeShort(Object _this, String name, short oldValue, short newValue) { System.out.println( "write " + name + " = " + newValue); return newValue; } } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/ExampleTask.java0000644000175000017500000000446310107334670025056 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import java.util.*; import net.sf.cglib.core.TypeUtils; import org.objectweb.asm.Type; public class ExampleTask extends AbstractTransformTask { private List properties = new ArrayList(); private String fieldSuffix = ""; private ClassTransformer transformer; protected ClassTransformer getClassTransformer(String name[]) { return transformer; } protected void beforeExecute() { ClassTransformer t1 = new AccessFieldTransformer(new AccessFieldTransformer.Callback() { public String getPropertyName(Type owner, String fieldName) { return fieldName + fieldSuffix; } }); int size = properties.size(); String[] names = new String[size]; Type[] types = new Type[size]; for (int i = 0; i < size; i++) { NewProperty p = (NewProperty)properties.get(i); names[i] = p.name; types[i] = TypeUtils.parseType(p.type); } ClassTransformer t2 = new AddPropertyTransformer(names, types); transformer = new ClassTransformerChain(new ClassTransformer[]{ t1, t2 }); } public static class NewProperty { private String name; private String type; public void setName(String name) { this.name = name; } public void setType(String type) { this.type = type; } } public void addNewproperty(NewProperty prop) { properties.add(prop); } public void setFieldsuffix(String fieldSuffix) { this.fieldSuffix = fieldSuffix; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/Example.java0000644000175000017500000000062507756353372024247 0ustar miguelmiguelpackage net.sf.cglib.transform.impl; public class Example { private int answer = 42; private String word; public int getAnswer() { return answer; } public void setAnswer(int answer) { this.answer = answer; } public String getWord() { return word; } public void setWord(String word) { this.word = word; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/transform/impl/PersistenceCapable.java0000644000175000017500000000033107756353372026402 0ustar miguelmiguel package net.sf.cglib.transform.impl; /** * * @author baliuka */ public interface PersistenceCapable { void setPersistenceManager(Object manager); Object getPersistenceManager(); } cglib3-3.1+dfsg/src/test/net/sf/cglib/CodeGenTestCase.java0000644000175000017500000000301212250620400022577 0ustar miguelmiguel/* * Copyright 2002,2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib; import java.io.*; import java.io.File; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.*; import java.util.ArrayList; import java.util.StringTokenizer; import net.sf.cglib.core.KeyFactory; import net.sf.cglib.core.Signature; import net.sf.cglib.proxy.*; import net.sf.cglib.proxy.Callback; import net.sf.cglib.proxy.Factory; import net.sf.cglib.reflect.FastClass; import junit.framework.*; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: CodeGenTestCase.java,v 1.10 2012/07/27 16:02:49 baliuka Exp $ */ abstract public class CodeGenTestCase extends TestCase { public CodeGenTestCase(String testName) { super(testName); } public abstract void perform(ClassLoader loader)throws Throwable; } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/0000755000175000017500000000000012250627450020104 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/beans/MA.java0000644000175000017500000000447710025635306021255 0ustar miguelmiguelpackage net.sf.cglib.beans; import java.io.ObjectStreamException; class MA { private Long id; private String name; private String privateName; private int intP; private long longP; private boolean booleanP; private char charP; private byte byteP; private short shortP; private float floatP; private double doubleP; private String stringP; public String publicField; public Long getId() { return id; } public String getName() { return name; } public void setId(Long id) { this.id = id; } public void setName(String name) { this.name = name; } protected Object writeReplace() throws ObjectStreamException { return null; } /* package */ String getPrivateName() { return privateName; } /* package */ void setPrivateName(String name) { this.privateName = name; } public int getIntP() { return this.intP; } public void setIntP(int intP) { this.intP = intP; } public long getLongP() { return this.longP; } public void setLongP(long longP) { this.longP = longP; } public boolean isBooleanP() { return this.booleanP; } public void setBooleanP(boolean booleanP) { this.booleanP = booleanP; } public char getCharP() { return this.charP; } public void setCharP(char charP) { this.charP = charP; } public byte getByteP() { return this.byteP; } public void setByteP(byte byteP) { this.byteP = byteP; } public short getShortP() { return this.shortP; } public void setShortP(short shortP) { this.shortP = shortP; } public float getFloatP() { return this.floatP; } public void setFloatP(float floatP) { this.floatP = floatP; } public double getDoubleP() { return this.doubleP; } public void setDoubleP(double doubleP) { this.doubleP = doubleP; } public String getStringP() { return this.stringP; } public void setStringP(String stringP) { this.stringP = stringP; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestBeanGenerator.java0000644000175000017500000000366610066633126024336 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.*; import java.lang.reflect.Method; import junit.framework.*; import net.sf.cglib.core.ReflectUtils; /** * @author Juozas Baliuka, Chris Nokleberg */ public class TestBeanGenerator extends TestCase { public void testSimple() throws Exception { BeanGenerator bg = new BeanGenerator(); bg.addProperty("sin", Double.TYPE); Object bean = bg.create(); PropertyDescriptor[] pds = ReflectUtils.getBeanProperties(bean.getClass()); assertTrue(pds.length == 1); assertTrue(pds[0].getName().equals("sin")); assertTrue(pds[0].getPropertyType().equals(Double.TYPE)); } public void testSuperclass() throws Exception { BeanGenerator bg = new BeanGenerator(); bg.setSuperclass(MA.class); bg.addProperty("sin", Double.TYPE); Object bean = bg.create(); assertTrue(bean instanceof MA); assertTrue(BeanMap.create(bean).keySet().contains("sin")); } public TestBeanGenerator(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBeanGenerator.class); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestBeanCopier.java0000644000175000017500000000376210066633126023626 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import net.sf.cglib.core.Converter; import java.lang.reflect.Method; import junit.framework.*; /** * * @author baliuka */ public class TestBeanCopier extends TestCase { public void testSimple() { BeanCopier copier = BeanCopier.create(MA.class, MA.class, false); MA bean1 = new MA(); bean1.setIntP(42); MA bean2 = new MA(); copier.copy(bean1, bean2, null); assertTrue(bean2.getIntP() == 42); } public void testConvert() { BeanCopier copier = BeanCopier.create(MA.class, MA.class, true); MA bean1 = new MA(); bean1.setIntP(42); MA bean2 = new MA(); copier.copy(bean1, bean2, new Converter() { public Object convert(Object value, Class target, Object context) { if (target.equals(Integer.TYPE)) { return new Integer(((Number)value).intValue() + 1); } return value; } }); assertTrue(bean2.getIntP() == 43); } public TestBeanCopier(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBeanCopier.class); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/BeanMapProxy.java0000644000175000017500000000335010066633126023315 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: BeanMapProxy.java,v 1.2 2004/06/24 21:15:17 herbyderby Exp $ */ public class BeanMapProxy implements InvocationHandler { private Map map; public static Object newInstance(Map map, Class[] interfaces) { return Proxy.newProxyInstance(map.getClass().getClassLoader(), interfaces, new BeanMapProxy(map)); } public BeanMapProxy(Map map) { this.map = map; } public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { String name = m.getName(); if (name.startsWith("get")) { return map.get(name.substring(3)); } else if (name.startsWith("set")) { map.put(name.substring(3), args[0]); return null; } return null; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestBulkBean.java0000644000175000017500000002513710402432046023272 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.lang.reflect.Method; import junit.framework.*; /** * * @author baliuka */ public class TestBulkBean extends TestCase { private String getters[] = { "getIntP", "getLongP", "getByteP", "getShortP", "getFloatP", "isBooleanP", "getCharP", "getDoubleP", "getStringP", "getId", "getName", "getPrivateName" } ; private String setters[] = { "setIntP", "setLongP", "setByteP", "setShortP", "setFloatP", "setBooleanP", "setCharP", "setDoubleP", "setStringP", "setId", "setName", "setPrivateName" }; private Class types[] = { int.class, long.class, byte.class, short.class, float.class, boolean.class, char.class, double.class, String.class, Long.class, String.class, String.class }; private Object values[] = { new Integer(2) , new Long(4) , new Byte((byte)8), new Short((short)4), new Float(1.2), Boolean.TRUE, new Character('S'), new Double(5.6), "test", new Long(88), "test2", "private" }; public TestBulkBean(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBulkBean.class); } /** Test of create method, of class net.sf.cglib.BulkBean. */ public void testGetInstance() throws Throwable { BulkBean mClass = BulkBean.create(MA.class, getters, setters, types); MA bean = new MA(); mClass.setPropertyValues( bean, values ); Object values1[] = mClass.getPropertyValues( bean ); for( int i = 0; i < types.length; i++ ){ assertEquals(" property " + getters[i] + "/" + setters[i] , values[i] , values1[i] ); } } public void testEmpty() throws Throwable { BulkBean.create(MA.class, new String[0], new String[0], new Class[0]); } public void testBadTypes() throws Throwable { Class[] types2 = (Class[])types.clone(); types2[2] = String.class; try { BulkBean.create(MA.class, getters, setters, types2); fail("expected exception"); } catch (BulkBeanException e) { assertTrue(e.getIndex() == 2); } } public void testMismatchedLengths() throws Throwable { try { BulkBean.create(MA.class, getters, setters, new Class[0]); fail("expected exception"); } catch (BulkBeanException e) { assertTrue(e.getIndex() == -1); } } public void testMissingProperty() throws Throwable { String[] getters2 = (String[])getters.clone(); getters2[3] = "getChris"; try { BulkBean.create(MA.class, getters2, setters, types); fail("expected exception"); } catch (BulkBeanException e) { assertTrue(e.getIndex() == 3); } } public void testSetWrongType() throws Throwable { BulkBean mClass = BulkBean.create(MA.class, getters, setters, types); MA bean = new MA(); Object[] values2 = (Object[])values.clone(); values2[4] = new Object(); try { mClass.setPropertyValues(bean, values2); fail("expected exception"); } catch (BulkBeanException e) { assertTrue(e.getIndex() == 4); } } public void testBulkBeanPerformance() throws Throwable{ int iterations = 100000; System.out.println(); System.out.println("iteration count: " + iterations); System.out.println(); BulkBean mClass = new BulkBeanReflectImpl( MA.class,getters,setters,types ); System.out.println( mClass.getClass().getName() + ": " ); int b = performanceTest( mClass, iterations ); System.out.println( b + " ms. " + ( b/(float)iterations) + " per iteration" ); System.out.println(); mClass = BulkBean.create(MA.class, getters, setters, types); System.out.println( mClass.getClass().getName() + ": " ); int a = performanceTest( mClass, iterations ); System.out.println( a + " ms. " + ( a/(float)iterations) + " per iteration" ); System.out.println( "factor: " + b/(float)a ); mClass = new BulkBeanPlainImpl(); System.out.println( mClass.getClass().getName() + ": " ); a = performanceTest( mClass, iterations ); System.out.println( a + " ms. " + ( a/(float)iterations) + " per iteration" ); } public int performanceTest( BulkBean mc, int iterations ) throws Throwable{ long start = System.currentTimeMillis(); for( int i = 0; i< iterations; i++ ){ MA bean = new MA(); // (MA)mc.newInstance(); mc.setPropertyValues( bean, values ); mc.getPropertyValues( bean, values ); } return (int)( System.currentTimeMillis() - start ); } private static class BulkBeanPlainImpl extends BulkBean { public void getPropertyValues(Object bean, Object[] values) { int i = 0; MA ma = (MA) bean; values[i++] = new Integer(ma.getIntP()); values[i++] = new Long(ma.getLongP()); values[i++] = new Byte(ma.getByteP()); values[i++] = new Short(ma.getShortP()); values[i++] = new Float(ma.getFloatP()); values[i++] = new Boolean(ma.isBooleanP()); values[i++] = new Character( ma.getCharP() ); values[i++] = new Double(ma.getDoubleP()); values[i++] = ma.getStringP(); values[i++] = ma.getId(); values[i++] = ma.getName(); values[i++] = ma.getPrivateName(); } public void setPropertyValues(Object bean, Object[] values) { int i = 0; MA ma = (MA) bean; ma.setIntP(((Number)values[i++]).intValue()); ma.setLongP(((Number)values[i++]).longValue()); ma.setByteP(((Number)values[i++]).byteValue()); ma.setShortP(((Number)values[i++]).shortValue()); ma.setFloatP(((Number)values[i++]).floatValue()); ma.setBooleanP(((Boolean)values[i++]).booleanValue()); ma.setCharP( ((Character)values[i++]).charValue()) ; ma.setDoubleP(((Number)values[i++]).doubleValue()); ma.setStringP((String) values[i++]); ma.setId((Long) values[i++]); ma.setName((String) values[i++]); ma.setPrivateName((String) values[i++]); } } /** Generated implementation of abstract class net.sf.cglib.BulkBean. Please fill dummy bodies of generated methods. */ private static class BulkBeanReflectImpl extends BulkBean { private Method gets[]; private Method sets[]; private int size ; public BulkBeanReflectImpl(Class target, String[] getters, String[] setters, Class[] types) { this.target = target; this.types = types; this.getters = getters; this.setters = setters; size = this.types.length; gets = new Method [size]; sets = new Method [size]; try{ for( int i = 0; i< size; i++ ) { if( getters[i] != null ){ gets[i] = target.getDeclaredMethod( getters[i], new Class[]{} ); gets[i].setAccessible(true); } if( setters[i] != null ) { sets[i] = target.getDeclaredMethod( setters[i], new Class[]{ types[i] } ); sets[i].setAccessible(true); } } }catch( Exception e ){ throw new Error(e.getClass().getName() + ":" + e.getMessage() ); } } public void getPropertyValues(Object bean, Object[] values) { try{ for( int i = 0; i < size ; i++ ){ if( this.gets[i] != null ){ values[i] = gets[i].invoke(bean, (Object[])null ); } } }catch( Exception e ){ throw new Error( e.getMessage() ); } } public void setPropertyValues(Object bean, Object[] values) { try{ for( int i = 0; i < size ; i++ ){ if( this.sets[i] != null ){ sets[i].invoke(bean, new Object[]{ values[i] } ); } } }catch( Exception e ){ e.printStackTrace(); throw new Error( e.getMessage() ); } } } // Add test methods here, they have to start with 'test' name. // for example: // public void testHello() {} } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestBeanMapProxy.java0000644000175000017500000000357710066633126024170 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import junit.framework.*; import java.util.*; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: TestBeanMapProxy.java,v 1.3 2004/06/24 21:15:17 herbyderby Exp $ */ public class TestBeanMapProxy extends net.sf.cglib.CodeGenTestCase { public void testBeanMap() throws Exception { HashMap identity = new HashMap(); Person person = (Person)BeanMapProxy.newInstance(identity, new Class[]{ Person.class }); person.setName("Chris"); assertTrue("Chris".equals(person.getName())); assertTrue("Chris".equals(identity.get("Name"))); } public interface Person { public String getName(); public void setName(String name); } public TestBeanMapProxy(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBeanMapProxy.class); } public void perform(ClassLoader loader) throws Throwable { //nothing to test at this time } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestBeanMap.java0000644000175000017500000001216410066633126023116 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import net.sf.cglib.proxy.*; import net.sf.cglib.core.Constants; import net.sf.cglib.core.ReflectUtils; import java.lang.reflect.Method; import java.util.*; import junit.framework.*; public class TestBeanMap extends net.sf.cglib.CodeGenTestCase { public static class TestBean { private String foo; private String bar = "x"; private String baz; private int quud; private int quick = 42; private int quip; public String getFoo() { return foo; } public void setFoo(String value) { foo = value; } public String getBar() { return bar; } public void setBaz(String value) { baz = value; } public int getQuud() { return quud; } public void setQuud(int value) { quud = value; } public int getQuick() { return quick; } public void setQuip(int value) { quip = value; } } public void testBeanMap() { TestBean bean = new TestBean(); BeanMap map = BeanMap.create(bean); assertTrue(map.size() == 6); assertTrue(map.get("foo") == null); map.put("foo", "FOO"); assertTrue("FOO".equals(map.get("foo"))); assertTrue(bean.getFoo().equals("FOO")); assertTrue("x".equals(map.get("bar"))); assertTrue(((Integer)map.get("quick")).intValue() == 42); map.put("quud", new Integer(13)); assertTrue(bean.getQuud() == 13); assertTrue(map.getPropertyType("foo").equals(String.class)); assertTrue(map.getPropertyType("quud").equals(Integer.TYPE)); assertTrue(map.getPropertyType("kdkkj") == null); } public void testEntrySet() { TestBean bean = new TestBean(); BeanMap map = BeanMap.create(bean); assertTrue(map.entrySet().size() == map.size()); } public void testNoUnderlyingBean() { BeanMap.Generator gen = new BeanMap.Generator(); gen.setBeanClass(TestBean.class); BeanMap map = gen.create(); TestBean bean = new TestBean(); assertTrue(bean.getFoo() == null); assertTrue(map.put(bean, "foo", "FOO") == null); assertTrue(bean.getFoo().equals("FOO")); assertTrue(map.get(bean, "foo").equals("FOO")); } public void testMixinMapIntoBean() { Object bean = new TestBean(); bean = mixinMapIntoBean(bean); ((TestBean)bean).setFoo("hello"); assertTrue(bean instanceof Map); assertTrue(((Map)bean).get("foo").equals("hello")); } public void testRequire() { BeanMap.Generator gen = new BeanMap.Generator(); gen.setBeanClass(TestBean.class); gen.setRequire(BeanMap.REQUIRE_GETTER); BeanMap map = gen.create(); assertTrue(map.containsKey("foo")); assertTrue(map.containsKey("bar")); assertTrue(!map.containsKey("baz")); } public static Object mixinMapIntoBean(final Object bean) { Enhancer e = new Enhancer(); e.setSuperclass(bean.getClass()); e.setInterfaces(new Class[]{ Map.class }); final Map map = BeanMap.create(bean); e.setCallbackFilter(new CallbackFilter() { public int accept(Method method) { return method.getDeclaringClass().equals(Map.class) ? 1 : 0; } }); e.setCallbacks(new Callback[]{ new Dispatcher() { public Object loadObject() { return bean; } }, new Dispatcher() { public Object loadObject() { return map; } } }); return e.create(); } // TODO: test different package // TODO: test change bean instance // TODO: test toString public TestBeanMap(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestBeanMap.class); } public void perform(ClassLoader loader) throws Throwable { //tested in enhancer test unit } public void testFailOnMemoryLeak() throws Throwable { } } cglib3-3.1+dfsg/src/test/net/sf/cglib/beans/TestImmutableBean.java0000644000175000017500000000302610066633126024315 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.lang.reflect.Method; import junit.framework.*; /** * * @author baliuka */ public class TestImmutableBean extends TestCase { public void testSimple() { MA bean = new MA(); assertTrue(bean.getIntP() == 0); bean.setIntP(42); assertTrue(bean.getIntP() == 42); bean = (MA)ImmutableBean.create(bean); assertTrue(bean.getIntP() == 42); try { bean.setIntP(43); fail("expecting illegal state exception"); } catch (IllegalStateException ignore) { } } public TestImmutableBean(java.lang.String testName) { super(testName); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestImmutableBean.class); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/0000755000175000017500000000000012250627450021377 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/ProxySampleInterface_ReturnsObject.java0000644000175000017500000000141710066633124031220 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxysample; public interface ProxySampleInterface_ReturnsObject { String getKala(String kalamees) throws Exception; } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/ProxySampleInterface_ReturnsBasic.java0000644000175000017500000000137110066633124031032 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxysample; public interface ProxySampleInterface_ReturnsBasic { int getKala(float kalamees); } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/InvocationHandlerSample.java0000644000175000017500000000304410066633124027012 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxysample; import java.lang.reflect.Method; import net.sf.cglib.proxy.InvocationHandler; /** * @author neeme * */ public class InvocationHandlerSample implements InvocationHandler { private Object o; /** * Constructor for InvocationHandlerSample. */ public InvocationHandlerSample(Object o) { this.o = o; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("invoke() start"); System.out.println(" method: " + method.getName()); if (args != null) { for (int i = 0; i < args.length; i++) { System.out.println(" arg: " + args[i]); } } Object r = method.invoke(o, args); System.out.println(" return: " + r); System.out.println("invoke() end"); return r; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/ProxySample.java0000644000175000017500000000642110402432046024520 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxysample; import java.lang.reflect.InvocationHandler; import java.lang.reflect.UndeclaredThrowableException; public final class ProxySample implements ProxySampleInterface_ReturnsObject, ProxySampleInterface_ReturnsBasic { private InvocationHandler handler = null; protected ProxySample(InvocationHandler handler) { this.handler = handler; } public String getKala(String kalamees) throws Exception { String result = null; try { // invocation is also generated result = (String) handler.invoke(this, ProxySampleInterface_ReturnsObject.class.getMethod("getKala", new Class[] {String.class}), new Object[] {kalamees}); } catch (ClassCastException e) { throw e; } catch (NoSuchMethodException e) { throw new Error(e.getMessage()); } catch (RuntimeException e) { throw e; } catch (Exception e) { // generated: catch the exception throwed by interface method and re-throw it throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } return result; } public int getKala(float kalamees) { Integer result = null; try { // invocation is also generated result = (Integer) handler.invoke(this, ProxySampleInterface_ReturnsBasic.class.getMethod("getKala", new Class[] {Float.TYPE}), new Object[] {new Float(kalamees)}); } catch (ClassCastException e) { throw e; } catch (NoSuchMethodException e) { // ignore, the method has to be found, as this class is generated } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } return result.intValue(); } /** * @see java.lang.Object#toString() */ public String toString() { String result = null; try { // invocation is also generated result = (String) handler.invoke(this, Object.class.getMethod("toString", (Class[])null), null); } catch (ClassCastException e) { throw e; } catch (NoSuchMethodException e) { // ignore, the method has to be found, as this class is generated } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Throwable e) { throw new UndeclaredThrowableException(e); } return result; } } cglib3-3.1+dfsg/src/test/net/sf/cglib/proxysample/SampleImpl.java0000644000175000017500000000176510066633124024314 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxysample; /** * @author neeme * */ public class SampleImpl implements ProxySampleInterface_ReturnsObject, ProxySampleInterface_ReturnsBasic { public String getKala(String kalamees) throws Exception { return "kala " + kalamees; } public int getKala(float kalamees) { return (int) (100 + kalamees); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/core/0000755000175000017500000000000012250627450017744 5ustar miguelmiguelcglib3-3.1+dfsg/src/test/net/sf/cglib/core/TestTinyBitSet.java0000644000175000017500000000371610066633126023514 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import net.sf.cglib.CodeGenTestCase; import junit.framework.*; public class TestTinyBitSet extends TestCase { public void testGetSetClear() { TinyBitSet b = new TinyBitSet(); assertTrue(!b.get(5)); b.set(5); assertTrue(b.get(5)); b.clear(5); assertTrue(!b.get(5)); } public void testLength() { TinyBitSet b = new TinyBitSet(); b.set(10); assertTrue(b.length() == 11); b.set(15); assertTrue(b.length() == 16); b.set(14); assertTrue(b.length() == 16); } public void testCardinality() { TinyBitSet b = new TinyBitSet(); assertTrue(b.cardinality() == 0); b.set(1); assertTrue(b.cardinality() == 1); b.set(4); assertTrue(b.cardinality() == 2); b.set(10); assertTrue(b.cardinality() == 3); b.set(10); assertTrue(b.cardinality() == 3); b.clear(10); assertTrue(b.cardinality() == 2); } public TestTinyBitSet(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestTinyBitSet.class); } } cglib3-3.1+dfsg/src/test/net/sf/cglib/core/TestKeyFactory.java0000644000175000017500000001301712250620400023515 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import junit.framework.*; import java.util.*; /** * @author Chris Nokleberg chris@nokleberg.com * @version $Id: TestKeyFactory.java,v 1.7 2012/07/27 16:02:50 baliuka Exp $ */ public class TestKeyFactory extends net.sf.cglib.CodeGenTestCase { public interface MyKey { public Object newInstance(int a, int[] b, boolean flag); } public interface MyKey2 { public Object newInstance(int[][] a); } public interface CharArrayKey { public Object newInstance(char[] a); } public interface BooleanArrayKey { public Object newInstance(boolean[] a); } public interface ClassArrayKey { public Object newInstance(Class[] a); } public interface MethodKey { public Object newInstance(Class returnType, Class[] parameterTypes); } public interface PrimitivesKey { public Object newInstance(boolean b, double d, float f, int i, long l); } public interface IntegerKey { public Object newInstance(int i); } public interface LongKey { public Object newInstance(long l); } public interface FloatKey { public Object newInstance(float f); } public void testSimple() throws Exception { MyKey mykey = (MyKey)KeyFactory.create(MyKey.class); assertTrue(mykey.newInstance(5, new int[]{ 6, 7 }, false).hashCode() == mykey.newInstance(5, new int[]{ 6, 7 }, false).hashCode()); } private Object helper(Class type) { KeyFactory.Generator gen = new KeyFactory.Generator(); gen.setInterface(type); gen.setHashConstant(5); gen.setHashMultiplier(3); return gen.create(); } public void testPrimitives() throws Exception { PrimitivesKey factory = (PrimitivesKey)helper(PrimitivesKey.class); Object instance = factory.newInstance(true, 1.234d, 5.678f, 100, 200L); assertTrue(instance.hashCode() == 1525582882); } public void testInteger() throws Exception { IntegerKey factory = (IntegerKey)helper(IntegerKey.class); Object instance = factory.newInstance(7); assertTrue(instance.hashCode() == 22); } public void testLong() throws Exception { LongKey factory = (LongKey)helper(LongKey.class); Object instance = factory.newInstance(7L); assertTrue(instance.hashCode() == 22); } public void testFloat() throws Exception { FloatKey factory = (FloatKey)helper(FloatKey.class); Object instance = factory.newInstance(7f); assertTrue(instance.hashCode() == 1088421903); } public void testNested() throws Exception { KeyFactory.Generator gen = new KeyFactory.Generator(); gen.setInterface(MyKey2.class); gen.setHashConstant(17); gen.setHashMultiplier(37); MyKey2 mykey2 = (MyKey2)gen.create(); Object instance = mykey2.newInstance(new int[][]{ { 1, 2 }, { 3, 4 } }); assertTrue(instance.hashCode() == 31914243); } public void testCharArray() throws Exception { CharArrayKey f = (CharArrayKey)KeyFactory.create(CharArrayKey.class); Object key1 = f.newInstance(new char[]{ 'a', 'b' }); Object key2 = f.newInstance(new char[]{ 'a', '_' }); assertTrue(!key1.equals(key2)); } public void testBooleanArray() throws Exception { BooleanArrayKey f = (BooleanArrayKey)KeyFactory.create(BooleanArrayKey.class); Object key1 = f.newInstance(new boolean[]{ true, false, true }); Object key2 = f.newInstance(new boolean[]{ true, false, true }); assertTrue(key1.equals(key2)); } public void testMethodKey() throws Exception { MethodKey factory = (MethodKey)KeyFactory.create(MethodKey.class); Set methodSet = new HashSet(); methodSet.add(factory.newInstance(Number.class, new Class[]{ int.class })); assertTrue(methodSet.contains(factory.newInstance(Number.class, new Class[]{ int.class }))); assertTrue(!methodSet.contains(factory.newInstance(Number.class, new Class[]{ Integer.class }))); } public void testEqualOtherClass() throws Exception { MyKey mykey = (MyKey)KeyFactory.create(MyKey.class); assertTrue(!mykey.newInstance(5, new int[]{ 6, 7 }, false).equals(new Object())); } public TestKeyFactory(String testName) { super(testName); } public static void main(String[] args) { junit.textui.TestRunner.run(suite()); } public static Test suite() { return new TestSuite(TestKeyFactory.class); } public void perform(ClassLoader loader) throws Throwable { KeyFactory.create(loader, MyKey.class, null ); } } cglib3-3.1+dfsg/src/proxy/0000755000175000017500000000000012250627450014740 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/samples/0000755000175000017500000000000012250627450016404 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/samples/Trace.java0000644000175000017500000000537507747615704020335 0ustar miguelmiguelpackage samples; import net.sf.cglib.proxy.*; import java.util.*; /** * * @author baliuka */ public class Trace implements MethodInterceptor { int ident = 1; static Trace callback = new Trace(); /** Creates a new instance of Trace */ private Trace() { } public static Object newInstance( Class clazz ){ try{ Enhancer e = new Enhancer(); e.setSuperclass(clazz); e.setCallback(callback); return e.create(); }catch( Throwable e ){ e.printStackTrace(); throw new Error(e.getMessage()); } } /** * @param args the command line arguments */ public static void main(String[] args) { List list = (List)newInstance(Vector.class); Object value = "TEST"; list.add(value); list.contains(value); try{ list.set(2, "ArrayIndexOutOfBounds" ); }catch( ArrayIndexOutOfBoundsException ignore ){ } list.add(value + "1"); list.add(value + "2"); list.toString(); list.equals(list); list.set( 0, null ); list.toString(); list.add(list); list.get(1); list.toArray(); list.remove(list); list.remove(""); list.containsAll(list); list.lastIndexOf(value); } public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable { printIdent(ident); System.out.println( method ); for( int i = 0; i < args.length; i++ ){ printIdent(ident); System.out.print( "arg" + (i + 1) + ": "); if( obj == args[i]) System.out.println("this"); else System.out.println(args[i]); } ident++; Object retValFromSuper = null; try { retValFromSuper = proxy.invokeSuper(obj, args); ident--; } catch (Throwable t) { ident--; printIdent(ident); System.out.println("throw " + t ); System.out.println(); throw t.fillInStackTrace(); } printIdent(ident); System.out.print("return " ); if( obj == retValFromSuper) System.out.println("this"); else System.out.println(retValFromSuper); if(ident == 1) System.out.println(); return retValFromSuper; } void printIdent( int ident ){ while( --ident > 0 ){ System.out.print("......."); } System.out.print(" "); } } cglib3-3.1+dfsg/src/proxy/samples/KeySample.java0000644000175000017500000000117207731111714021141 0ustar miguelmiguelpackage samples; import net.sf.cglib.core.KeyFactory; public class KeySample { private interface MyFactory { public Object newInstance(int a, char[] b, String d); } public static void main(String[] args) { MyFactory f = (MyFactory)KeyFactory.create(MyFactory.class); Object key1 = f.newInstance(20, new char[]{ 'a', 'b' }, "hello"); Object key2 = f.newInstance(20, new char[]{ 'a', 'b' }, "hello"); Object key3 = f.newInstance(20, new char[]{ 'a', '_' }, "hello"); System.out.println(key1.equals(key2)); System.out.println(key2.equals(key3)); } } cglib3-3.1+dfsg/src/proxy/samples/Beans.java0000644000175000017500000000542007747615704020316 0ustar miguelmiguel package samples; import java.beans.*; import java.lang.reflect.*; import net.sf.cglib.proxy.*; /** * * @author baliuka */ public class Beans implements MethodInterceptor { private PropertyChangeSupport propertySupport; public void addPropertyChangeListener(PropertyChangeListener listener) { propertySupport.addPropertyChangeListener(listener); } public void removePropertyChangeListener(PropertyChangeListener listener) { propertySupport.removePropertyChangeListener(listener); } public static Object newInstance( Class clazz ){ try{ Beans interceptor = new Beans(); Enhancer e = new Enhancer(); e.setSuperclass(clazz); e.setCallback(interceptor); Object bean = e.create(); interceptor.propertySupport = new PropertyChangeSupport( bean ); return bean; }catch( Throwable e ){ e.printStackTrace(); throw new Error(e.getMessage()); } } static final Class C[] = new Class[0]; static final Object emptyArgs [] = new Object[0]; public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { Object retValFromSuper = null; try { if (!Modifier.isAbstract(method.getModifiers())) { retValFromSuper = proxy.invokeSuper(obj, args); } } finally { String name = method.getName(); if( name.equals("addPropertyChangeListener")) { addPropertyChangeListener((PropertyChangeListener)args[0]); }else if ( name.equals( "removePropertyChangeListener" ) ){ removePropertyChangeListener((PropertyChangeListener)args[0]); } if( name.startsWith("set") && args.length == 1 && method.getReturnType() == Void.TYPE ){ char propName[] = name.substring("set".length()).toCharArray(); propName[0] = Character.toLowerCase( propName[0] ); propertySupport.firePropertyChange( new String( propName ) , null , args[0]); } } return retValFromSuper; } public static void main( String args[] ){ Bean bean = (Bean)newInstance( Bean.class ); bean.addPropertyChangeListener( new PropertyChangeListener(){ public void propertyChange(PropertyChangeEvent evt){ System.out.println(evt); } } ); bean.setSampleProperty("TEST"); } } cglib3-3.1+dfsg/src/proxy/samples/Bean.java0000644000175000017500000000117007616327562020126 0ustar miguelmiguelpackage samples; import java.beans.*; /** * * @author baliuka */ public abstract class Bean implements java.io.Serializable{ String sampleProperty; abstract public void addPropertyChangeListener(PropertyChangeListener listener); abstract public void removePropertyChangeListener(PropertyChangeListener listener); public String getSampleProperty(){ return sampleProperty; } public void setSampleProperty(String value){ this.sampleProperty = value; } public String toString(){ return "sampleProperty is " + sampleProperty; } } cglib3-3.1+dfsg/src/proxy/net/0000755000175000017500000000000012250627450015526 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/0000755000175000017500000000000012250627450016136 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/0000755000175000017500000000000012250627450017216 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/util/0000755000175000017500000000000012250627450020173 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/util/ParallelSorter.java0000644000175000017500000002401010066633126023766 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import java.lang.reflect.*; import java.util.Comparator; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; /** * For the efficient sorting of multiple arrays in parallel. *

* Given two arrays of equal length and varying types, the standard * technique for sorting them in parallel is to create a new temporary * object for each row, store the objects in a temporary array, sort the * array using a custom comparator, and the extract the original values * back into their respective arrays. This is wasteful in both time and * memory. *

* This class generates bytecode customized to the particular set of * arrays you need to sort, in such a way that both arrays are sorted * in-place, simultaneously. *

* Two sorting algorithms are provided. * Quicksort is best when you only need to sort by a single column, as * it requires very few comparisons and swaps. Mergesort is best used * when sorting multiple columns, as it is a "stable" sort--that is, it * does not affect the relative order of equal objects from previous sorts. *

* The mergesort algorithm here is an "in-place" variant, which while * slower, does not require a temporary array. * * @author Chris Nokleberg */ abstract public class ParallelSorter extends SorterTemplate { protected Object[] a; private Comparer comparer; protected ParallelSorter() { } abstract public ParallelSorter newInstance(Object[] arrays); /** * Create a new ParallelSorter object for a set of arrays. You may * sort the arrays multiple times via the same ParallelSorter object. * @param arrays An array of arrays to sort. The arrays may be a mix * of primitive and non-primitive types, but should all be the same * length. * @param loader ClassLoader for generated class, uses "current" if null */ public static ParallelSorter create(Object[] arrays) { Generator gen = new Generator(); gen.setArrays(arrays); return gen.create(); } private int len() { return ((Object[])a[0]).length; } /** * Sort the arrays using the quicksort algorithm. * @param index array (column) to sort by */ public void quickSort(int index) { quickSort(index, 0, len(), null); } /** * Sort the arrays using the quicksort algorithm. * @param index array (column) to sort by * @param lo starting array index (row), inclusive * @param hi ending array index (row), exclusive */ public void quickSort(int index, int lo, int hi) { quickSort(index, lo, hi, null); } /** * Sort the arrays using the quicksort algorithm. * @param index array (column) to sort by * @param cmp Comparator to use if the specified column is non-primitive */ public void quickSort(int index, Comparator cmp) { quickSort(index, 0, len(), cmp); } /** * Sort the arrays using the quicksort algorithm. * @param index array (column) to sort by * @param lo starting array index (row), inclusive * @param hi ending array index (row), exclusive * @param cmp Comparator to use if the specified column is non-primitive */ public void quickSort(int index, int lo, int hi, Comparator cmp) { chooseComparer(index, cmp); super.quickSort(lo, hi - 1); } /** * @param index array (column) to sort by */ public void mergeSort(int index) { mergeSort(index, 0, len(), null); } /** * Sort the arrays using an in-place merge sort. * @param index array (column) to sort by * @param lo starting array index (row), inclusive * @param hi ending array index (row), exclusive */ public void mergeSort(int index, int lo, int hi) { mergeSort(index, lo, hi, null); } /** * Sort the arrays using an in-place merge sort. * @param index array (column) to sort by * @param lo starting array index (row), inclusive * @param hi ending array index (row), exclusive */ public void mergeSort(int index, Comparator cmp) { mergeSort(index, 0, len(), cmp); } /** * Sort the arrays using an in-place merge sort. * @param index array (column) to sort by * @param lo starting array index (row), inclusive * @param hi ending array index (row), exclusive * @param cmp Comparator to use if the specified column is non-primitive */ public void mergeSort(int index, int lo, int hi, Comparator cmp) { chooseComparer(index, cmp); super.mergeSort(lo, hi - 1); } private void chooseComparer(int index, Comparator cmp) { Object array = a[index]; Class type = array.getClass().getComponentType(); if (type.equals(Integer.TYPE)) { comparer = new IntComparer((int[])array); } else if (type.equals(Long.TYPE)) { comparer = new LongComparer((long[])array); } else if (type.equals(Double.TYPE)) { comparer = new DoubleComparer((double[])array); } else if (type.equals(Float.TYPE)) { comparer = new FloatComparer((float[])array); } else if (type.equals(Short.TYPE)) { comparer = new ShortComparer((short[])array); } else if (type.equals(Byte.TYPE)) { comparer = new ByteComparer((byte[])array); } else if (cmp != null) { comparer = new ComparatorComparer((Object[])array, cmp); } else { comparer = new ObjectComparer((Object[])array); } } protected int compare(int i, int j) { return comparer.compare(i, j); } interface Comparer { int compare(int i, int j); } static class ComparatorComparer implements Comparer { private Object[] a; private Comparator cmp; public ComparatorComparer(Object[] a, Comparator cmp) { this.a = a; this.cmp = cmp; } public int compare(int i, int j) { return cmp.compare(a[i], a[j]); } } static class ObjectComparer implements Comparer { private Object[] a; public ObjectComparer(Object[] a) { this.a = a; } public int compare(int i, int j) { return ((Comparable)a[i]).compareTo(a[j]); } } static class IntComparer implements Comparer { private int[] a; public IntComparer(int[] a) { this.a = a; } public int compare(int i, int j) { return a[i] - a[j]; } } static class LongComparer implements Comparer { private long[] a; public LongComparer(long[] a) { this.a = a; } public int compare(int i, int j) { long vi = a[i]; long vj = a[j]; return (vi == vj) ? 0 : (vi > vj) ? 1 : -1; } } static class FloatComparer implements Comparer { private float[] a; public FloatComparer(float[] a) { this.a = a; } public int compare(int i, int j) { float vi = a[i]; float vj = a[j]; return (vi == vj) ? 0 : (vi > vj) ? 1 : -1; } } static class DoubleComparer implements Comparer { private double[] a; public DoubleComparer(double[] a) { this.a = a; } public int compare(int i, int j) { double vi = a[i]; double vj = a[j]; return (vi == vj) ? 0 : (vi > vj) ? 1 : -1; } } static class ShortComparer implements Comparer { private short[] a; public ShortComparer(short[] a) { this.a = a; } public int compare(int i, int j) { return a[i] - a[j]; } } static class ByteComparer implements Comparer { private byte[] a; public ByteComparer(byte[] a) { this.a = a; } public int compare(int i, int j) { return a[i] - a[j]; } } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(ParallelSorter.class.getName()); private Object[] arrays; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return null; // TODO } public void setArrays(Object[] arrays) { this.arrays = arrays; } public ParallelSorter create() { return (ParallelSorter)super.create(ClassesKey.create(arrays)); } public void generateClass(ClassVisitor v) throws Exception { if (arrays.length == 0) { throw new IllegalArgumentException("No arrays specified to sort"); } for (int i = 0; i < arrays.length; i++) { if (!arrays[i].getClass().isArray()) { throw new IllegalArgumentException(arrays[i].getClass() + " is not an array"); } } new ParallelSorterEmitter(v, getClassName(), arrays); } protected Object firstInstance(Class type) { return ((ParallelSorter)ReflectUtils.newInstance(type)).newInstance(arrays); } protected Object nextInstance(Object instance) { return ((ParallelSorter)instance).newInstance(arrays); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/util/StringSwitcher.java0000644000175000017500000001353410402432046024013 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; /** * This class implements a simple String->int mapping for a fixed set of keys. */ abstract public class StringSwitcher { private static final Type STRING_SWITCHER = TypeUtils.parseType("net.sf.cglib.util.StringSwitcher"); private static final Signature INT_VALUE = TypeUtils.parseSignature("int intValue(String)"); private static final StringSwitcherKey KEY_FACTORY = (StringSwitcherKey)KeyFactory.create(StringSwitcherKey.class); interface StringSwitcherKey { public Object newInstance(String[] strings, int[] ints, boolean fixedInput); } /** * Helper method to create a StringSwitcher. * For finer control over the generated instance, use a new instance of StringSwitcher.Generator * instead of this static method. * @param strings the array of String keys; must be the same length as the value array * @param ints the array of integer results; must be the same length as the key array * @param fixedInput if false, an unknown key will be returned from {@link #intValue} as -1; if true, * the result will be undefined, and the resulting code will be faster */ public static StringSwitcher create(String[] strings, int[] ints, boolean fixedInput) { Generator gen = new Generator(); gen.setStrings(strings); gen.setInts(ints); gen.setFixedInput(fixedInput); return gen.create(); } protected StringSwitcher() { } /** * Return the integer associated with the given key. * @param s the key * @return the associated integer value, or -1 if the key is unknown (unless * fixedInput was specified when this StringSwitcher was created, * in which case the return value for an unknown key is undefined) */ abstract public int intValue(String s); public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(StringSwitcher.class.getName()); private String[] strings; private int[] ints; private boolean fixedInput; public Generator() { super(SOURCE); } /** * Set the array of recognized Strings. * @param strings the array of String keys; must be the same length as the value array * @see #setInts */ public void setStrings(String[] strings) { this.strings = strings; } /** * Set the array of integer results. * @param ints the array of integer results; must be the same length as the key array * @see #setStrings */ public void setInts(int[] ints) { this.ints = ints; } /** * Configure how unknown String keys will be handled. * @param fixedInput if false, an unknown key will be returned from {@link #intValue} as -1; if true, * the result will be undefined, and the resulting code will be faster */ public void setFixedInput(boolean fixedInput) { this.fixedInput = fixedInput; } protected ClassLoader getDefaultClassLoader() { return getClass().getClassLoader(); } /** * Generate the StringSwitcher. */ public StringSwitcher create() { setNamePrefix(StringSwitcher.class.getName()); Object key = KEY_FACTORY.newInstance(strings, ints, fixedInput); return (StringSwitcher)super.create(key); } public void generateClass(ClassVisitor v) throws Exception { ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), STRING_SWITCHER, null, Constants.SOURCE_FILE); EmitUtils.null_constructor(ce); final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, INT_VALUE, null); e.load_arg(0); final List stringList = Arrays.asList(strings); int style = fixedInput ? Constants.SWITCH_STYLE_HASHONLY : Constants.SWITCH_STYLE_HASH; EmitUtils.string_switch(e, strings, style, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { e.push(ints[stringList.indexOf(key)]); e.return_value(); } public void processDefault() { e.push(-1); e.return_value(); } }); e.end_method(); ce.end_class(); } protected Object firstInstance(Class type) { return (StringSwitcher)ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/util/SorterTemplate.java0000644000175000017500000001172310066633126024014 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import java.util.*; abstract class SorterTemplate { private static final int MERGESORT_THRESHOLD = 12; private static final int QUICKSORT_THRESHOLD = 7; abstract protected void swap(int i, int j); abstract protected int compare(int i, int j); protected void quickSort(int lo, int hi) { quickSortHelper(lo, hi); insertionSort(lo, hi); } private void quickSortHelper(int lo, int hi) { for (;;) { int diff = hi - lo; if (diff <= QUICKSORT_THRESHOLD) { break; } int i = (hi + lo) / 2; if (compare(lo, i) > 0) { swap(lo, i); } if (compare(lo, hi) > 0) { swap(lo, hi); } if (compare(i, hi) > 0) { swap(i, hi); } int j = hi - 1; swap(i, j); i = lo; int v = j; for (;;) { while (compare(++i, v) < 0) { /* nothing */; } while (compare(--j, v) > 0) { /* nothing */; } if (j < i) { break; } swap(i, j); } swap(i, hi - 1); if (j - lo <= hi - i + 1) { quickSortHelper(lo, j); lo = i + 1; } else { quickSortHelper(i + 1, hi); hi = j; } } } private void insertionSort(int lo, int hi) { for (int i = lo + 1 ; i <= hi; i++) { for (int j = i; j > lo; j--) { if (compare(j - 1, j) > 0) { swap(j - 1, j); } else { break; } } } } protected void mergeSort(int lo, int hi) { int diff = hi - lo; if (diff <= MERGESORT_THRESHOLD) { insertionSort(lo, hi); return; } int mid = lo + diff / 2; mergeSort(lo, mid); mergeSort(mid, hi); merge(lo, mid, hi, mid - lo, hi - mid); } private void merge(int lo, int pivot, int hi, int len1, int len2) { if (len1 == 0 || len2 == 0) { return; } if (len1 + len2 == 2) { if (compare(pivot, lo) < 0) { swap(pivot, lo); } return; } int first_cut, second_cut; int len11, len22; if (len1 > len2) { len11 = len1 / 2; first_cut = lo + len11; second_cut = lower(pivot, hi, first_cut); len22 = second_cut - pivot; } else { len22 = len2 / 2; second_cut = pivot + len22; first_cut = upper(lo, pivot, second_cut); len11 = first_cut - lo; } rotate(first_cut, pivot, second_cut); int new_mid = first_cut + len22; merge(lo, first_cut, new_mid, len11, len22); merge(new_mid, second_cut, hi, len1 - len11, len2 - len22); } private void rotate(int lo, int mid, int hi) { int lot = lo; int hit = mid - 1; while (lot < hit) { swap(lot++, hit--); } lot = mid; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } lot = lo; hit = hi - 1; while (lot < hit) { swap(lot++, hit--); } } private int lower(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid= lo + half; if (compare(mid, val) < 0) { lo = mid + 1; len = len - half -1; } else { len = half; } } return lo; } private int upper(int lo, int hi, int val) { int len = hi - lo; while (len > 0) { int half = len / 2; int mid = lo + half; if (compare(val, mid) < 0) { len = half; } else { lo = mid + 1; len = len - half -1; } } return lo; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/util/ParallelSorterEmitter.java0000644000175000017500000000675210402432046025325 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.util; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; class ParallelSorterEmitter extends ClassEmitter { private static final Type PARALLEL_SORTER = TypeUtils.parseType("net.sf.cglib.util.ParallelSorter"); private static final Signature CSTRUCT_OBJECT_ARRAY = TypeUtils.parseConstructor("Object[]"); private static final Signature NEW_INSTANCE = new Signature("newInstance", PARALLEL_SORTER, new Type[]{ Constants.TYPE_OBJECT_ARRAY }); private static final Signature SWAP = TypeUtils.parseSignature("void swap(int, int)"); public ParallelSorterEmitter(ClassVisitor v, String className, Object[] arrays) { super(v); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, PARALLEL_SORTER, null, Constants.SOURCE_FILE); EmitUtils.null_constructor(this); EmitUtils.factory_method(this, NEW_INSTANCE); generateConstructor(arrays); generateSwap(arrays); end_class(); } private String getFieldName(int index) { return "FIELD_" + index; } private void generateConstructor(Object[] arrays) { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT_ARRAY, null); e.load_this(); e.super_invoke_constructor(); e.load_this(); e.load_arg(0); e.super_putfield("a", Constants.TYPE_OBJECT_ARRAY); for (int i = 0; i < arrays.length; i++) { Type type = Type.getType(arrays[i].getClass()); declare_field(Constants.ACC_PRIVATE, getFieldName(i), type, null); e.load_this(); e.load_arg(0); e.push(i); e.aaload(); e.checkcast(type); e.putfield(getFieldName(i)); } e.return_value(); e.end_method(); } private void generateSwap(final Object[] arrays) { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, SWAP, null); for (int i = 0; i < arrays.length; i++) { Type type = Type.getType(arrays[i].getClass()); Type component = TypeUtils.getComponentType(type); Local T = e.make_local(type); e.load_this(); e.getfield(getFieldName(i)); e.store_local(T); e.load_local(T); e.load_arg(0); e.load_local(T); e.load_arg(1); e.array_load(component); e.load_local(T); e.load_arg(1); e.load_local(T); e.load_arg(0); e.array_load(component); e.array_store(component); e.array_store(component); } e.return_value(); e.end_method(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/0000755000175000017500000000000012250627450020377 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Proxy.java0000644000175000017500000000721310066633130022361 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Member; import net.sf.cglib.core.CodeGenerationException; /** * This class is meant to be used as replacement for * java.lang.reflect.Proxy under JDK 1.2. There are some known * subtle differences: *

    *
  • The exceptions returned by invoking getExceptionTypes * on the Method passed to the invoke method * are the exact set that can be thrown without resulting in an * UndeclaredThrowableException being thrown. *
  • {@link UndeclaredThrowableException} is used instead * of java.lang.reflect.UndeclaredThrowableException. *
*

* @version $Id: Proxy.java,v 1.6 2004/06/24 21:15:19 herbyderby Exp $ */ public class Proxy implements Serializable { protected InvocationHandler h; private static final CallbackFilter BAD_OBJECT_METHOD_FILTER = new CallbackFilter() { public int accept(Method method) { if (method.getDeclaringClass().getName().equals("java.lang.Object")) { String name = method.getName(); if (!(name.equals("hashCode") || name.equals("equals") || name.equals("toString"))) { return 1; } } return 0; } }; protected Proxy(InvocationHandler h) { Enhancer.registerCallbacks(getClass(), new Callback[]{ h, null }); this.h = h; } // private for security of isProxyClass private static class ProxyImpl extends Proxy { protected ProxyImpl(InvocationHandler h) { super(h); } } public static InvocationHandler getInvocationHandler(Object proxy) { if (!(proxy instanceof ProxyImpl)) { throw new IllegalArgumentException("Object is not a proxy"); } return ((Proxy)proxy).h; } public static Class getProxyClass(ClassLoader loader, Class[] interfaces) { Enhancer e = new Enhancer(); e.setSuperclass(ProxyImpl.class); e.setInterfaces(interfaces); e.setCallbackTypes(new Class[]{ InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(BAD_OBJECT_METHOD_FILTER); e.setUseFactory(false); return e.createClass(); } public static boolean isProxyClass(Class cl) { return cl.getSuperclass().equals(ProxyImpl.class); } public static Object newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) { try { Class clazz = getProxyClass(loader, interfaces); return clazz.getConstructor(new Class[]{ InvocationHandler.class }).newInstance(new Object[]{ h }); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MethodInterceptor.java0000644000175000017500000000356010066633130024700 0ustar miguelmiguel/* * Copyright 2002,2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * General-purpose {@link Enhancer} callback which provides for "around advice". * @author Juozas Baliuka baliuka@mwm.lt * @version $Id: MethodInterceptor.java,v 1.8 2004/06/24 21:15:20 herbyderby Exp $ */ public interface MethodInterceptor extends Callback { /** * All generated proxied methods call this method instead of the original method. * The original method may either be invoked by normal reflection using the Method object, * or by using the MethodProxy (faster). * @param obj "this", the enhanced object * @param method intercepted Method * @param args argument array; primitive types are wrapped * @param proxy used to invoke super (non-intercepted method); may be called * as many times as needed * @throws Throwable any exception may be thrown; if so, super method will not be invoked * @return any value compatible with the signature of the proxied method. Method returning void will ignore this value. * @see MethodProxy */ public Object intercept(Object obj, java.lang.reflect.Method method, Object[] args, MethodProxy proxy) throws Throwable; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Callback.java0000644000175000017500000000161610066633130022735 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * All callback interfaces used by {@link Enhancer} extend this interface. * @see MethodInterceptor * @see NoOp * @see LazyLoader * @see Dispatcher * @see InvocationHandler * @see FixedValue */ public interface Callback { } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Dispatcher.java0000644000175000017500000000224310066633130023324 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * Dispatching {@link Enhancer} callback. This is identical to the * {@link LazyLoader} interface but needs to be separate so that Enhancer * knows which type of code to generate. */ public interface Dispatcher extends Callback { /** * Return the object which the original method invocation should * be dispatched. This method is called for every method invocation. * @return an object that can invoke the method */ Object loadObject() throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/InvocationHandlerGenerator.java0000644000175000017500000000526410402432050026512 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.core.*; import java.util.*; import org.objectweb.asm.Type; class InvocationHandlerGenerator implements CallbackGenerator { public static final InvocationHandlerGenerator INSTANCE = new InvocationHandlerGenerator(); private static final Type INVOCATION_HANDLER = TypeUtils.parseType("net.sf.cglib.proxy.InvocationHandler"); private static final Type UNDECLARED_THROWABLE_EXCEPTION = TypeUtils.parseType("net.sf.cglib.proxy.UndeclaredThrowableException"); private static final Type METHOD = TypeUtils.parseType("java.lang.reflect.Method"); private static final Signature INVOKE = TypeUtils.parseSignature("Object invoke(Object, java.lang.reflect.Method, Object[])"); public void generate(ClassEmitter ce, Context context, List methods) { for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); Signature impl = context.getImplSignature(method); ce.declare_field(Constants.PRIVATE_FINAL_STATIC, impl.getName(), METHOD, null); CodeEmitter e = context.beginMethod(ce, method); Block handler = e.begin_block(); context.emitCallback(e, context.getIndex(method)); e.load_this(); e.getfield(impl.getName()); e.create_arg_array(); e.invoke_interface(INVOCATION_HANDLER, INVOKE); e.unbox(method.getSignature().getReturnType()); e.return_value(); handler.end(); EmitUtils.wrap_undeclared_throwable(e, handler, method.getExceptionTypes(), UNDECLARED_THROWABLE_EXCEPTION); e.end_method(); } } public void generateStatic(CodeEmitter e, Context context, List methods) { for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); EmitUtils.load_method(e, method); e.putfield(context.getImplSignature(method).getName()); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/LazyLoader.java0000644000175000017500000000220610066633130023303 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * Lazy-loading {@link Enhancer} callback. */ public interface LazyLoader extends Callback { /** * Return the object which the original method invocation should be * dispatched. Called as soon as the first lazily-loaded method in * the enhanced instance is invoked. The same object is then used * for every future method call to the proxy instance. * @return an object that can invoke the method */ Object loadObject() throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MethodProxy.java0000644000175000017500000002065111132423734023525 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import net.sf.cglib.core.AbstractClassGenerator; import net.sf.cglib.core.CodeGenerationException; import net.sf.cglib.core.GeneratorStrategy; import net.sf.cglib.core.NamingPolicy; import net.sf.cglib.core.Signature; import net.sf.cglib.reflect.FastClass; /** * Classes generated by {@link Enhancer} pass this object to the * registered {@link MethodInterceptor} objects when an intercepted method is invoked. It can * be used to either invoke the original method, or call the same method on a different * object of the same type. * @version $Id: MethodProxy.java,v 1.16 2009/01/11 20:09:48 herbyderby Exp $ */ public class MethodProxy { private Signature sig1; private Signature sig2; private CreateInfo createInfo; private final Object initLock = new Object(); private volatile FastClassInfo fastClassInfo; /** * For internal use by {@link Enhancer} only; see the {@link net.sf.cglib.reflect.FastMethod} class * for similar functionality. */ public static MethodProxy create(Class c1, Class c2, String desc, String name1, String name2) { MethodProxy proxy = new MethodProxy(); proxy.sig1 = new Signature(name1, desc); proxy.sig2 = new Signature(name2, desc); proxy.createInfo = new CreateInfo(c1, c2); return proxy; } private void init() { /* * Using a volatile invariant allows us to initialize the FastClass and * method index pairs atomically. * * Double-checked locking is safe with volatile in Java 5. Before 1.5 this * code could allow fastClassInfo to be instantiated more than once, which * appears to be benign. */ if (fastClassInfo == null) { synchronized (initLock) { if (fastClassInfo == null) { CreateInfo ci = createInfo; FastClassInfo fci = new FastClassInfo(); fci.f1 = helper(ci, ci.c1); fci.f2 = helper(ci, ci.c2); fci.i1 = fci.f1.getIndex(sig1); fci.i2 = fci.f2.getIndex(sig2); fastClassInfo = fci; createInfo = null; } } } } private static class FastClassInfo { FastClass f1; FastClass f2; int i1; int i2; } private static class CreateInfo { Class c1; Class c2; NamingPolicy namingPolicy; GeneratorStrategy strategy; boolean attemptLoad; public CreateInfo(Class c1, Class c2) { this.c1 = c1; this.c2 = c2; AbstractClassGenerator fromEnhancer = AbstractClassGenerator.getCurrent(); if (fromEnhancer != null) { namingPolicy = fromEnhancer.getNamingPolicy(); strategy = fromEnhancer.getStrategy(); attemptLoad = fromEnhancer.getAttemptLoad(); } } } private static FastClass helper(CreateInfo ci, Class type) { FastClass.Generator g = new FastClass.Generator(); g.setType(type); g.setClassLoader(ci.c2.getClassLoader()); g.setNamingPolicy(ci.namingPolicy); g.setStrategy(ci.strategy); g.setAttemptLoad(ci.attemptLoad); return g.create(); } private MethodProxy() { } /** * Return the signature of the proxied method. */ public Signature getSignature() { return sig1; } /** * Return the name of the synthetic method created by CGLIB which is * used by {@link #invokeSuper} to invoke the superclass * (non-intercepted) method implementation. The parameter types are * the same as the proxied method. */ public String getSuperName() { return sig2.getName(); } /** * Return the {@link net.sf.cglib.reflect.FastClass} method index * for the method used by {@link #invokeSuper}. This index uniquely * identifies the method within the generated proxy, and therefore * can be useful to reference external metadata. * @see #getSuperName */ public int getSuperIndex() { init(); return fastClassInfo.i2; } // For testing FastClass getFastClass() { init(); return fastClassInfo.f1; } // For testing FastClass getSuperFastClass() { init(); return fastClassInfo.f2; } /** * Return the MethodProxy used when intercepting the method * matching the given signature. * @param type the class generated by Enhancer * @param sig the signature to match * @return the MethodProxy instance, or null if no applicable matching method is found * @throws IllegalArgumentException if the Class was not created by Enhancer or does not use a MethodInterceptor */ public static MethodProxy find(Class type, Signature sig) { try { Method m = type.getDeclaredMethod(MethodInterceptorGenerator.FIND_PROXY_NAME, MethodInterceptorGenerator.FIND_PROXY_TYPES); return (MethodProxy)m.invoke(null, new Object[]{ sig }); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Class " + type + " does not use a MethodInterceptor"); } catch (IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e); } } /** * Invoke the original method, on a different object of the same type. * @param obj the compatible object; recursion will result if you use the object passed as the first * argument to the MethodInterceptor (usually not what you want) * @param args the arguments passed to the intercepted method; you may substitute a different * argument array as long as the types are compatible * @see MethodInterceptor#intercept * @throws Throwable the bare exceptions thrown by the called method are passed through * without wrapping in an InvocationTargetException */ public Object invoke(Object obj, Object[] args) throws Throwable { try { init(); FastClassInfo fci = fastClassInfo; return fci.f1.invoke(fci.i1, obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } catch (IllegalArgumentException e) { if (fastClassInfo.i1 < 0) throw new IllegalArgumentException("Protected method: " + sig1); throw e; } } /** * Invoke the original (super) method on the specified object. * @param obj the enhanced object, must be the object passed as the first * argument to the MethodInterceptor * @param args the arguments passed to the intercepted method; you may substitute a different * argument array as long as the types are compatible * @see MethodInterceptor#intercept * @throws Throwable the bare exceptions thrown by the called method are passed through * without wrapping in an InvocationTargetException */ public Object invokeSuper(Object obj, Object[] args) throws Throwable { try { init(); FastClassInfo fci = fastClassInfo; return fci.f2.invoke(fci.i2, obj, args); } catch (InvocationTargetException e) { throw e.getTargetException(); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/InvocationHandler.java0000644000175000017500000000253110066633130024645 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; /** * {@link java.lang.reflect.InvocationHandler} replacement (unavailable under JDK 1.2). * This callback type is primarily for use by the {@link Proxy} class but * may be used with {@link Enhancer} as well. * @author Neeme Praks neeme@apache.org * @version $Id: InvocationHandler.java,v 1.3 2004/06/24 21:15:20 herbyderby Exp $ */ public interface InvocationHandler extends Callback { /** * @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object) */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MethodInterceptorGenerator.java0000644000175000017500000002313512250627534026557 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Label; import org.objectweb.asm.Type; class MethodInterceptorGenerator implements CallbackGenerator { public static final MethodInterceptorGenerator INSTANCE = new MethodInterceptorGenerator(); static final String EMPTY_ARGS_NAME = "CGLIB$emptyArgs"; static final String FIND_PROXY_NAME = "CGLIB$findMethodProxy"; static final Class[] FIND_PROXY_TYPES = { Signature.class }; private static final Type ABSTRACT_METHOD_ERROR = TypeUtils.parseType("AbstractMethodError"); private static final Type METHOD = TypeUtils.parseType("java.lang.reflect.Method"); private static final Type REFLECT_UTILS = TypeUtils.parseType("net.sf.cglib.core.ReflectUtils"); private static final Type METHOD_PROXY = TypeUtils.parseType("net.sf.cglib.proxy.MethodProxy"); private static final Type METHOD_INTERCEPTOR = TypeUtils.parseType("net.sf.cglib.proxy.MethodInterceptor"); private static final Signature GET_DECLARED_METHODS = TypeUtils.parseSignature("java.lang.reflect.Method[] getDeclaredMethods()"); private static final Signature GET_DECLARING_CLASS = TypeUtils.parseSignature("Class getDeclaringClass()"); private static final Signature FIND_METHODS = TypeUtils.parseSignature("java.lang.reflect.Method[] findMethods(String[], java.lang.reflect.Method[])"); private static final Signature MAKE_PROXY = new Signature("create", METHOD_PROXY, new Type[]{ Constants.TYPE_CLASS, Constants.TYPE_CLASS, Constants.TYPE_STRING, Constants.TYPE_STRING, Constants.TYPE_STRING }); private static final Signature INTERCEPT = new Signature("intercept", Constants.TYPE_OBJECT, new Type[]{ Constants.TYPE_OBJECT, METHOD, Constants.TYPE_OBJECT_ARRAY, METHOD_PROXY }); private static final Signature FIND_PROXY = new Signature(FIND_PROXY_NAME, METHOD_PROXY, new Type[]{ Constants.TYPE_SIGNATURE }); private static final Signature TO_STRING = TypeUtils.parseSignature("String toString()"); private static final Transformer METHOD_TO_CLASS = new Transformer(){ public Object transform(Object value) { return ((MethodInfo)value).getClassInfo(); } }; private static final Signature CSTRUCT_SIGNATURE = TypeUtils.parseConstructor("String, String"); private String getMethodField(Signature impl) { return impl.getName() + "$Method"; } private String getMethodProxyField(Signature impl) { return impl.getName() + "$Proxy"; } public void generate(ClassEmitter ce, Context context, List methods) { Map sigMap = new HashMap(); for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); Signature sig = method.getSignature(); Signature impl = context.getImplSignature(method); String methodField = getMethodField(impl); String methodProxyField = getMethodProxyField(impl); sigMap.put(sig.toString(), methodProxyField); ce.declare_field(Constants.PRIVATE_FINAL_STATIC, methodField, METHOD, null); ce.declare_field(Constants.PRIVATE_FINAL_STATIC, methodProxyField, METHOD_PROXY, null); ce.declare_field(Constants.PRIVATE_FINAL_STATIC, EMPTY_ARGS_NAME, Constants.TYPE_OBJECT_ARRAY, null); CodeEmitter e; // access method e = ce.begin_method(Constants.ACC_FINAL, impl, method.getExceptionTypes()); superHelper(e, method, context); e.return_value(); e.end_method(); // around method e = context.beginMethod(ce, method); Label nullInterceptor = e.make_label(); context.emitCallback(e, context.getIndex(method)); e.dup(); e.ifnull(nullInterceptor); e.load_this(); e.getfield(methodField); if (sig.getArgumentTypes().length == 0) { e.getfield(EMPTY_ARGS_NAME); } else { e.create_arg_array(); } e.getfield(methodProxyField); e.invoke_interface(METHOD_INTERCEPTOR, INTERCEPT); e.unbox_or_zero(sig.getReturnType()); e.return_value(); e.mark(nullInterceptor); superHelper(e, method, context); e.return_value(); e.end_method(); } generateFindProxy(ce, sigMap); } private static void superHelper(CodeEmitter e, MethodInfo method, Context context) { if (TypeUtils.isAbstract(method.getModifiers())) { e.throw_exception(ABSTRACT_METHOD_ERROR, method.toString() + " is abstract" ); } else { e.load_this(); e.load_args(); context.emitInvoke(e, method); } } public void generateStatic(CodeEmitter e, Context context, List methods) throws Exception { /* generates: static { Class thisClass = Class.forName("NameOfThisClass"); Class cls = Class.forName("java.lang.Object"); String[] sigs = new String[]{ "toString", "()Ljava/lang/String;", ... }; Method[] methods = cls.getDeclaredMethods(); methods = ReflectUtils.findMethods(sigs, methods); METHOD_0 = methods[0]; CGLIB$ACCESS_0 = MethodProxy.create(cls, thisClass, "()Ljava/lang/String;", "toString", "CGLIB$ACCESS_0"); ... } */ e.push(0); e.newarray(); e.putfield(EMPTY_ARGS_NAME); Local thisclass = e.make_local(); Local declaringclass = e.make_local(); EmitUtils.load_class_this(e); e.store_local(thisclass); Map methodsByClass = CollectionUtils.bucket(methods, METHOD_TO_CLASS); for (Iterator i = methodsByClass.keySet().iterator(); i.hasNext();) { ClassInfo classInfo = (ClassInfo)i.next(); List classMethods = (List)methodsByClass.get(classInfo); e.push(2 * classMethods.size()); e.newarray(Constants.TYPE_STRING); for (int index = 0; index < classMethods.size(); index++) { MethodInfo method = (MethodInfo)classMethods.get(index); Signature sig = method.getSignature(); e.dup(); e.push(2 * index); e.push(sig.getName()); e.aastore(); e.dup(); e.push(2 * index + 1); e.push(sig.getDescriptor()); e.aastore(); } EmitUtils.load_class(e, classInfo.getType()); e.dup(); e.store_local(declaringclass); e.invoke_virtual(Constants.TYPE_CLASS, GET_DECLARED_METHODS); e.invoke_static(REFLECT_UTILS, FIND_METHODS); for (int index = 0; index < classMethods.size(); index++) { MethodInfo method = (MethodInfo)classMethods.get(index); Signature sig = method.getSignature(); Signature impl = context.getImplSignature(method); e.dup(); e.push(index); e.array_load(METHOD); e.putfield(getMethodField(impl)); e.load_local(declaringclass); e.load_local(thisclass); e.push(sig.getDescriptor()); e.push(sig.getName()); e.push(impl.getName()); e.invoke_static(METHOD_PROXY, MAKE_PROXY); e.putfield(getMethodProxyField(impl)); } e.pop(); } } public void generateFindProxy(ClassEmitter ce, final Map sigMap) { final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC | Constants.ACC_STATIC, FIND_PROXY, null); e.load_arg(0); e.invoke_virtual(Constants.TYPE_OBJECT, TO_STRING); ObjectSwitchCallback callback = new ObjectSwitchCallback() { public void processCase(Object key, Label end) { e.getfield((String)sigMap.get(key)); e.return_value(); } public void processDefault() { e.aconst_null(); e.return_value(); } }; EmitUtils.string_switch(e, (String[])sigMap.keySet().toArray(new String[0]), Constants.SWITCH_STYLE_HASH, callback); e.end_method(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MixinEverythingEmitter.java0000644000175000017500000000347510066633130025731 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import net.sf.cglib.core.CollectionUtils; import net.sf.cglib.core.ReflectUtils; import net.sf.cglib.core.RejectModifierPredicate; import org.objectweb.asm.ClassVisitor; /** * @author Chris Nokleberg * @version $Id: MixinEverythingEmitter.java,v 1.3 2004/06/24 21:15:19 herbyderby Exp $ */ class MixinEverythingEmitter extends MixinEmitter { public MixinEverythingEmitter(ClassVisitor v, String className, Class[] classes) { super(v, className, classes, null); } protected Class[] getInterfaces(Class[] classes) { List list = new ArrayList(); for (int i = 0; i < classes.length; i++) { ReflectUtils.addAllInterfaces(classes[i], list); } return (Class[])list.toArray(new Class[list.size()]); } protected Method[] getMethods(Class type) { List methods = new ArrayList(Arrays.asList(type.getMethods())); CollectionUtils.filter(methods, new RejectModifierPredicate(Modifier.FINAL | Modifier.STATIC)); return (Method[])methods.toArray(new Method[methods.size()]); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Enhancer.java0000644000175000017500000013337612250627534023005 0ustar miguelmiguel/* * Copyright 2002,2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; import org.objectweb.asm.Label; /** * Generates dynamic subclasses to enable method interception. This * class started as a substitute for the standard Dynamic Proxy support * included with JDK 1.3, but one that allowed the proxies to extend a * concrete base class, in addition to implementing interfaces. The dynamically * generated subclasses override the non-final methods of the superclass and * have hooks which callback to user-defined interceptor * implementations. *

* The original and most general callback type is the {@link MethodInterceptor}, which * in AOP terms enables "around advice"--that is, you can invoke custom code both before * and after the invocation of the "super" method. In addition you can modify the * arguments before calling the super method, or not call it at all. *

* Although MethodInterceptor is generic enough to meet any * interception need, it is often overkill. For simplicity and performance, additional * specialized callback types, such as {@link LazyLoader} are also available. * Often a single callback will be used per enhanced class, but you can control * which callback is used on a per-method basis with a {@link CallbackFilter}. *

* The most common uses of this class are embodied in the static helper methods. For * advanced needs, such as customizing the ClassLoader to use, you should create * a new instance of Enhancer. Other classes within CGLIB follow a similar pattern. *

* All enhanced objects implement the {@link Factory} interface, unless {@link #setUseFactory} is * used to explicitly disable this feature. The Factory interface provides an API * to change the callbacks of an existing object, as well as a faster and easier way to create * new instances of the same type. *

* For an almost drop-in replacement for * java.lang.reflect.Proxy, see the {@link Proxy} class. */ public class Enhancer extends AbstractClassGenerator { private static final CallbackFilter ALL_ZERO = new CallbackFilter(){ public int accept(Method method) { return 0; } }; private static final Source SOURCE = new Source(Enhancer.class.getName()); private static final EnhancerKey KEY_FACTORY = (EnhancerKey)KeyFactory.create(EnhancerKey.class); private static final String BOUND_FIELD = "CGLIB$BOUND"; private static final String THREAD_CALLBACKS_FIELD = "CGLIB$THREAD_CALLBACKS"; private static final String STATIC_CALLBACKS_FIELD = "CGLIB$STATIC_CALLBACKS"; private static final String SET_THREAD_CALLBACKS_NAME = "CGLIB$SET_THREAD_CALLBACKS"; private static final String SET_STATIC_CALLBACKS_NAME = "CGLIB$SET_STATIC_CALLBACKS"; private static final String CONSTRUCTED_FIELD = "CGLIB$CONSTRUCTED"; private static final Type FACTORY = TypeUtils.parseType("net.sf.cglib.proxy.Factory"); private static final Type ILLEGAL_STATE_EXCEPTION = TypeUtils.parseType("IllegalStateException"); private static final Type ILLEGAL_ARGUMENT_EXCEPTION = TypeUtils.parseType("IllegalArgumentException"); private static final Type THREAD_LOCAL = TypeUtils.parseType("ThreadLocal"); private static final Type CALLBACK = TypeUtils.parseType("net.sf.cglib.proxy.Callback"); private static final Type CALLBACK_ARRAY = Type.getType(Callback[].class); private static final Signature CSTRUCT_NULL = TypeUtils.parseConstructor(""); private static final Signature SET_THREAD_CALLBACKS = new Signature(SET_THREAD_CALLBACKS_NAME, Type.VOID_TYPE, new Type[]{ CALLBACK_ARRAY }); private static final Signature SET_STATIC_CALLBACKS = new Signature(SET_STATIC_CALLBACKS_NAME, Type.VOID_TYPE, new Type[]{ CALLBACK_ARRAY }); private static final Signature NEW_INSTANCE = new Signature("newInstance", Constants.TYPE_OBJECT, new Type[]{ CALLBACK_ARRAY }); private static final Signature MULTIARG_NEW_INSTANCE = new Signature("newInstance", Constants.TYPE_OBJECT, new Type[]{ Constants.TYPE_CLASS_ARRAY, Constants.TYPE_OBJECT_ARRAY, CALLBACK_ARRAY, }); private static final Signature SINGLE_NEW_INSTANCE = new Signature("newInstance", Constants.TYPE_OBJECT, new Type[]{ CALLBACK }); private static final Signature SET_CALLBACK = new Signature("setCallback", Type.VOID_TYPE, new Type[]{ Type.INT_TYPE, CALLBACK }); private static final Signature GET_CALLBACK = new Signature("getCallback", CALLBACK, new Type[]{ Type.INT_TYPE }); private static final Signature SET_CALLBACKS = new Signature("setCallbacks", Type.VOID_TYPE, new Type[]{ CALLBACK_ARRAY }); private static final Signature GET_CALLBACKS = new Signature("getCallbacks", CALLBACK_ARRAY, new Type[0]); private static final Signature THREAD_LOCAL_GET = TypeUtils.parseSignature("Object get()"); private static final Signature THREAD_LOCAL_SET = TypeUtils.parseSignature("void set(Object)"); private static final Signature BIND_CALLBACKS = TypeUtils.parseSignature("void CGLIB$BIND_CALLBACKS(Object)"); /** Internal interface, only public due to ClassLoader issues. */ public interface EnhancerKey { public Object newInstance(String type, String[] interfaces, CallbackFilter filter, Type[] callbackTypes, boolean useFactory, boolean interceptDuringConstruction, Long serialVersionUID); } private Class[] interfaces; private CallbackFilter filter; private Callback[] callbacks; private Type[] callbackTypes; private boolean classOnly; private Class superclass; private Class[] argumentTypes; private Object[] arguments; private boolean useFactory = true; private Long serialVersionUID; private boolean interceptDuringConstruction = true; /** * Create a new Enhancer. A new Enhancer * object should be used for each generated object, and should not * be shared across threads. To create additional instances of a * generated class, use the Factory interface. * @see Factory */ public Enhancer() { super(SOURCE); } /** * Set the class which the generated class will extend. As a convenience, * if the supplied superclass is actually an interface, setInterfaces * will be called with the appropriate argument instead. * A non-interface argument must not be declared as final, and must have an * accessible constructor. * @param superclass class to extend or interface to implement * @see #setInterfaces(Class[]) */ public void setSuperclass(Class superclass) { if (superclass != null && superclass.isInterface()) { setInterfaces(new Class[]{ superclass }); } else if (superclass != null && superclass.equals(Object.class)) { // affects choice of ClassLoader this.superclass = null; } else { this.superclass = superclass; } } /** * Set the interfaces to implement. The Factory interface will * always be implemented regardless of what is specified here. * @param interfaces array of interfaces to implement, or null * @see Factory */ public void setInterfaces(Class[] interfaces) { this.interfaces = interfaces; } /** * Set the {@link CallbackFilter} used to map the generated class' methods * to a particular callback index. * New object instances will always use the same mapping, but may use different * actual callback objects. * @param filter the callback filter to use when generating a new class * @see #setCallbacks */ public void setCallbackFilter(CallbackFilter filter) { this.filter = filter; } /** * Set the single {@link Callback} to use. * Ignored if you use {@link #createClass}. * @param callback the callback to use for all methods * @see #setCallbacks */ public void setCallback(final Callback callback) { setCallbacks(new Callback[]{ callback }); } /** * Set the array of callbacks to use. * Ignored if you use {@link #createClass}. * You must use a {@link CallbackFilter} to specify the index into this * array for each method in the proxied class. * @param callbacks the callback array * @see #setCallbackFilter * @see #setCallback */ public void setCallbacks(Callback[] callbacks) { if (callbacks != null && callbacks.length == 0) { throw new IllegalArgumentException("Array cannot be empty"); } this.callbacks = callbacks; } /** * Set whether the enhanced object instances should implement * the {@link Factory} interface. * This was added for tools that need for proxies to be more * indistinguishable from their targets. Also, in some cases it may * be necessary to disable the Factory interface to * prevent code from changing the underlying callbacks. * @param useFactory whether to implement Factory; default is true */ public void setUseFactory(boolean useFactory) { this.useFactory = useFactory; } /** * Set whether methods called from within the proxy's constructer * will be intercepted. The default value is true. Unintercepted methods * will call the method of the proxy's base class, if it exists. * @param interceptDuringConstruction whether to intercept methods called from the constructor */ public void setInterceptDuringConstruction(boolean interceptDuringConstruction) { this.interceptDuringConstruction = interceptDuringConstruction; } /** * Set the single type of {@link Callback} to use. * This may be used instead of {@link #setCallback} when calling * {@link #createClass}, since it may not be possible to have * an array of actual callback instances. * @param callbackType the type of callback to use for all methods * @see #setCallbackTypes */ public void setCallbackType(Class callbackType) { setCallbackTypes(new Class[]{ callbackType }); } /** * Set the array of callback types to use. * This may be used instead of {@link #setCallbacks} when calling * {@link #createClass}, since it may not be possible to have * an array of actual callback instances. * You must use a {@link CallbackFilter} to specify the index into this * array for each method in the proxied class. * @param callbackTypes the array of callback types */ public void setCallbackTypes(Class[] callbackTypes) { if (callbackTypes != null && callbackTypes.length == 0) { throw new IllegalArgumentException("Array cannot be empty"); } this.callbackTypes = CallbackInfo.determineTypes(callbackTypes); } /** * Generate a new class if necessary and uses the specified * callbacks (if any) to create a new object instance. * Uses the no-arg constructor of the superclass. * @return a new instance */ public Object create() { classOnly = false; argumentTypes = null; return createHelper(); } /** * Generate a new class if necessary and uses the specified * callbacks (if any) to create a new object instance. * Uses the constructor of the superclass matching the argumentTypes * parameter, with the given arguments. * @param argumentTypes constructor signature * @param arguments compatible wrapped arguments to pass to constructor * @return a new instance */ public Object create(Class[] argumentTypes, Object[] arguments) { classOnly = false; if (argumentTypes == null || arguments == null || argumentTypes.length != arguments.length) { throw new IllegalArgumentException("Arguments must be non-null and of equal length"); } this.argumentTypes = argumentTypes; this.arguments = arguments; return createHelper(); } /** * Generate a new class if necessary and return it without creating a new instance. * This ignores any callbacks that have been set. * To create a new instance you will have to use reflection, and methods * called during the constructor will not be intercepted. To avoid this problem, * use the multi-arg create method. * @see #create(Class[], Object[]) */ public Class createClass() { classOnly = true; return (Class)createHelper(); } /** * Insert a static serialVersionUID field into the generated class. * @param sUID the field value, or null to avoid generating field. */ public void setSerialVersionUID(Long sUID) { serialVersionUID = sUID; } private void validate() { if (classOnly ^ (callbacks == null)) { if (classOnly) { throw new IllegalStateException("createClass does not accept callbacks"); } else { throw new IllegalStateException("Callbacks are required"); } } if (classOnly && (callbackTypes == null)) { throw new IllegalStateException("Callback types are required"); } if (callbacks != null && callbackTypes != null) { if (callbacks.length != callbackTypes.length) { throw new IllegalStateException("Lengths of callback and callback types array must be the same"); } Type[] check = CallbackInfo.determineTypes(callbacks); for (int i = 0; i < check.length; i++) { if (!check[i].equals(callbackTypes[i])) { throw new IllegalStateException("Callback " + check[i] + " is not assignable to " + callbackTypes[i]); } } } else if (callbacks != null) { callbackTypes = CallbackInfo.determineTypes(callbacks); } if (filter == null) { if (callbackTypes.length > 1) { throw new IllegalStateException("Multiple callback types possible but no filter specified"); } filter = ALL_ZERO; } if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { if (interfaces[i] == null) { throw new IllegalStateException("Interfaces cannot be null"); } if (!interfaces[i].isInterface()) { throw new IllegalStateException(interfaces[i] + " is not an interface"); } } } } private Object createHelper() { validate(); if (superclass != null) { setNamePrefix(superclass.getName()); } else if (interfaces != null) { setNamePrefix(interfaces[ReflectUtils.findPackageProtected(interfaces)].getName()); } return super.create(KEY_FACTORY.newInstance((superclass != null) ? superclass.getName() : null, ReflectUtils.getNames(interfaces), filter, callbackTypes, useFactory, interceptDuringConstruction, serialVersionUID)); } protected ClassLoader getDefaultClassLoader() { if (superclass != null) { return superclass.getClassLoader(); } else if (interfaces != null) { return interfaces[0].getClassLoader(); } else { return null; } } private Signature rename(Signature sig, int index) { return new Signature("CGLIB$" + sig.getName() + "$" + index, sig.getDescriptor()); } /** * Finds all of the methods that will be extended by an * Enhancer-generated class using the specified superclass and * interfaces. This can be useful in building a list of Callback * objects. The methods are added to the end of the given list. Due * to the subclassing nature of the classes generated by Enhancer, * the methods are guaranteed to be non-static, non-final, and * non-private. Each method signature will only occur once, even if * it occurs in multiple classes. * @param superclass the class that will be extended, or null * @param interfaces the list of interfaces that will be implemented, or null * @param methods the list into which to copy the applicable methods */ public static void getMethods(Class superclass, Class[] interfaces, List methods) { getMethods(superclass, interfaces, methods, null, null); } private static void getMethods(Class superclass, Class[] interfaces, List methods, List interfaceMethods, Set forcePublic) { ReflectUtils.addAllMethods(superclass, methods); List target = (interfaceMethods != null) ? interfaceMethods : methods; if (interfaces != null) { for (int i = 0; i < interfaces.length; i++) { if (interfaces[i] != Factory.class) { ReflectUtils.addAllMethods(interfaces[i], target); } } } if (interfaceMethods != null) { if (forcePublic != null) { forcePublic.addAll(MethodWrapper.createSet(interfaceMethods)); } methods.addAll(interfaceMethods); } CollectionUtils.filter(methods, new RejectModifierPredicate(Constants.ACC_STATIC)); CollectionUtils.filter(methods, new VisibilityPredicate(superclass, true)); CollectionUtils.filter(methods, new DuplicatesPredicate()); CollectionUtils.filter(methods, new RejectModifierPredicate(Constants.ACC_FINAL)); } public void generateClass(ClassVisitor v) throws Exception { Class sc = (superclass == null) ? Object.class : superclass; if (TypeUtils.isFinal(sc.getModifiers())) throw new IllegalArgumentException("Cannot subclass final class " + sc); List constructors = new ArrayList(Arrays.asList(sc.getDeclaredConstructors())); filterConstructors(sc, constructors); // Order is very important: must add superclass, then // its superclass chain, then each interface and // its superinterfaces. List actualMethods = new ArrayList(); List interfaceMethods = new ArrayList(); final Set forcePublic = new HashSet(); getMethods(sc, interfaces, actualMethods, interfaceMethods, forcePublic); List methods = CollectionUtils.transform(actualMethods, new Transformer() { public Object transform(Object value) { Method method = (Method)value; int modifiers = Constants.ACC_FINAL | (method.getModifiers() & ~Constants.ACC_ABSTRACT & ~Constants.ACC_NATIVE & ~Constants.ACC_SYNCHRONIZED); if (forcePublic.contains(MethodWrapper.create(method))) { modifiers = (modifiers & ~Constants.ACC_PROTECTED) | Constants.ACC_PUBLIC; } return ReflectUtils.getMethodInfo(method, modifiers); } }); ClassEmitter e = new ClassEmitter(v); e.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), Type.getType(sc), (useFactory ? TypeUtils.add(TypeUtils.getTypes(interfaces), FACTORY) : TypeUtils.getTypes(interfaces)), Constants.SOURCE_FILE); List constructorInfo = CollectionUtils.transform(constructors, MethodInfoTransformer.getInstance()); e.declare_field(Constants.ACC_PRIVATE, BOUND_FIELD, Type.BOOLEAN_TYPE, null); if (!interceptDuringConstruction) { e.declare_field(Constants.ACC_PRIVATE, CONSTRUCTED_FIELD, Type.BOOLEAN_TYPE, null); } e.declare_field(Constants.PRIVATE_FINAL_STATIC, THREAD_CALLBACKS_FIELD, THREAD_LOCAL, null); e.declare_field(Constants.PRIVATE_FINAL_STATIC, STATIC_CALLBACKS_FIELD, CALLBACK_ARRAY, null); if (serialVersionUID != null) { e.declare_field(Constants.PRIVATE_FINAL_STATIC, Constants.SUID_FIELD_NAME, Type.LONG_TYPE, serialVersionUID); } for (int i = 0; i < callbackTypes.length; i++) { e.declare_field(Constants.ACC_PRIVATE, getCallbackField(i), callbackTypes[i], null); } emitMethods(e, methods, actualMethods); emitConstructors(e, constructorInfo); emitSetThreadCallbacks(e); emitSetStaticCallbacks(e); emitBindCallbacks(e); if (useFactory) { int[] keys = getCallbackKeys(); emitNewInstanceCallbacks(e); emitNewInstanceCallback(e); emitNewInstanceMultiarg(e, constructorInfo); emitGetCallback(e, keys); emitSetCallback(e, keys); emitGetCallbacks(e); emitSetCallbacks(e); } e.end_class(); } /** * Filter the list of constructors from the superclass. The * constructors which remain will be included in the generated * class. The default implementation is to filter out all private * constructors, but subclasses may extend Enhancer to override this * behavior. * @param sc the superclass * @param constructors the list of all declared constructors from the superclass * @throws IllegalArgumentException if there are no non-private constructors */ protected void filterConstructors(Class sc, List constructors) { CollectionUtils.filter(constructors, new VisibilityPredicate(sc, true)); if (constructors.size() == 0) throw new IllegalArgumentException("No visible constructors in " + sc); } protected Object firstInstance(Class type) throws Exception { if (classOnly) { return type; } else { return createUsingReflection(type); } } protected Object nextInstance(Object instance) { Class protoclass = (instance instanceof Class) ? (Class)instance : instance.getClass(); if (classOnly) { return protoclass; } else if (instance instanceof Factory) { if (argumentTypes != null) { return ((Factory)instance).newInstance(argumentTypes, arguments, callbacks); } else { return ((Factory)instance).newInstance(callbacks); } } else { return createUsingReflection(protoclass); } } /** * Call this method to register the {@link Callback} array to use before * creating a new instance of the generated class via reflection. If you are using * an instance of Enhancer or the {@link Factory} interface to create * new instances, this method is unnecessary. Its primary use is for when you want to * cache and reuse a generated class yourself, and the generated class does * not implement the {@link Factory} interface. *

* Note that this method only registers the callbacks on the current thread. * If you want to register callbacks for instances created by multiple threads, * use {@link #registerStaticCallbacks}. *

* The registered callbacks are overwritten and subsequently cleared * when calling any of the create methods (such as * {@link #create}), or any {@link Factory} newInstance method. * Otherwise they are not cleared, and you should be careful to set them * back to null after creating new instances via reflection if * memory leakage is a concern. * @param generatedClass a class previously created by {@link Enhancer} * @param callbacks the array of callbacks to use when instances of the generated * class are created * @see #setUseFactory */ public static void registerCallbacks(Class generatedClass, Callback[] callbacks) { setThreadCallbacks(generatedClass, callbacks); } /** * Similar to {@link #registerCallbacks}, but suitable for use * when multiple threads will be creating instances of the generated class. * The thread-level callbacks will always override the static callbacks. * Static callbacks are never cleared. * @param generatedClass a class previously created by {@link Enhancer} * @param callbacks the array of callbacks to use when instances of the generated * class are created */ public static void registerStaticCallbacks(Class generatedClass, Callback[] callbacks) { setCallbacksHelper(generatedClass, callbacks, SET_STATIC_CALLBACKS_NAME); } /** * Determine if a class was generated using Enhancer. * @param type any class * @return whether the class was generated using Enhancer */ public static boolean isEnhanced(Class type) { try { getCallbacksSetter(type, SET_THREAD_CALLBACKS_NAME); return true; } catch (NoSuchMethodException e) { return false; } } private static void setThreadCallbacks(Class type, Callback[] callbacks) { setCallbacksHelper(type, callbacks, SET_THREAD_CALLBACKS_NAME); } private static void setCallbacksHelper(Class type, Callback[] callbacks, String methodName) { // TODO: optimize try { Method setter = getCallbacksSetter(type, methodName); setter.invoke(null, new Object[]{ callbacks }); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(type + " is not an enhanced class"); } catch (IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e); } } private static Method getCallbacksSetter(Class type, String methodName) throws NoSuchMethodException { return type.getDeclaredMethod(methodName, new Class[]{ Callback[].class }); } private Object createUsingReflection(Class type) { setThreadCallbacks(type, callbacks); try{ if (argumentTypes != null) { return ReflectUtils.newInstance(type, argumentTypes, arguments); } else { return ReflectUtils.newInstance(type); } }finally{ // clear thread callbacks to allow them to be gc'd setThreadCallbacks(type, null); } } /** * Helper method to create an intercepted object. * For finer control over the generated instance, use a new instance of Enhancer * instead of this static method. * @param type class to extend or interface to implement * @param callback the callback to use for all methods */ public static Object create(Class type, Callback callback) { Enhancer e = new Enhancer(); e.setSuperclass(type); e.setCallback(callback); return e.create(); } /** * Helper method to create an intercepted object. * For finer control over the generated instance, use a new instance of Enhancer * instead of this static method. * @param type class to extend or interface to implement * @param interfaces array of interfaces to implement, or null * @param callback the callback to use for all methods */ public static Object create(Class superclass, Class interfaces[], Callback callback) { Enhancer e = new Enhancer(); e.setSuperclass(superclass); e.setInterfaces(interfaces); e.setCallback(callback); return e.create(); } /** * Helper method to create an intercepted object. * For finer control over the generated instance, use a new instance of Enhancer * instead of this static method. * @param type class to extend or interface to implement * @param interfaces array of interfaces to implement, or null * @param filter the callback filter to use when generating a new class * @param callbacks callback implementations to use for the enhanced object */ public static Object create(Class superclass, Class[] interfaces, CallbackFilter filter, Callback[] callbacks) { Enhancer e = new Enhancer(); e.setSuperclass(superclass); e.setInterfaces(interfaces); e.setCallbackFilter(filter); e.setCallbacks(callbacks); return e.create(); } private void emitConstructors(ClassEmitter ce, List constructors) { boolean seenNull = false; for (Iterator it = constructors.iterator(); it.hasNext();) { MethodInfo constructor = (MethodInfo)it.next(); CodeEmitter e = EmitUtils.begin_method(ce, constructor, Constants.ACC_PUBLIC); e.load_this(); e.dup(); e.load_args(); Signature sig = constructor.getSignature(); seenNull = seenNull || sig.getDescriptor().equals("()V"); e.super_invoke_constructor(sig); e.invoke_static_this(BIND_CALLBACKS); if (!interceptDuringConstruction) { e.load_this(); e.push(1); e.putfield(CONSTRUCTED_FIELD); } e.return_value(); e.end_method(); } if (!classOnly && !seenNull && arguments == null) throw new IllegalArgumentException("Superclass has no null constructors but no arguments were given"); } private int[] getCallbackKeys() { int[] keys = new int[callbackTypes.length]; for (int i = 0; i < callbackTypes.length; i++) { keys[i] = i; } return keys; } private void emitGetCallback(ClassEmitter ce, int[] keys) { final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, GET_CALLBACK, null); e.load_this(); e.invoke_static_this(BIND_CALLBACKS); e.load_this(); e.load_arg(0); e.process_switch(keys, new ProcessSwitchCallback() { public void processCase(int key, Label end) { e.getfield(getCallbackField(key)); e.goTo(end); } public void processDefault() { e.pop(); // stack height e.aconst_null(); } }); e.return_value(); e.end_method(); } private void emitSetCallback(ClassEmitter ce, int[] keys) { final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, SET_CALLBACK, null); e.load_arg(0); e.process_switch(keys, new ProcessSwitchCallback() { public void processCase(int key, Label end) { e.load_this(); e.load_arg(1); e.checkcast(callbackTypes[key]); e.putfield(getCallbackField(key)); e.goTo(end); } public void processDefault() { // TODO: error? } }); e.return_value(); e.end_method(); } private void emitSetCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, SET_CALLBACKS, null); e.load_this(); e.load_arg(0); for (int i = 0; i < callbackTypes.length; i++) { e.dup2(); e.aaload(i); e.checkcast(callbackTypes[i]); e.putfield(getCallbackField(i)); } e.return_value(); e.end_method(); } private void emitGetCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, GET_CALLBACKS, null); e.load_this(); e.invoke_static_this(BIND_CALLBACKS); e.load_this(); e.push(callbackTypes.length); e.newarray(CALLBACK); for (int i = 0; i < callbackTypes.length; i++) { e.dup(); e.push(i); e.load_this(); e.getfield(getCallbackField(i)); e.aastore(); } e.return_value(); e.end_method(); } private void emitNewInstanceCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, NEW_INSTANCE, null); e.load_arg(0); e.invoke_static_this(SET_THREAD_CALLBACKS); emitCommonNewInstance(e); } private void emitCommonNewInstance(CodeEmitter e) { e.new_instance_this(); e.dup(); e.invoke_constructor_this(); e.aconst_null(); e.invoke_static_this(SET_THREAD_CALLBACKS); e.return_value(); e.end_method(); } private void emitNewInstanceCallback(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, SINGLE_NEW_INSTANCE, null); switch (callbackTypes.length) { case 0: // TODO: make sure Callback is null break; case 1: // for now just make a new array; TODO: optimize e.push(1); e.newarray(CALLBACK); e.dup(); e.push(0); e.load_arg(0); e.aastore(); e.invoke_static_this(SET_THREAD_CALLBACKS); break; default: e.throw_exception(ILLEGAL_STATE_EXCEPTION, "More than one callback object required"); } emitCommonNewInstance(e); } private void emitNewInstanceMultiarg(ClassEmitter ce, List constructors) { final CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, MULTIARG_NEW_INSTANCE, null); e.load_arg(2); e.invoke_static_this(SET_THREAD_CALLBACKS); e.new_instance_this(); e.dup(); e.load_arg(0); EmitUtils.constructor_switch(e, constructors, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { MethodInfo constructor = (MethodInfo)key; Type types[] = constructor.getSignature().getArgumentTypes(); for (int i = 0; i < types.length; i++) { e.load_arg(1); e.push(i); e.aaload(); e.unbox(types[i]); } e.invoke_constructor_this(constructor.getSignature()); e.goTo(end); } public void processDefault() { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Constructor not found"); } }); e.aconst_null(); e.invoke_static_this(SET_THREAD_CALLBACKS); e.return_value(); e.end_method(); } private void emitMethods(final ClassEmitter ce, List methods, List actualMethods) { CallbackGenerator[] generators = CallbackInfo.getGenerators(callbackTypes); Map groups = new HashMap(); final Map indexes = new HashMap(); final Map originalModifiers = new HashMap(); final Map positions = CollectionUtils.getIndexMap(methods); final Map declToBridge = new HashMap(); Iterator it1 = methods.iterator(); Iterator it2 = (actualMethods != null) ? actualMethods.iterator() : null; while (it1.hasNext()) { MethodInfo method = (MethodInfo)it1.next(); Method actualMethod = (it2 != null) ? (Method)it2.next() : null; int index = filter.accept(actualMethod); if (index >= callbackTypes.length) { throw new IllegalArgumentException("Callback filter returned an index that is too large: " + index); } originalModifiers.put(method, new Integer((actualMethod != null) ? actualMethod.getModifiers() : method.getModifiers())); indexes.put(method, new Integer(index)); List group = (List)groups.get(generators[index]); if (group == null) { groups.put(generators[index], group = new ArrayList(methods.size())); } group.add(method); // Optimization: build up a map of Class -> bridge methods in class // so that we can look up all the bridge methods in one pass for a class. if (TypeUtils.isBridge(actualMethod.getModifiers())) { Set bridges = (Set)declToBridge.get(actualMethod.getDeclaringClass()); if (bridges == null) { bridges = new HashSet(); declToBridge.put(actualMethod.getDeclaringClass(), bridges); } bridges.add(method.getSignature()); } } final Map bridgeToTarget = new BridgeMethodResolver(declToBridge).resolveAll(); Set seenGen = new HashSet(); CodeEmitter se = ce.getStaticHook(); se.new_instance(THREAD_LOCAL); se.dup(); se.invoke_constructor(THREAD_LOCAL, CSTRUCT_NULL); se.putfield(THREAD_CALLBACKS_FIELD); final Object[] state = new Object[1]; CallbackGenerator.Context context = new CallbackGenerator.Context() { public ClassLoader getClassLoader() { return Enhancer.this.getClassLoader(); } public int getOriginalModifiers(MethodInfo method) { return ((Integer)originalModifiers.get(method)).intValue(); } public int getIndex(MethodInfo method) { return ((Integer)indexes.get(method)).intValue(); } public void emitCallback(CodeEmitter e, int index) { emitCurrentCallback(e, index); } public Signature getImplSignature(MethodInfo method) { return rename(method.getSignature(), ((Integer)positions.get(method)).intValue()); } public void emitInvoke(CodeEmitter e, MethodInfo method) { // If this is a bridge and we know the target was called from invokespecial, // then we need to invoke_virtual w/ the bridge target instead of doing // a super, because super may itself be using super, which would bypass // any proxies on the target. Signature bridgeTarget = (Signature)bridgeToTarget.get(method.getSignature()); if (bridgeTarget != null) { // TODO: this assumes that the target has wider or the same type // parameters than the current. // In reality this should always be true because otherwise we wouldn't // have had a bridge doing an invokespecial. // If it isn't true, we would need to checkcast each argument // against the target's argument types e.invoke_virtual_this(bridgeTarget); Type retType = method.getSignature().getReturnType(); // Not necessary to cast if the target & bridge have // the same return type. // (This conveniently includes void and primitive types, // which would fail if casted. It's not possible to // covariant from boxed to unbox (or vice versa), so no having // to box/unbox for bridges). // TODO: It also isn't necessary to checkcast if the return is // assignable from the target. (This would happen if a subclass // used covariant returns to narrow the return type within a bridge // method.) if (!retType.equals(bridgeTarget.getReturnType())) { e.checkcast(retType); } } else { e.super_invoke(method.getSignature()); } } public CodeEmitter beginMethod(ClassEmitter ce, MethodInfo method) { CodeEmitter e = EmitUtils.begin_method(ce, method); if (!interceptDuringConstruction && !TypeUtils.isAbstract(method.getModifiers())) { Label constructed = e.make_label(); e.load_this(); e.getfield(CONSTRUCTED_FIELD); e.if_jump(e.NE, constructed); e.load_this(); e.load_args(); e.super_invoke(); e.return_value(); e.mark(constructed); } return e; } }; for (int i = 0; i < callbackTypes.length; i++) { CallbackGenerator gen = generators[i]; if (!seenGen.contains(gen)) { seenGen.add(gen); final List fmethods = (List)groups.get(gen); if (fmethods != null) { try { gen.generate(ce, context, fmethods); gen.generateStatic(se, context, fmethods); } catch (RuntimeException x) { throw x; } catch (Exception x) { throw new CodeGenerationException(x); } } } } se.return_value(); se.end_method(); } private void emitSetThreadCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC | Constants.ACC_STATIC, SET_THREAD_CALLBACKS, null); e.getfield(THREAD_CALLBACKS_FIELD); e.load_arg(0); e.invoke_virtual(THREAD_LOCAL, THREAD_LOCAL_SET); e.return_value(); e.end_method(); } private void emitSetStaticCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC | Constants.ACC_STATIC, SET_STATIC_CALLBACKS, null); e.load_arg(0); e.putfield(STATIC_CALLBACKS_FIELD); e.return_value(); e.end_method(); } private void emitCurrentCallback(CodeEmitter e, int index) { e.load_this(); e.getfield(getCallbackField(index)); e.dup(); Label end = e.make_label(); e.ifnonnull(end); e.pop(); // stack height e.load_this(); e.invoke_static_this(BIND_CALLBACKS); e.load_this(); e.getfield(getCallbackField(index)); e.mark(end); } private void emitBindCallbacks(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.PRIVATE_FINAL_STATIC, BIND_CALLBACKS, null); Local me = e.make_local(); e.load_arg(0); e.checkcast_this(); e.store_local(me); Label end = e.make_label(); e.load_local(me); e.getfield(BOUND_FIELD); e.if_jump(e.NE, end); e.load_local(me); e.push(1); e.putfield(BOUND_FIELD); e.getfield(THREAD_CALLBACKS_FIELD); e.invoke_virtual(THREAD_LOCAL, THREAD_LOCAL_GET); e.dup(); Label found_callback = e.make_label(); e.ifnonnull(found_callback); e.pop(); e.getfield(STATIC_CALLBACKS_FIELD); e.dup(); e.ifnonnull(found_callback); e.pop(); e.goTo(end); e.mark(found_callback); e.checkcast(CALLBACK_ARRAY); e.load_local(me); e.swap(); for (int i = callbackTypes.length - 1; i >= 0; i--) { if (i != 0) { e.dup2(); } e.aaload(i); e.checkcast(callbackTypes[i]); e.putfield(getCallbackField(i)); } e.mark(end); e.return_value(); e.end_method(); } private static String getCallbackField(int index) { return "CGLIB$CALLBACK_" + index; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MixinBeanEmitter.java0000644000175000017500000000246010066633130024443 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; import net.sf.cglib.core.ReflectUtils; import org.objectweb.asm.ClassVisitor; /** * @author Chris Nokleberg * @version $Id: MixinBeanEmitter.java,v 1.2 2004/06/24 21:15:20 herbyderby Exp $ */ class MixinBeanEmitter extends MixinEmitter { public MixinBeanEmitter(ClassVisitor v, String className, Class[] classes) { super(v, className, classes, null); } protected Class[] getInterfaces(Class[] classes) { return null; } protected Method[] getMethods(Class type) { return ReflectUtils.getPropertyMethods(ReflectUtils.getBeanProperties(type), true, true); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/CallbackGenerator.java0000644000175000017500000000250312250620400024571 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.util.List; import net.sf.cglib.core.*; interface CallbackGenerator { void generate(ClassEmitter ce, Context context, List methods) throws Exception; void generateStatic(CodeEmitter e, Context context, List methods) throws Exception; interface Context { ClassLoader getClassLoader(); CodeEmitter beginMethod(ClassEmitter ce, MethodInfo method); int getOriginalModifiers(MethodInfo method); int getIndex(MethodInfo method); void emitCallback(CodeEmitter ce, int index); Signature getImplSignature(MethodInfo method); void emitInvoke(CodeEmitter e, MethodInfo method); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/ProxyRefDispatcher.java0000644000175000017500000000233210156243316025025 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * Dispatching {@link Enhancer} callback. This is the same as the * {@link Dispatcher} except for the addition of an argument * which references the proxy object. */ public interface ProxyRefDispatcher extends Callback { /** * Return the object which the original method invocation should * be dispatched. This method is called for every method invocation. * @param proxy a reference to the proxy (generated) object * @return an object that can invoke the method */ Object loadObject(Object proxy) throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Mixin.java0000644000175000017500000002041410316221024022313 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Constructor; import java.lang.reflect.Modifier; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; /** * Mixin allows * multiple objects to be combined into a single larger object. The * methods in the generated object simply call the original methods in the * underlying "delegate" objects. * @author Chris Nokleberg * @version $Id: Mixin.java,v 1.7 2005/09/27 11:42:27 baliuka Exp $ */ abstract public class Mixin { private static final MixinKey KEY_FACTORY = (MixinKey)KeyFactory.create(MixinKey.class, KeyFactory.CLASS_BY_NAME); private static final Map ROUTE_CACHE = Collections.synchronizedMap(new HashMap()); public static final int STYLE_INTERFACES = 0; public static final int STYLE_BEANS = 1; public static final int STYLE_EVERYTHING = 2; interface MixinKey { public Object newInstance(int style, String[] classes, int[] route); } abstract public Mixin newInstance(Object[] delegates); /** * Helper method to create an interface mixin. For finer control over the * generated instance, use a new instance of Mixin * instead of this static method. * TODO */ public static Mixin create(Object[] delegates) { Generator gen = new Generator(); gen.setDelegates(delegates); return gen.create(); } /** * Helper method to create an interface mixin. For finer control over the * generated instance, use a new instance of Mixin * instead of this static method. * TODO */ public static Mixin create(Class[] interfaces, Object[] delegates) { Generator gen = new Generator(); gen.setClasses(interfaces); gen.setDelegates(delegates); return gen.create(); } public static Mixin createBean(Object[] beans) { return createBean(null, beans); } /** * Helper method to create a bean mixin. For finer control over the * generated instance, use a new instance of Mixin * instead of this static method. * TODO */ public static Mixin createBean(ClassLoader loader,Object[] beans) { Generator gen = new Generator(); gen.setStyle(STYLE_BEANS); gen.setDelegates(beans); gen.setClassLoader(loader); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(Mixin.class.getName()); private Class[] classes; private Object[] delegates; private int style = STYLE_INTERFACES; private int[] route; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return classes[0].getClassLoader(); // is this right? } public void setStyle(int style) { switch (style) { case STYLE_INTERFACES: case STYLE_BEANS: case STYLE_EVERYTHING: this.style = style; break; default: throw new IllegalArgumentException("Unknown mixin style: " + style); } } public void setClasses(Class[] classes) { this.classes = classes; } public void setDelegates(Object[] delegates) { this.delegates = delegates; } public Mixin create() { if (classes == null && delegates == null) { throw new IllegalStateException("Either classes or delegates must be set"); } switch (style) { case STYLE_INTERFACES: if (classes == null) { Route r = route(delegates); classes = r.classes; route = r.route; } break; case STYLE_BEANS: // fall-through case STYLE_EVERYTHING: if (classes == null) { classes = ReflectUtils.getClasses(delegates); } else { if (delegates != null) { Class[] temp = ReflectUtils.getClasses(delegates); if (classes.length != temp.length) { throw new IllegalStateException("Specified classes are incompatible with delegates"); } for (int i = 0; i < classes.length; i++) { if (!classes[i].isAssignableFrom(temp[i])) { throw new IllegalStateException("Specified class " + classes[i] + " is incompatible with delegate class " + temp[i] + " (index " + i + ")"); } } } } } setNamePrefix(classes[ReflectUtils.findPackageProtected(classes)].getName()); return (Mixin)super.create(KEY_FACTORY.newInstance(style, ReflectUtils.getNames( classes ), route)); } public void generateClass(ClassVisitor v) { switch (style) { case STYLE_INTERFACES: new MixinEmitter(v, getClassName(), classes, route); break; case STYLE_BEANS: new MixinBeanEmitter(v, getClassName(), classes); break; case STYLE_EVERYTHING: new MixinEverythingEmitter(v, getClassName(), classes); break; } } protected Object firstInstance(Class type) { return ((Mixin)ReflectUtils.newInstance(type)).newInstance(delegates); } protected Object nextInstance(Object instance) { return ((Mixin)instance).newInstance(delegates); } } public static Class[] getClasses(Object[] delegates) { return (Class[])route(delegates).classes.clone(); } // public static int[] getRoute(Object[] delegates) { // return (int[])route(delegates).route.clone(); // } private static Route route(Object[] delegates) { Object key = ClassesKey.create(delegates); Route route = (Route)ROUTE_CACHE.get(key); if (route == null) { ROUTE_CACHE.put(key, route = new Route(delegates)); } return route; } private static class Route { private Class[] classes; private int[] route; Route(Object[] delegates) { Map map = new HashMap(); ArrayList collect = new ArrayList(); for (int i = 0; i < delegates.length; i++) { Class delegate = delegates[i].getClass(); collect.clear(); ReflectUtils.addAllInterfaces(delegate, collect); for (Iterator it = collect.iterator(); it.hasNext();) { Class iface = (Class)it.next(); if (!map.containsKey(iface)) { map.put(iface, new Integer(i)); } } } classes = new Class[map.size()]; route = new int[map.size()]; int index = 0; for (Iterator it = map.keySet().iterator(); it.hasNext();) { Class key = (Class)it.next(); classes[index] = key; route[index] = ((Integer)map.get(key)).intValue(); index++; } } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/BridgeMethodResolver.java0000644000175000017500000001053611760000000025303 0ustar miguelmiguel/* * Copyright 2011 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.io.IOException; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; import net.sf.cglib.core.Signature; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; /** * Uses bytecode reflection to figure out the targets of all bridge methods * that use invokespecial, so that we can later rewrite them to use invokevirtual. * * @author sberlin@gmail.com (Sam Berlin) */ class BridgeMethodResolver { private final Map/* */declToBridge; public BridgeMethodResolver(Map declToBridge) { this.declToBridge = declToBridge; } /** * Finds all bridge methods that are being called with invokespecial & * returns them. */ public Map/**/resolveAll() { Map resolved = new HashMap(); for (Iterator entryIter = declToBridge.entrySet().iterator(); entryIter.hasNext(); ) { Map.Entry entry = (Map.Entry)entryIter.next(); Class owner = (Class)entry.getKey(); Set bridges = (Set)entry.getValue(); try { new ClassReader(owner.getName()) .accept(new BridgedFinder(bridges, resolved), ClassReader.SKIP_FRAMES | ClassReader.SKIP_DEBUG); } catch(IOException ignored) {} } return resolved; } private static class BridgedFinder extends ClassVisitor { private Map/**/ resolved; private Set/**/ eligableMethods; private Signature currentMethod = null; BridgedFinder(Set eligableMethods, Map resolved) { super(Opcodes.ASM4); this.resolved = resolved; this.eligableMethods = eligableMethods; } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { Signature sig = new Signature(name, desc); if (eligableMethods.remove(sig)) { currentMethod = sig; return new MethodVisitor(Opcodes.ASM4) { public void visitMethodInsn(int opcode, String owner, String name, String desc) { if (opcode == Opcodes.INVOKESPECIAL && currentMethod != null) { Signature target = new Signature(name, desc); // If the target signature is the same as the current, // we shouldn't change our bridge becaues invokespecial // is the only way to make progress (otherwise we'll // get infinite recursion). This would typically // only happen when a bridge method is created to widen // the visibility of a superclass' method. if (!target.equals(currentMethod)) { resolved.put(currentMethod, target); } currentMethod = null; } } }; } else { return null; } } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/FixedValue.java0000644000175000017500000000274310066633130023277 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * {@link Enhancer} callback that simply returns the value to return * from the proxied method. No information about what method * is being called is available to the callback, and the type of * the returned object must be compatible with the return type of * the proxied method. This makes this callback primarily useful * for forcing a particular method (through the use of a {@link CallbackFilter} * to return a fixed value with little overhead. */ public interface FixedValue extends Callback { /** * Return the object which the original method invocation should * return. This method is called for every method invocation. * @return an object matching the type of the return value for every * method this callback is mapped to */ Object loadObject() throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/LazyLoaderGenerator.java0000644000175000017500000000654610402432050025155 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Label; import org.objectweb.asm.Type; class LazyLoaderGenerator implements CallbackGenerator { public static final LazyLoaderGenerator INSTANCE = new LazyLoaderGenerator(); private static final Signature LOAD_OBJECT = TypeUtils.parseSignature("Object loadObject()"); private static final Type LAZY_LOADER = TypeUtils.parseType("net.sf.cglib.proxy.LazyLoader"); public void generate(ClassEmitter ce, Context context, List methods) { Set indexes = new HashSet(); for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); if (TypeUtils.isProtected(method.getModifiers())) { // ignore protected methods } else { int index = context.getIndex(method); indexes.add(new Integer(index)); CodeEmitter e = context.beginMethod(ce, method); e.load_this(); e.dup(); e.invoke_virtual_this(loadMethod(index)); e.checkcast(method.getClassInfo().getType()); e.load_args(); e.invoke(method); e.return_value(); e.end_method(); } } for (Iterator it = indexes.iterator(); it.hasNext();) { int index = ((Integer)it.next()).intValue(); String delegate = "CGLIB$LAZY_LOADER_" + index; ce.declare_field(Constants.ACC_PRIVATE, delegate, Constants.TYPE_OBJECT, null); CodeEmitter e = ce.begin_method(Constants.ACC_PRIVATE | Constants.ACC_SYNCHRONIZED | Constants.ACC_FINAL, loadMethod(index), null); e.load_this(); e.getfield(delegate); e.dup(); Label end = e.make_label(); e.ifnonnull(end); e.pop(); e.load_this(); context.emitCallback(e, index); e.invoke_interface(LAZY_LOADER, LOAD_OBJECT); e.dup_x1(); e.putfield(delegate); e.mark(end); e.return_value(); e.end_method(); } } private Signature loadMethod(int index) { return new Signature("CGLIB$LOAD_PRIVATE_" + index, Constants.TYPE_OBJECT, Constants.TYPES_EMPTY); } public void generateStatic(CodeEmitter e, Context context, List methods) { } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/CallbackInfo.java0000644000175000017500000000732710156243316023561 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import org.objectweb.asm.Type; class CallbackInfo { public static Type[] determineTypes(Class[] callbackTypes) { Type[] types = new Type[callbackTypes.length]; for (int i = 0; i < types.length; i++) { types[i] = determineType(callbackTypes[i]); } return types; } public static Type[] determineTypes(Callback[] callbacks) { Type[] types = new Type[callbacks.length]; for (int i = 0; i < types.length; i++) { types[i] = determineType(callbacks[i]); } return types; } public static CallbackGenerator[] getGenerators(Type[] callbackTypes) { CallbackGenerator[] generators = new CallbackGenerator[callbackTypes.length]; for (int i = 0; i < generators.length; i++) { generators[i] = getGenerator(callbackTypes[i]); } return generators; } //////////////////// PRIVATE //////////////////// private Class cls; private CallbackGenerator generator; private Type type; private static final CallbackInfo[] CALLBACKS = { new CallbackInfo(NoOp.class, NoOpGenerator.INSTANCE), new CallbackInfo(MethodInterceptor.class, MethodInterceptorGenerator.INSTANCE), new CallbackInfo(InvocationHandler.class, InvocationHandlerGenerator.INSTANCE), new CallbackInfo(LazyLoader.class, LazyLoaderGenerator.INSTANCE), new CallbackInfo(Dispatcher.class, DispatcherGenerator.INSTANCE), new CallbackInfo(FixedValue.class, FixedValueGenerator.INSTANCE), new CallbackInfo(ProxyRefDispatcher.class, DispatcherGenerator.PROXY_REF_INSTANCE), }; private CallbackInfo(Class cls, CallbackGenerator generator) { this.cls = cls; this.generator = generator; type = Type.getType(cls); } private static Type determineType(Callback callback) { if (callback == null) { throw new IllegalStateException("Callback is null"); } return determineType(callback.getClass()); } private static Type determineType(Class callbackType) { Class cur = null; for (int i = 0; i < CALLBACKS.length; i++) { CallbackInfo info = CALLBACKS[i]; if (info.cls.isAssignableFrom(callbackType)) { if (cur != null) { throw new IllegalStateException("Callback implements both " + cur + " and " + info.cls); } cur = info.cls; } } if (cur == null) { throw new IllegalStateException("Unknown callback type " + callbackType); } return Type.getType(cur); } private static CallbackGenerator getGenerator(Type callbackType) { for (int i = 0; i < CALLBACKS.length; i++) { CallbackInfo info = CALLBACKS[i]; if (info.type.equals(callbackType)) { return info.generator; } } throw new IllegalStateException("Unknown callback type " + callbackType); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/DispatcherGenerator.java0000644000175000017500000000502410162421562025174 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Type; class DispatcherGenerator implements CallbackGenerator { public static final DispatcherGenerator INSTANCE = new DispatcherGenerator(false); public static final DispatcherGenerator PROXY_REF_INSTANCE = new DispatcherGenerator(true); private static final Type DISPATCHER = TypeUtils.parseType("net.sf.cglib.proxy.Dispatcher"); private static final Type PROXY_REF_DISPATCHER = TypeUtils.parseType("net.sf.cglib.proxy.ProxyRefDispatcher"); private static final Signature LOAD_OBJECT = TypeUtils.parseSignature("Object loadObject()"); private static final Signature PROXY_REF_LOAD_OBJECT = TypeUtils.parseSignature("Object loadObject(Object)"); private boolean proxyRef; private DispatcherGenerator(boolean proxyRef) { this.proxyRef = proxyRef; } public void generate(ClassEmitter ce, Context context, List methods) { for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); if (!TypeUtils.isProtected(method.getModifiers())) { CodeEmitter e = context.beginMethod(ce, method); context.emitCallback(e, context.getIndex(method)); if (proxyRef) { e.load_this(); e.invoke_interface(PROXY_REF_DISPATCHER, PROXY_REF_LOAD_OBJECT); } else { e.invoke_interface(DISPATCHER, LOAD_OBJECT); } e.checkcast(method.getClassInfo().getType()); e.load_args(); e.invoke(method); e.return_value(); e.end_method(); } } } public void generateStatic(CodeEmitter e, Context context, List methods) { } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/NoOp.java0000644000175000017500000000175310066633130022116 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * Methods using this {@link Enhancer} callback will delegate directly to the * default (super) implementation in the base class. */ public interface NoOp extends Callback { /** * A thread-safe singleton instance of the NoOp callback. */ public static final NoOp INSTANCE = new NoOp() { }; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/UndeclaredThrowableException.java0000644000175000017500000000232610066633130027035 0ustar miguelmiguel/* * Copyright 2002,2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.core.CodeGenerationException; /** * Used by {@link Proxy} as a replacement for java.lang.reflect.UndeclaredThrowableException. * @author Juozas Baliuka */ public class UndeclaredThrowableException extends CodeGenerationException { /** * Creates a new instance of UndeclaredThrowableException without detail message. */ public UndeclaredThrowableException(Throwable t) { super(t); } public Throwable getUndeclaredThrowable() { return getCause(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/MixinEmitter.java0000644000175000017500000000634110474375326023674 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; /** * @author Chris Nokleberg * @version $Id: MixinEmitter.java,v 1.9 2006/08/27 21:04:37 herbyderby Exp $ */ class MixinEmitter extends ClassEmitter { private static final String FIELD_NAME = "CGLIB$DELEGATES"; private static final Signature CSTRUCT_OBJECT_ARRAY = TypeUtils.parseConstructor("Object[]"); private static final Type MIXIN = TypeUtils.parseType("net.sf.cglib.proxy.Mixin"); private static final Signature NEW_INSTANCE = new Signature("newInstance", MIXIN, new Type[]{ Constants.TYPE_OBJECT_ARRAY }); public MixinEmitter(ClassVisitor v, String className, Class[] classes, int[] route) { super(v); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, MIXIN, TypeUtils.getTypes(getInterfaces(classes)), Constants.SOURCE_FILE); EmitUtils.null_constructor(this); EmitUtils.factory_method(this, NEW_INSTANCE); declare_field(Constants.ACC_PRIVATE, FIELD_NAME, Constants.TYPE_OBJECT_ARRAY, null); CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT_ARRAY, null); e.load_this(); e.super_invoke_constructor(); e.load_this(); e.load_arg(0); e.putfield(FIELD_NAME); e.return_value(); e.end_method(); Set unique = new HashSet(); for (int i = 0; i < classes.length; i++) { Method[] methods = getMethods(classes[i]); for (int j = 0; j < methods.length; j++) { if (unique.add(MethodWrapper.create(methods[j]))) { MethodInfo method = ReflectUtils.getMethodInfo(methods[j]); e = EmitUtils.begin_method(this, method, Constants.ACC_PUBLIC); e.load_this(); e.getfield(FIELD_NAME); e.aaload((route != null) ? route[i] : i); e.checkcast(method.getClassInfo().getType()); e.load_args(); e.invoke(method); e.return_value(); e.end_method(); } } } end_class(); } protected Class[] getInterfaces(Class[] classes) { return classes; } protected Method[] getMethods(Class type) { return type.getMethods(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/InterfaceMaker.java0000644000175000017500000001023510402432050024106 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; /** * Generates new interfaces at runtime. * By passing a generated interface to the Enhancer's list of interfaces to * implement, you can make your enhanced classes handle an arbitrary set * of method signatures. * @author Chris Nokleberg * @version $Id: InterfaceMaker.java,v 1.4 2006/03/05 02:43:19 herbyderby Exp $ */ public class InterfaceMaker extends AbstractClassGenerator { private static final Source SOURCE = new Source(InterfaceMaker.class.getName()); private Map signatures = new HashMap(); /** * Create a new InterfaceMaker. A new InterfaceMaker * object should be used for each generated interface, and should not * be shared across threads. */ public InterfaceMaker() { super(SOURCE); } /** * Add a method signature to the interface. * @param sig the method signature to add to the interface * @param exceptions an array of exception types to declare for the method */ public void add(Signature sig, Type[] exceptions) { signatures.put(sig, exceptions); } /** * Add a method signature to the interface. The method modifiers are ignored, * since interface methods are by definition abstract and public. * @param method the method to add to the interface */ public void add(Method method) { add(ReflectUtils.getSignature(method), ReflectUtils.getExceptionTypes(method)); } /** * Add all the public methods in the specified class. * Methods from superclasses are included, except for methods declared in the base * Object class (e.g. getClass, equals, hashCode). * @param class the class containing the methods to add to the interface */ public void add(Class clazz) { Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (!m.getDeclaringClass().getName().equals("java.lang.Object")) { add(m); } } } /** * Create an interface using the current set of method signatures. */ public Class create() { setUseCache(false); return (Class)super.create(this); } protected ClassLoader getDefaultClassLoader() { return null; } protected Object firstInstance(Class type) { return type; } protected Object nextInstance(Object instance) { throw new IllegalStateException("InterfaceMaker does not cache"); } public void generateClass(ClassVisitor v) throws Exception { ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC | Constants.ACC_INTERFACE, getClassName(), null, null, Constants.SOURCE_FILE); for (Iterator it = signatures.keySet().iterator(); it.hasNext();) { Signature sig = (Signature)it.next(); Type[] exceptions = (Type[])signatures.get(sig); ce.begin_method(Constants.ACC_PUBLIC | Constants.ACC_ABSTRACT, sig, exceptions).end_method(); } ce.end_class(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/NoOpGenerator.java0000644000175000017500000000317712250627534023777 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.util.Iterator; import java.util.List; import net.sf.cglib.core.*; class NoOpGenerator implements CallbackGenerator { public static final NoOpGenerator INSTANCE = new NoOpGenerator(); public void generate(ClassEmitter ce, Context context, List methods) { for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); if (TypeUtils.isBridge(method.getModifiers()) || ( TypeUtils.isProtected(context.getOriginalModifiers(method)) && TypeUtils.isPublic(method.getModifiers()))) { CodeEmitter e = EmitUtils.begin_method(ce, method); e.load_this(); e.load_args(); context.emitInvoke(e, method); e.return_value(); e.end_method(); } } } public void generateStatic(CodeEmitter e, Context context, List methods) { } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/FixedValueGenerator.java0000644000175000017500000000324710162421562025147 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Type; class FixedValueGenerator implements CallbackGenerator { public static final FixedValueGenerator INSTANCE = new FixedValueGenerator(); private static final Type FIXED_VALUE = TypeUtils.parseType("net.sf.cglib.proxy.FixedValue"); private static final Signature LOAD_OBJECT = TypeUtils.parseSignature("Object loadObject()"); public void generate(ClassEmitter ce, Context context, List methods) { for (Iterator it = methods.iterator(); it.hasNext();) { MethodInfo method = (MethodInfo)it.next(); CodeEmitter e = context.beginMethod(ce, method); context.emitCallback(e, context.getIndex(method)); e.invoke_interface(FIXED_VALUE, LOAD_OBJECT); e.unbox_or_zero(e.getReturnType()); e.return_value(); e.end_method(); } } public void generateStatic(CodeEmitter e, Context context, List methods) { } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/CallbackFilter.java0000644000175000017500000000316110066633130024100 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import java.lang.reflect.Method; /** * Map methods of subclasses generated by {@link Enhancer} to a particular * callback. The type of the callbacks chosen for each method affects * the bytecode generated for that method in the subclass, and cannot * change for the life of the class. */ public interface CallbackFilter { /** * Map a method to a callback. * @param method the intercepted method * @return the index into the array of callbacks (as specified by {@link Enhancer#setCallbacks}) to use for the method, */ int accept(Method method); /** * The CallbackFilter in use affects which cached class * the Enhancer will use, so this is a reminder that * you should correctly implement equals and * hashCode for custom CallbackFilter * implementations in order to improve performance. */ boolean equals(Object o); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/Factory.java0000644000175000017500000000575610066633130022661 0ustar miguelmiguel/* * Copyright 2002,2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; /** * All enhanced instances returned by the {@link Enhancer} class implement this interface. * Using this interface for new instances is faster than going through the Enhancer * interface or using reflection. In addition, to intercept methods called during * object construction you must use these methods instead of reflection. * @author Juozas Baliuka baliuka@mwm.lt * @version $Id: Factory.java,v 1.13 2004/06/24 21:15:20 herbyderby Exp $ */ public interface Factory { /** * Creates new instance of the same type, using the no-arg constructor. * The class of this object must have been created using a single Callback type. * If multiple callbacks are required an exception will be thrown. * @param callback the new interceptor to use * @return new instance of the same type */ Object newInstance(Callback callback); /** * Creates new instance of the same type, using the no-arg constructor. * @param callbacks the new callbacks(s) to use * @return new instance of the same type */ Object newInstance(Callback[] callbacks); /** * Creates a new instance of the same type, using the constructor * matching the given signature. * @param types the constructor argument types * @param args the constructor arguments * @param callbacks the new interceptor(s) to use * @return new instance of the same type */ Object newInstance(Class[] types, Object[] args, Callback[] callbacks); /** * Return the Callback implementation at the specified index. * @param index the callback index * @return the callback implementation */ Callback getCallback(int index); /** * Set the callback for this object for the given type. * @param index the callback index to replace * @param callback the new callback */ void setCallback(int index, Callback callback); /** * Replace all of the callbacks for this object at once. * @param callbacks the new callbacks(s) to use */ void setCallbacks(Callback[] callbacks); /** * Get the current set of callbacks for ths object. * @return a new array instance */ Callback[] getCallbacks(); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/proxy/CallbackHelper.java0000644000175000017500000000672110066633130024077 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.proxy; import net.sf.cglib.core.ReflectUtils; import java.lang.reflect.Method; import java.util.*; /** * @version $Id: CallbackHelper.java,v 1.2 2004/06/24 21:15:20 herbyderby Exp $ */ abstract public class CallbackHelper implements CallbackFilter { private Map methodMap = new HashMap(); private List callbacks = new ArrayList(); public CallbackHelper(Class superclass, Class[] interfaces) { List methods = new ArrayList(); Enhancer.getMethods(superclass, interfaces, methods); Map indexes = new HashMap(); for (int i = 0, size = methods.size(); i < size; i++) { Method method = (Method)methods.get(i); Object callback = getCallback(method); if (callback == null) throw new IllegalStateException("getCallback cannot return null"); boolean isCallback = callback instanceof Callback; if (!(isCallback || (callback instanceof Class))) throw new IllegalStateException("getCallback must return a Callback or a Class"); if (i > 0 && ((callbacks.get(i - 1) instanceof Callback) ^ isCallback)) throw new IllegalStateException("getCallback must return a Callback or a Class consistently for every Method"); Integer index = (Integer)indexes.get(callback); if (index == null) { index = new Integer(callbacks.size()); indexes.put(callback, index); } methodMap.put(method, index); callbacks.add(callback); } } abstract protected Object getCallback(Method method); public Callback[] getCallbacks() { if (callbacks.size() == 0) return new Callback[0]; if (callbacks.get(0) instanceof Callback) { return (Callback[])callbacks.toArray(new Callback[callbacks.size()]); } else { throw new IllegalStateException("getCallback returned classes, not callbacks; call getCallbackTypes instead"); } } public Class[] getCallbackTypes() { if (callbacks.size() == 0) return new Class[0]; if (callbacks.get(0) instanceof Callback) { return ReflectUtils.getClasses(getCallbacks()); } else { return (Class[])callbacks.toArray(new Class[callbacks.size()]); } } public int accept(Method method) { return ((Integer)methodMap.get(method)).intValue(); } public int hashCode() { return methodMap.hashCode(); } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof CallbackHelper)) return false; return methodMap.equals(((CallbackHelper)o).methodMap); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/0000755000175000017500000000000012250627450020642 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/ConstructorDelegate.java0000644000175000017500000001055210402432050025453 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; /** * @author Chris Nokleberg * @version $Id: ConstructorDelegate.java,v 1.20 2006/03/05 02:43:19 herbyderby Exp $ */ abstract public class ConstructorDelegate { private static final ConstructorKey KEY_FACTORY = (ConstructorKey)KeyFactory.create(ConstructorKey.class, KeyFactory.CLASS_BY_NAME); interface ConstructorKey { public Object newInstance(String declaring, String iface); } protected ConstructorDelegate() { } public static ConstructorDelegate create(Class targetClass, Class iface) { Generator gen = new Generator(); gen.setTargetClass(targetClass); gen.setInterface(iface); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(ConstructorDelegate.class.getName()); private static final Type CONSTRUCTOR_DELEGATE = TypeUtils.parseType("net.sf.cglib.reflect.ConstructorDelegate"); private Class iface; private Class targetClass; public Generator() { super(SOURCE); } public void setInterface(Class iface) { this.iface = iface; } public void setTargetClass(Class targetClass) { this.targetClass = targetClass; } public ConstructorDelegate create() { setNamePrefix(targetClass.getName()); Object key = KEY_FACTORY.newInstance(iface.getName(), targetClass.getName()); return (ConstructorDelegate)super.create(key); } protected ClassLoader getDefaultClassLoader() { return targetClass.getClassLoader(); } public void generateClass(ClassVisitor v) { setNamePrefix(targetClass.getName()); final Method newInstance = ReflectUtils.findNewInstance(iface); if (!newInstance.getReturnType().isAssignableFrom(targetClass)) { throw new IllegalArgumentException("incompatible return type"); } final Constructor constructor; try { constructor = targetClass.getDeclaredConstructor(newInstance.getParameterTypes()); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("interface does not match any known constructor"); } ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), CONSTRUCTOR_DELEGATE, new Type[]{ Type.getType(iface) }, Constants.SOURCE_FILE); Type declaring = Type.getType(constructor.getDeclaringClass()); EmitUtils.null_constructor(ce); CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, ReflectUtils.getSignature(newInstance), ReflectUtils.getExceptionTypes(newInstance)); e.new_instance(declaring); e.dup(); e.load_args(); e.invoke_constructor(declaring, ReflectUtils.getSignature(constructor)); e.return_value(); e.end_method(); ce.end_class(); } protected Object firstInstance(Class type) { return ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/FastClassEmitter.java0000644000175000017500000002251010402432050024705 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; class FastClassEmitter extends ClassEmitter { private static final Signature CSTRUCT_CLASS = TypeUtils.parseConstructor("Class"); private static final Signature METHOD_GET_INDEX = TypeUtils.parseSignature("int getIndex(String, Class[])"); private static final Signature SIGNATURE_GET_INDEX = new Signature("getIndex", Type.INT_TYPE, new Type[]{ Constants.TYPE_SIGNATURE }); private static final Signature TO_STRING = TypeUtils.parseSignature("String toString()"); private static final Signature CONSTRUCTOR_GET_INDEX = TypeUtils.parseSignature("int getIndex(Class[])"); private static final Signature INVOKE = TypeUtils.parseSignature("Object invoke(int, Object, Object[])"); private static final Signature NEW_INSTANCE = TypeUtils.parseSignature("Object newInstance(int, Object[])"); private static final Signature GET_MAX_INDEX = TypeUtils.parseSignature("int getMaxIndex()"); private static final Signature GET_SIGNATURE_WITHOUT_RETURN_TYPE = TypeUtils.parseSignature("String getSignatureWithoutReturnType(String, Class[])"); private static final Type FAST_CLASS = TypeUtils.parseType("net.sf.cglib.reflect.FastClass"); private static final Type ILLEGAL_ARGUMENT_EXCEPTION = TypeUtils.parseType("IllegalArgumentException"); private static final Type INVOCATION_TARGET_EXCEPTION = TypeUtils.parseType("java.lang.reflect.InvocationTargetException"); private static final Type[] INVOCATION_TARGET_EXCEPTION_ARRAY = { INVOCATION_TARGET_EXCEPTION }; public FastClassEmitter(ClassVisitor v, String className, Class type) { super(v); Type base = Type.getType(type); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, FAST_CLASS, null, Constants.SOURCE_FILE); // constructor CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_CLASS, null); e.load_this(); e.load_args(); e.super_invoke_constructor(CSTRUCT_CLASS); e.return_value(); e.end_method(); VisibilityPredicate vp = new VisibilityPredicate(type, false); List methods = ReflectUtils.addAllMethods(type, new ArrayList()); CollectionUtils.filter(methods, vp); CollectionUtils.filter(methods, new DuplicatesPredicate()); List constructors = new ArrayList(Arrays.asList(type.getDeclaredConstructors())); CollectionUtils.filter(constructors, vp); // getIndex(String) emitIndexBySignature(methods); // getIndex(String, Class[]) emitIndexByClassArray(methods); // getIndex(Class[]) e = begin_method(Constants.ACC_PUBLIC, CONSTRUCTOR_GET_INDEX, null); e.load_args(); List info = CollectionUtils.transform(constructors, MethodInfoTransformer.getInstance()); EmitUtils.constructor_switch(e, info, new GetIndexCallback(e, info)); e.end_method(); // invoke(int, Object, Object[]) e = begin_method(Constants.ACC_PUBLIC, INVOKE, INVOCATION_TARGET_EXCEPTION_ARRAY); e.load_arg(1); e.checkcast(base); e.load_arg(0); invokeSwitchHelper(e, methods, 2, base); e.end_method(); // newInstance(int, Object[]) e = begin_method(Constants.ACC_PUBLIC, NEW_INSTANCE, INVOCATION_TARGET_EXCEPTION_ARRAY); e.new_instance(base); e.dup(); e.load_arg(0); invokeSwitchHelper(e, constructors, 1, base); e.end_method(); // getMaxIndex() e = begin_method(Constants.ACC_PUBLIC, GET_MAX_INDEX, null); e.push(methods.size() - 1); e.return_value(); e.end_method(); end_class(); } // TODO: support constructor indices ("") private void emitIndexBySignature(List methods) { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, SIGNATURE_GET_INDEX, null); List signatures = CollectionUtils.transform(methods, new Transformer() { public Object transform(Object obj) { return ReflectUtils.getSignature((Method)obj).toString(); } }); e.load_arg(0); e.invoke_virtual(Constants.TYPE_OBJECT, TO_STRING); signatureSwitchHelper(e, signatures); e.end_method(); } private static final int TOO_MANY_METHODS = 100; // TODO private void emitIndexByClassArray(List methods) { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, METHOD_GET_INDEX, null); if (methods.size() > TOO_MANY_METHODS) { // hack for big classes List signatures = CollectionUtils.transform(methods, new Transformer() { public Object transform(Object obj) { String s = ReflectUtils.getSignature((Method)obj).toString(); return s.substring(0, s.lastIndexOf(')') + 1); } }); e.load_args(); e.invoke_static(FAST_CLASS, GET_SIGNATURE_WITHOUT_RETURN_TYPE); signatureSwitchHelper(e, signatures); } else { e.load_args(); List info = CollectionUtils.transform(methods, MethodInfoTransformer.getInstance()); EmitUtils.method_switch(e, info, new GetIndexCallback(e, info)); } e.end_method(); } private void signatureSwitchHelper(final CodeEmitter e, final List signatures) { ObjectSwitchCallback callback = new ObjectSwitchCallback() { public void processCase(Object key, Label end) { // TODO: remove linear indexOf e.push(signatures.indexOf(key)); e.return_value(); } public void processDefault() { e.push(-1); e.return_value(); } }; EmitUtils.string_switch(e, (String[])signatures.toArray(new String[signatures.size()]), Constants.SWITCH_STYLE_HASH, callback); } private static void invokeSwitchHelper(final CodeEmitter e, List members, final int arg, final Type base) { final List info = CollectionUtils.transform(members, MethodInfoTransformer.getInstance()); final Label illegalArg = e.make_label(); Block block = e.begin_block(); e.process_switch(getIntRange(info.size()), new ProcessSwitchCallback() { public void processCase(int key, Label end) { MethodInfo method = (MethodInfo)info.get(key); Type[] types = method.getSignature().getArgumentTypes(); for (int i = 0; i < types.length; i++) { e.load_arg(arg); e.aaload(i); e.unbox(types[i]); } // TODO: change method lookup process so MethodInfo will already reference base // instead of superclass when superclass method is inaccessible e.invoke(method, base); if (!TypeUtils.isConstructor(method)) { e.box(method.getSignature().getReturnType()); } e.return_value(); } public void processDefault() { e.goTo(illegalArg); } }); block.end(); EmitUtils.wrap_throwable(block, INVOCATION_TARGET_EXCEPTION); e.mark(illegalArg); e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Cannot find matching method/constructor"); } private static class GetIndexCallback implements ObjectSwitchCallback { private CodeEmitter e; private Map indexes = new HashMap(); public GetIndexCallback(CodeEmitter e, List methods) { this.e = e; int index = 0; for (Iterator it = methods.iterator(); it.hasNext();) { indexes.put(it.next(), new Integer(index++)); } } public void processCase(Object key, Label end) { e.push(((Integer)indexes.get(key)).intValue()); e.return_value(); } public void processDefault() { e.push(-1); e.return_value(); } } private static int[] getIntRange(int length) { int[] range = new int[length]; for (int i = 0; i < length; i++) { range[i] = i; } return range; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/FastConstructor.java0000644000175000017500000000277410066633130024655 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; public class FastConstructor extends FastMember { FastConstructor(FastClass fc, Constructor constructor) { super(fc, constructor, fc.getIndex(constructor.getParameterTypes())); } public Class[] getParameterTypes() { return ((Constructor)member).getParameterTypes(); } public Class[] getExceptionTypes() { return ((Constructor)member).getExceptionTypes(); } public Object newInstance() throws InvocationTargetException { return fc.newInstance(index, null); } public Object newInstance(Object[] args) throws InvocationTargetException { return fc.newInstance(index, args); } public Constructor getJavaConstructor() { return (Constructor)member; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/FastMethod.java0000644000175000017500000000376110066633130023545 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public class FastMethod extends FastMember { FastMethod(FastClass fc, Method method) { super(fc, method, helper(fc, method)); } private static int helper(FastClass fc, Method method) { int index = fc.getIndex(method.getName(), method.getParameterTypes()); if (index < 0) { Class[] types = method.getParameterTypes(); System.err.println("hash=" + method.getName().hashCode() + " size=" + types.length); for (int i = 0; i < types.length; i++) { System.err.println(" types[" + i + "]=" + types[i].getName()); } throw new IllegalArgumentException("Cannot find method " + method); } return index; } public Class getReturnType() { return ((Method)member).getReturnType(); } public Class[] getParameterTypes() { return ((Method)member).getParameterTypes(); } public Class[] getExceptionTypes() { return ((Method)member).getExceptionTypes(); } public Object invoke(Object obj, Object[] args) throws InvocationTargetException { return fc.invoke(index, obj, args); } public Method getJavaMethod() { return (Method)member; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/FastMember.java0000644000175000017500000000330610066633130023527 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.Member; abstract public class FastMember { protected FastClass fc; protected Member member; protected int index; protected FastMember(FastClass fc, Member member, int index) { this.fc = fc; this.member = member; this.index = index; } abstract public Class[] getParameterTypes(); abstract public Class[] getExceptionTypes(); public int getIndex() { return index; } public String getName() { return member.getName(); } public Class getDeclaringClass() { return fc.getJavaClass(); } public int getModifiers() { return member.getModifiers(); } public String toString() { return member.toString(); } public int hashCode() { return member.hashCode(); } public boolean equals(Object o) { if (o == null || !(o instanceof FastMember)) { return false; } return member.equals(((FastMember)o).member); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/MulticastDelegate.java0000644000175000017500000001435610402432050025101 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Type; abstract public class MulticastDelegate implements Cloneable { protected Object[] targets = {}; protected MulticastDelegate() { } public List getTargets() { return new ArrayList(Arrays.asList(targets)); } abstract public MulticastDelegate add(Object target); protected MulticastDelegate addHelper(Object target) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length + 1]; System.arraycopy(targets, 0, copy.targets, 0, targets.length); copy.targets[targets.length] = target; return copy; } public MulticastDelegate remove(Object target) { for (int i = targets.length - 1; i >= 0; i--) { if (targets[i].equals(target)) { MulticastDelegate copy = newInstance(); copy.targets = new Object[targets.length - 1]; System.arraycopy(targets, 0, copy.targets, 0, i); System.arraycopy(targets, i + 1, copy.targets, i, targets.length - i - 1); return copy; } } return this; } abstract public MulticastDelegate newInstance(); public static MulticastDelegate create(Class iface) { Generator gen = new Generator(); gen.setInterface(iface); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(MulticastDelegate.class.getName()); private static final Type MULTICAST_DELEGATE = TypeUtils.parseType("net.sf.cglib.reflect.MulticastDelegate"); private static final Signature NEW_INSTANCE = new Signature("newInstance", MULTICAST_DELEGATE, new Type[0]); private static final Signature ADD_DELEGATE = new Signature("add", MULTICAST_DELEGATE, new Type[]{ Constants.TYPE_OBJECT }); private static final Signature ADD_HELPER = new Signature("addHelper", MULTICAST_DELEGATE, new Type[]{ Constants.TYPE_OBJECT }); private Class iface; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return iface.getClassLoader(); } public void setInterface(Class iface) { this.iface = iface; } public MulticastDelegate create() { setNamePrefix(MulticastDelegate.class.getName()); return (MulticastDelegate)super.create(iface.getName()); } public void generateClass(ClassVisitor cv) { final MethodInfo method = ReflectUtils.getMethodInfo(ReflectUtils.findInterfaceMethod(iface)); ClassEmitter ce = new ClassEmitter(cv); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), MULTICAST_DELEGATE, new Type[]{ Type.getType(iface) }, Constants.SOURCE_FILE); EmitUtils.null_constructor(ce); // generate proxied method emitProxy(ce, method); // newInstance CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, NEW_INSTANCE, null); e.new_instance_this(); e.dup(); e.invoke_constructor_this(); e.return_value(); e.end_method(); // add e = ce.begin_method(Constants.ACC_PUBLIC, ADD_DELEGATE, null); e.load_this(); e.load_arg(0); e.checkcast(Type.getType(iface)); e.invoke_virtual_this(ADD_HELPER); e.return_value(); e.end_method(); ce.end_class(); } private void emitProxy(ClassEmitter ce, final MethodInfo method) { final CodeEmitter e = EmitUtils.begin_method(ce, method, Constants.ACC_PUBLIC); Type returnType = method.getSignature().getReturnType(); final boolean returns = returnType != Type.VOID_TYPE; Local result = null; if (returns) { result = e.make_local(returnType); e.zero_or_null(returnType); e.store_local(result); } e.load_this(); e.super_getfield("targets", Constants.TYPE_OBJECT_ARRAY); final Local result2 = result; EmitUtils.process_array(e, Constants.TYPE_OBJECT_ARRAY, new ProcessArrayCallback() { public void processElement(Type type) { e.checkcast(Type.getType(iface)); e.load_args(); e.invoke(method); if (returns) { e.store_local(result2); } } }); if (returns) { e.load_local(result); } e.return_value(); e.end_method(); } protected Object firstInstance(Class type) { // make a new instance in case first object is used with a long list of targets return ((MulticastDelegate)ReflectUtils.newInstance(type)).newInstance(); } protected Object nextInstance(Object instance) { return ((MulticastDelegate)instance).newInstance(); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/FastClass.java0000644000175000017500000001533610213357354023400 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import net.sf.cglib.core.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; abstract public class FastClass { private Class type; protected FastClass() { throw new Error("Using the FastClass empty constructor--please report to the cglib-devel mailing list"); } protected FastClass(Class type) { this.type = type; } public static FastClass create(Class type) { return create(type.getClassLoader(),type); } public static FastClass create(ClassLoader loader, Class type) { Generator gen = new Generator(); gen.setType(type); gen.setClassLoader(loader); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(FastClass.class.getName()); private Class type; public Generator() { super(SOURCE); } public void setType(Class type) { this.type = type; } public FastClass create() { setNamePrefix(type.getName()); return (FastClass)super.create(type.getName()); } protected ClassLoader getDefaultClassLoader() { return type.getClassLoader(); } public void generateClass(ClassVisitor v) throws Exception { new FastClassEmitter(v, getClassName(), type); } protected Object firstInstance(Class type) { return ReflectUtils.newInstance(type, new Class[]{ Class.class }, new Object[]{ this.type }); } protected Object nextInstance(Object instance) { return instance; } } public Object invoke(String name, Class[] parameterTypes, Object obj, Object[] args) throws InvocationTargetException { return invoke(getIndex(name, parameterTypes), obj, args); } public Object newInstance() throws InvocationTargetException { return newInstance(getIndex(Constants.EMPTY_CLASS_ARRAY), null); } public Object newInstance(Class[] parameterTypes, Object[] args) throws InvocationTargetException { return newInstance(getIndex(parameterTypes), args); } public FastMethod getMethod(Method method) { return new FastMethod(this, method); } public FastConstructor getConstructor(Constructor constructor) { return new FastConstructor(this, constructor); } public FastMethod getMethod(String name, Class[] parameterTypes) { try { return getMethod(type.getMethod(name, parameterTypes)); } catch (NoSuchMethodException e) { throw new NoSuchMethodError(e.getMessage()); } } public FastConstructor getConstructor(Class[] parameterTypes) { try { return getConstructor(type.getConstructor(parameterTypes)); } catch (NoSuchMethodException e) { throw new NoSuchMethodError(e.getMessage()); } } public String getName() { return type.getName(); } public Class getJavaClass() { return type; } public String toString() { return type.toString(); } public int hashCode() { return type.hashCode(); } public boolean equals(Object o) { if (o == null || !(o instanceof FastClass)) { return false; } return type.equals(((FastClass)o).type); } /** * Return the index of the matching method. The index may be used * later to invoke the method with less overhead. If more than one * method matches (i.e. they differ by return type only), one is * chosen arbitrarily. * @see #invoke(int, Object, Object[]) * @param name the method name * @param parameterTypes the parameter array * @return the index, or -1 if none is found. */ abstract public int getIndex(String name, Class[] parameterTypes); /** * Return the index of the matching constructor. The index may be used * later to create a new instance with less overhead. * @see #newInstance(int, Object[]) * @param parameterTypes the parameter array * @return the constructor index, or -1 if none is found. */ abstract public int getIndex(Class[] parameterTypes); /** * Invoke the method with the specified index. * @see getIndex(name, Class[]) * @param index the method index * @param obj the object the underlying method is invoked from * @param args the arguments used for the method call * @throws java.lang.reflect.InvocationTargetException if the underlying method throws an exception */ abstract public Object invoke(int index, Object obj, Object[] args) throws InvocationTargetException; /** * Create a new instance using the specified constructor index and arguments. * @see getIndex(Class[]) * @param index the constructor index * @param args the arguments passed to the constructor * @throws java.lang.reflect.InvocationTargetException if the constructor throws an exception */ abstract public Object newInstance(int index, Object[] args) throws InvocationTargetException; abstract public int getIndex(Signature sig); /** * Returns the maximum method index for this class. */ abstract public int getMaxIndex(); protected static String getSignatureWithoutReturnType(String name, Class[] parameterTypes) { StringBuffer sb = new StringBuffer(); sb.append(name); sb.append('('); for (int i = 0; i < parameterTypes.length; i++) { sb.append(Type.getDescriptor(parameterTypes[i])); } sb.append(')'); return sb.toString(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/reflect/MethodDelegate.java0000644000175000017500000002342610402432050024352 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.reflect; import java.lang.reflect.*; import net.sf.cglib.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; // TODO: don't require exact match for return type /** * DOCUMENTATION FROM APACHE AVALON DELEGATE CLASS * *

* Delegates are a typesafe pointer to another method. Since Java does not * have language support for such a construct, this utility will construct * a proxy that forwards method calls to any method with the same signature. * This utility is inspired in part by the C# delegate mechanism. We * implemented it in a Java-centric manner. *

* *

Delegate

*

* Any interface with one method can become the interface for a delegate. * Consider the example below: *

* *
 *   public interface MainDelegate {
 *       int main(String[] args);
 *   }
 * 
* *

* The interface above is an example of an interface that can become a * delegate. It has only one method, and the interface is public. In * order to create a delegate for that method, all we have to do is * call MethodDelegate.create(this, "alternateMain", MainDelegate.class). * The following program will show how to use it: *

* *
 *   public class Main {
 *       public static int main( String[] args ) {
 *           Main newMain = new Main();
 *           MainDelegate start = (MainDelegate)
 *               MethodDelegate.create(newMain, "alternateMain", MainDelegate.class);
 *           return start.main( args );
 *       }
 *
 *       public int alternateMain( String[] args ) {
 *           for (int i = 0; i < args.length; i++) {
 *               System.out.println( args[i] );
 *           }
 *           return args.length;
 *       }
 *   }
 * 
* *

* By themselves, delegates don't do much. Their true power lies in the fact that * they can be treated like objects, and passed to other methods. In fact that is * one of the key building blocks of building Intelligent Agents which in tern are * the foundation of artificial intelligence. In the above program, we could have * easily created the delegate to match the static main method by * substituting the delegate creation call with this: * MethodDelegate.createStatic(getClass(), "main", MainDelegate.class). *

*

* Another key use for Delegates is to register event listeners. It is much easier * to have all the code for your events separated out into methods instead of individual * classes. One of the ways Java gets around that is to create anonymous classes. * They are particularly troublesome because many Debuggers do not know what to do * with them. Anonymous classes tend to duplicate alot of code as well. We can * use any interface with one declared method to forward events to any method that * matches the signature (although the method name can be different). *

* *

Equality

* The criteria that we use to test if two delegates are equal are: *
    *
  • * They both refer to the same instance. That is, the instance * parameter passed to the newDelegate method was the same for both. The * instances are compared with the identity equality operator, ==. *
  • *
  • They refer to the same method as resolved by Method.equals.
  • *
* * @version $Id: MethodDelegate.java,v 1.25 2006/03/05 02:43:19 herbyderby Exp $ */ abstract public class MethodDelegate { private static final MethodDelegateKey KEY_FACTORY = (MethodDelegateKey)KeyFactory.create(MethodDelegateKey.class, KeyFactory.CLASS_BY_NAME); protected Object target; protected String eqMethod; interface MethodDelegateKey { Object newInstance(Class delegateClass, String methodName, Class iface); } public static MethodDelegate createStatic(Class targetClass, String methodName, Class iface) { Generator gen = new Generator(); gen.setTargetClass(targetClass); gen.setMethodName(methodName); gen.setInterface(iface); return gen.create(); } public static MethodDelegate create(Object target, String methodName, Class iface) { Generator gen = new Generator(); gen.setTarget(target); gen.setMethodName(methodName); gen.setInterface(iface); return gen.create(); } public boolean equals(Object obj) { MethodDelegate other = (MethodDelegate)obj; return target == other.target && eqMethod.equals(other.eqMethod); } public int hashCode() { return target.hashCode() ^ eqMethod.hashCode(); } public Object getTarget() { return target; } abstract public MethodDelegate newInstance(Object target); public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(MethodDelegate.class.getName()); private static final Type METHOD_DELEGATE = TypeUtils.parseType("net.sf.cglib.reflect.MethodDelegate"); private static final Signature NEW_INSTANCE = new Signature("newInstance", METHOD_DELEGATE, new Type[]{ Constants.TYPE_OBJECT }); private Object target; private Class targetClass; private String methodName; private Class iface; public Generator() { super(SOURCE); } public void setTarget(Object target) { this.target = target; this.targetClass = target.getClass(); } public void setTargetClass(Class targetClass) { this.targetClass = targetClass; } public void setMethodName(String methodName) { this.methodName = methodName; } public void setInterface(Class iface) { this.iface = iface; } protected ClassLoader getDefaultClassLoader() { return targetClass.getClassLoader(); } public MethodDelegate create() { setNamePrefix(targetClass.getName()); Object key = KEY_FACTORY.newInstance(targetClass, methodName, iface); return (MethodDelegate)super.create(key); } protected Object firstInstance(Class type) { return ((MethodDelegate)ReflectUtils.newInstance(type)).newInstance(target); } protected Object nextInstance(Object instance) { return ((MethodDelegate)instance).newInstance(target); } public void generateClass(ClassVisitor v) throws NoSuchMethodException { Method proxy = ReflectUtils.findInterfaceMethod(iface); final Method method = targetClass.getMethod(methodName, proxy.getParameterTypes()); if (!proxy.getReturnType().isAssignableFrom(method.getReturnType())) { throw new IllegalArgumentException("incompatible return types"); } MethodInfo methodInfo = ReflectUtils.getMethodInfo(method); boolean isStatic = TypeUtils.isStatic(methodInfo.getModifiers()); if ((target == null) ^ isStatic) { throw new IllegalArgumentException("Static method " + (isStatic ? "not " : "") + "expected"); } ClassEmitter ce = new ClassEmitter(v); CodeEmitter e; ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), METHOD_DELEGATE, new Type[]{ Type.getType(iface) }, Constants.SOURCE_FILE); ce.declare_field(Constants.PRIVATE_FINAL_STATIC, "eqMethod", Constants.TYPE_STRING, null); EmitUtils.null_constructor(ce); // generate proxied method MethodInfo proxied = ReflectUtils.getMethodInfo(iface.getDeclaredMethods()[0]); e = EmitUtils.begin_method(ce, proxied, Constants.ACC_PUBLIC); e.load_this(); e.super_getfield("target", Constants.TYPE_OBJECT); e.checkcast(methodInfo.getClassInfo().getType()); e.load_args(); e.invoke(methodInfo); e.return_value(); e.end_method(); // newInstance e = ce.begin_method(Constants.ACC_PUBLIC, NEW_INSTANCE, null); e.new_instance_this(); e.dup(); e.dup2(); e.invoke_constructor_this(); e.getfield("eqMethod"); e.super_putfield("eqMethod", Constants.TYPE_STRING); e.load_arg(0); e.super_putfield("target", Constants.TYPE_OBJECT); e.return_value(); e.end_method(); // static initializer e = ce.begin_static(); e.push(methodInfo.getSignature().toString()); e.putfield("eqMethod"); e.return_value(); e.end_method(); ce.end_class(); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/0000755000175000017500000000000012250627450021231 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassFilter.java0000644000175000017500000000142610066633126024312 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; /** * * @author baliuka */ public interface ClassFilter { boolean accept(String className); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AbstractClassFilterTransformer.java0000644000175000017500000000610010402432046030203 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; abstract public class AbstractClassFilterTransformer extends AbstractClassTransformer { private ClassTransformer pass; private ClassVisitor target; public void setTarget(ClassVisitor target) { super.setTarget(target); pass.setTarget(target); } protected AbstractClassFilterTransformer(ClassTransformer pass) { this.pass = pass; } abstract protected boolean accept(int version, int access, String name, String signature, String superName, String[] interfaces); public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { target = accept(version, access, name, signature, superName, interfaces) ? pass : cv; target.visit(version, access, name, signature, superName, interfaces); } public void visitSource(String source, String debug) { target.visitSource(source, debug); } public void visitOuterClass(String owner, String name, String desc) { target.visitOuterClass(owner, name, desc); } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return target.visitAnnotation(desc, visible); } public void visitAttribute(Attribute attr) { target.visitAttribute(attr); } public void visitInnerClass(String name, String outerName, String innerName, int access) { target.visitInnerClass(name, outerName, innerName, access); } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { return target.visitField(access, name, desc, signature, value); } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return target.visitMethod(access, name, desc, signature, exceptions); } public void visitEnd() { target.visitEnd(); target = null; // just to be safe } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AbstractProcessTask.java0000644000175000017500000000424710211265442026022 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import java.io.File; import java.util.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.Task; import org.apache.tools.ant.types.FileSet; abstract public class AbstractProcessTask extends Task { private Vector filesets = new Vector(); public void addFileset(FileSet set) { filesets.addElement(set); } protected Collection getFiles() { Map fileMap = new HashMap(); Project p = getProject(); for (int i = 0; i < filesets.size(); i++) { FileSet fs = (FileSet)filesets.elementAt(i); DirectoryScanner ds = fs.getDirectoryScanner(p); String[] srcFiles = ds.getIncludedFiles(); File dir = fs.getDir(p); for (int j = 0; j < srcFiles.length; j++) { File src = new File(dir, srcFiles[j]); fileMap.put(src.getAbsolutePath(), src); } } return fileMap.values(); } public void execute() throws BuildException { beforeExecute(); for (Iterator it = getFiles().iterator(); it.hasNext();) { try { processFile((File)it.next()); } catch (Exception e) { throw new BuildException(e); } } } protected void beforeExecute() throws BuildException { } abstract protected void processFile(File file) throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassReaderGenerator.java0000644000175000017500000000257311016424462026137 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import net.sf.cglib.core.ClassGenerator; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; public class ClassReaderGenerator implements ClassGenerator { private final ClassReader r; private final Attribute[] attrs; private final int flags; public ClassReaderGenerator(ClassReader r, int flags) { this(r, null, flags); } public ClassReaderGenerator(ClassReader r, Attribute[] attrs, int flags) { this.r = r; this.attrs = (attrs != null) ? attrs : new Attribute[0]; this.flags = flags; } public void generateClass(ClassVisitor v) { r.accept(v, attrs, flags); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AnnotationVisitorTee.java0000644000175000017500000000374312250620400026217 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Opcodes; public class AnnotationVisitorTee extends AnnotationVisitor { private AnnotationVisitor av1, av2; public static AnnotationVisitor getInstance(AnnotationVisitor av1, AnnotationVisitor av2) { if (av1 == null) return av2; if (av2 == null) return av1; return new AnnotationVisitorTee(av1, av2); } public AnnotationVisitorTee(AnnotationVisitor av1, AnnotationVisitor av2) { super(Opcodes.ASM4); this.av1 = av1; this.av2 = av2; } public void visit(String name, Object value) { av2.visit(name, value); av2.visit(name, value); } public void visitEnum(String name, String desc, String value) { av1.visitEnum(name, desc, value); av2.visitEnum(name, desc, value); } public AnnotationVisitor visitAnnotation(String name, String desc) { return getInstance(av1.visitAnnotation(name, desc), av2.visitAnnotation(name, desc)); } public AnnotationVisitor visitArray(String name) { return getInstance(av1.visitArray(name), av2.visitArray(name)); } public void visitEnd() { av1.visitEnd(); av2.visitEnd(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AbstractClassTransformer.java0000644000175000017500000000173012250620400027035 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; abstract public class AbstractClassTransformer extends ClassTransformer { protected AbstractClassTransformer() { super(Opcodes.ASM4); } public void setTarget(ClassVisitor target) { cv = target; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassVisitorTee.java0000644000175000017500000000701312250620400025144 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; public class ClassVisitorTee extends ClassVisitor { private ClassVisitor cv1, cv2; public ClassVisitorTee(ClassVisitor cv1, ClassVisitor cv2) { super(Opcodes.ASM4); this.cv1 = cv1; this.cv2 = cv2; } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { cv1.visit(version, access, name, signature, superName, interfaces); cv2.visit(version, access, name, signature, superName, interfaces); } public void visitEnd() { cv1.visitEnd(); cv2.visitEnd(); cv1 = cv2 = null; } public void visitInnerClass(String name, String outerName, String innerName, int access) { cv1.visitInnerClass(name, outerName, innerName, access); cv2.visitInnerClass(name, outerName, innerName, access); } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { FieldVisitor fv1 = cv1.visitField(access, name, desc, signature, value); FieldVisitor fv2 = cv2.visitField(access, name, desc, signature, value); if (fv1 == null) return fv2; if (fv2 == null) return fv1; return new FieldVisitorTee(fv1, fv2); } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv1 = cv1.visitMethod(access, name, desc, signature, exceptions); MethodVisitor mv2 = cv2.visitMethod(access, name, desc, signature, exceptions); if (mv1 == null) return mv2; if (mv2 == null) return mv1; return new MethodVisitorTee(mv1, mv2); } public void visitSource(String source, String debug) { cv1.visitSource(source, debug); cv2.visitSource(source, debug); } public void visitOuterClass(String owner, String name, String desc) { cv1.visitOuterClass(owner, name, desc); cv2.visitOuterClass(owner, name, desc); } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return AnnotationVisitorTee.getInstance(cv1.visitAnnotation(desc, visible), cv2.visitAnnotation(desc, visible)); } public void visitAttribute(Attribute attrs) { cv1.visitAttribute(attrs); cv2.visitAttribute(attrs); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassTransformer.java0000644000175000017500000000174512250620400025357 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; public abstract class ClassTransformer extends ClassVisitor { public ClassTransformer() { super(Opcodes.ASM4); } public ClassTransformer(int opcode) { super(opcode); } public abstract void setTarget(ClassVisitor target); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/MethodFilter.java0000644000175000017500000000155310402432046024456 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.Attribute; public interface MethodFilter { // TODO: pass class name too? boolean accept(int access, String name, String desc, String signature, String[] exceptions); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassTransformerFactory.java0000644000175000017500000000135710066633126026722 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; public interface ClassTransformerFactory { ClassTransformer newInstance(); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/FieldVisitorTee.java0000644000175000017500000000301112250620400025114 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Opcodes; public class FieldVisitorTee extends FieldVisitor { private FieldVisitor fv1, fv2; public FieldVisitorTee(FieldVisitor fv1, FieldVisitor fv2) { super(Opcodes.ASM4); this.fv1 = fv1; this.fv2 = fv2; } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return AnnotationVisitorTee.getInstance(fv1.visitAnnotation(desc, visible), fv2.visitAnnotation(desc, visible)); } public void visitAttribute(Attribute attr) { fv1.visitAttribute(attr); fv2.visitAttribute(attr); } public void visitEnd() { fv1.visitEnd(); fv2.visitEnd(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassEmitterTransformer.java0000644000175000017500000000141612250620400026704 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import net.sf.cglib.core.ClassEmitter; abstract public class ClassEmitterTransformer extends ClassEmitter { } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassFilterTransformer.java0000644000175000017500000000217610402432046026530 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; public class ClassFilterTransformer extends AbstractClassFilterTransformer { private ClassFilter filter; public ClassFilterTransformer(ClassFilter filter, ClassTransformer pass) { super(pass); this.filter = filter; } protected boolean accept(int version, int access, String name, String signature, String superName, String[] interfaces) { return filter.accept(name.replace('/', '.')); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AbstractClassLoader.java0000644000175000017500000000713612250620400025747 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import net.sf.cglib.core.CodeGenerationException; import net.sf.cglib.core.ClassGenerator; import net.sf.cglib.core.DebuggingClassWriter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.util.*; import org.objectweb.asm.Attribute; import java.io.IOException; abstract public class AbstractClassLoader extends ClassLoader { private ClassFilter filter; private ClassLoader classPath; private static java.security.ProtectionDomain DOMAIN ; static{ DOMAIN = (java.security.ProtectionDomain) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { return AbstractClassLoader.class.getProtectionDomain(); } }); } protected AbstractClassLoader(ClassLoader parent, ClassLoader classPath, ClassFilter filter) { super(parent); this.filter = filter; this.classPath = classPath; } public Class loadClass(String name) throws ClassNotFoundException { Class loaded = findLoadedClass(name); if( loaded != null ){ if( loaded.getClassLoader() == this ){ return loaded; }//else reload with this class loader } if (!filter.accept(name)) { return super.loadClass(name); } ClassReader r; try { java.io.InputStream is = classPath.getResourceAsStream( name.replace('.','/') + ".class" ); if (is == null) { throw new ClassNotFoundException(name); } try { r = new ClassReader(is); } finally { is.close(); } } catch (IOException e) { throw new ClassNotFoundException(name + ":" + e.getMessage()); } try { DebuggingClassWriter w = new DebuggingClassWriter(ClassWriter.COMPUTE_MAXS); getGenerator(r).generateClass(w); byte[] b = w.toByteArray(); Class c = super.defineClass(name, b, 0, b.length, DOMAIN); postProcess(c); return c; } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } protected ClassGenerator getGenerator(ClassReader r) { return new ClassReaderGenerator(r, attributes(), getFlags()); } protected int getFlags() { return 0; } protected Attribute[] attributes() { return null; } protected void postProcess(Class c) { } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassTransformerChain.java0000644000175000017500000000361110402432046026320 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; public class ClassTransformerChain extends AbstractClassTransformer { private ClassTransformer[] chain; public ClassTransformerChain(ClassTransformer[] chain) { this.chain = (ClassTransformer[])chain.clone(); } public void setTarget(ClassVisitor v) { super.setTarget(chain[0]); ClassVisitor next = v; for (int i = chain.length - 1; i >= 0; i--) { chain[i].setTarget(next); next = chain[i]; } } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return cv.visitMethod(access, name, desc, signature, exceptions); } public String toString() { StringBuffer sb = new StringBuffer(); sb.append("ClassTransformerChain{"); for (int i = 0; i < chain.length; i++) { if (i > 0) { sb.append(", "); } sb.append(chain[i].toString()); } sb.append("}"); return sb.toString(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/TransformingClassGenerator.java0000644000175000017500000000226310066633126027405 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import net.sf.cglib.core.ClassGenerator; import net.sf.cglib.core.Transformer; import org.objectweb.asm.ClassVisitor; public class TransformingClassGenerator implements ClassGenerator { private ClassGenerator gen; private ClassTransformer t; public TransformingClassGenerator(ClassGenerator gen, ClassTransformer t) { this.gen = gen; this.t = t; } public void generateClass(ClassVisitor v) throws Exception { t.setTarget(v); gen.generateClass(t); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/MethodFilterTransformer.java0000644000175000017500000000311210402432046026672 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; public class MethodFilterTransformer extends AbstractClassTransformer { private MethodFilter filter; private ClassTransformer pass; private ClassVisitor direct; public MethodFilterTransformer(MethodFilter filter, ClassTransformer pass) { this.filter = filter; this.pass = pass; super.setTarget(pass); } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return (filter.accept(access, name, desc, signature, exceptions) ? pass : direct).visitMethod(access, name, desc, signature, exceptions); } public void setTarget(ClassVisitor target) { pass.setTarget(target); direct = target; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/ClassTransformerTee.java0000644000175000017500000000207612250620400026013 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; public class ClassTransformerTee extends ClassTransformer { private ClassVisitor branch; public ClassTransformerTee(ClassVisitor branch) { super(Opcodes.ASM4); this.branch = branch; } public void setTarget(ClassVisitor target) { cv = new ClassVisitorTee(branch, target); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/AbstractTransformTask.java0000644000175000017500000002122312250620400026342 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package net.sf.cglib.transform; import java.io.*; import java.net.MalformedURLException; import java.util.*; import java.util.zip.*; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import net.sf.cglib.core.*; import org.apache.tools.ant.*; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.ProjectComponent; import org.objectweb.asm.*; abstract public class AbstractTransformTask extends AbstractProcessTask { private static final int ZIP_MAGIC = 0x504B0304; private static final int CLASS_MAGIC = 0xCAFEBABE; private boolean verbose; public void setVerbose(boolean verbose) { this.verbose = verbose; } /** * returns transformation for source class * * @param classInfo * class information * class name := classInfo[ 0 ] * super class name := classInfo[ 1 ] * interfaces := classInfo[ >1 ] */ abstract protected ClassTransformer getClassTransformer(String[] classInfo); protected Attribute[] attributes() { return null; } protected void processFile(File file) throws Exception { if (isClassFile(file)) { processClassFile(file); } else if (isJarFile(file)) { processJarFile(file); } else { log("ignoring " + file.toURI(), Project.MSG_WARN); } } /** * @param file * @throws Exception * @throws FileNotFoundException * @throws IOException * @throws MalformedURLException */ private void processClassFile(File file) throws Exception, FileNotFoundException, IOException, MalformedURLException { ClassReader reader = getClassReader(file); String name[] = ClassNameReader.getClassInfo(reader); DebuggingClassWriter w = new DebuggingClassWriter(ClassWriter.COMPUTE_MAXS); ClassTransformer t = getClassTransformer(name); if (t != null) { if (verbose) { log("processing " + file.toURI()); } new TransformingClassGenerator(new ClassReaderGenerator( getClassReader(file), attributes(), getFlags()), t) .generateClass(w); FileOutputStream fos = new FileOutputStream(file); try { fos.write(w.toByteArray()); } finally { fos.close(); } } } protected int getFlags() { return 0; } private static ClassReader getClassReader(File file) throws Exception { InputStream in = new BufferedInputStream(new FileInputStream(file)); try { ClassReader r = new ClassReader(in); return r; } finally { in.close(); } } protected boolean isClassFile(File file) throws IOException { return checkMagic(file, CLASS_MAGIC); } protected void processJarFile(File file) throws Exception { if (verbose) { log("processing " + file.toURI()); } File tempFile = File.createTempFile(file.getName(), null, new File(file .getAbsoluteFile().getParent())); try{ ZipInputStream zip = new ZipInputStream(new FileInputStream(file)); try { FileOutputStream fout = new FileOutputStream(tempFile); try{ ZipOutputStream out = new ZipOutputStream(fout); ZipEntry entry; while ((entry = zip.getNextEntry()) != null) { byte bytes[] = getBytes(zip); if (!entry.isDirectory()) { DataInputStream din = new DataInputStream( new ByteArrayInputStream(bytes) ); if (din.readInt() == CLASS_MAGIC) { bytes = process(bytes); } else { if (verbose) { log("ignoring " + entry.toString()); } } } ZipEntry outEntry = new ZipEntry(entry.getName()); outEntry.setMethod(entry.getMethod()); outEntry.setComment(entry.getComment()); outEntry.setSize(bytes.length); if(outEntry.getMethod() == ZipEntry.STORED){ CRC32 crc = new CRC32(); crc.update(bytes); outEntry.setCrc( crc.getValue() ); outEntry.setCompressedSize(bytes.length); } out.putNextEntry(outEntry); out.write(bytes); out.closeEntry(); zip.closeEntry(); } out.close(); }finally{ fout.close(); } } finally { zip.close(); } if(file.delete()){ File newFile = new File(tempFile.getAbsolutePath()); if(!newFile.renameTo(file)){ throw new IOException("can not rename " + tempFile + " to " + file); } }else{ throw new IOException("can not delete " + file); } }finally{ tempFile.delete(); } } /** * @param bytes * @return * @throws IOException * @throws Exception */ private byte[] process(byte[] bytes) throws Exception { ClassReader reader = new ClassReader(new ByteArrayInputStream(bytes)); String name[] = ClassNameReader.getClassInfo(reader); DebuggingClassWriter w = new DebuggingClassWriter(ClassWriter.COMPUTE_MAXS); ClassTransformer t = getClassTransformer(name); if (t != null) { if (verbose) { log("processing " + name[0]); } new TransformingClassGenerator(new ClassReaderGenerator( new ClassReader(new ByteArrayInputStream(bytes)), attributes(), getFlags()), t).generateClass(w); ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(w.toByteArray()); return out.toByteArray(); } return bytes; } /** * @param zip * @return * @throws IOException */ private byte[] getBytes(ZipInputStream zip) throws IOException { ByteArrayOutputStream bout = new ByteArrayOutputStream(); InputStream in = new BufferedInputStream(zip); int b; while ((b = in.read()) != -1) { bout.write(b); } return bout.toByteArray(); } private boolean checkMagic(File file, long magic) throws IOException { DataInputStream in = new DataInputStream(new FileInputStream(file)); try { int m = in.readInt(); return magic == m; } finally { in.close(); } } protected boolean isJarFile(File file) throws IOException { return checkMagic(file, ZIP_MAGIC); } }cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/0000755000175000017500000000000012250627450022172 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AddStaticInitTransformer.java0000644000175000017500000000336210066633126027750 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import java.lang.reflect.Method; import net.sf.cglib.core.*; import net.sf.cglib.transform.*; import org.objectweb.asm.Type; /** * @author Juozas Baliuka, Chris Nokleberg */ public class AddStaticInitTransformer extends ClassEmitterTransformer { private MethodInfo info; public AddStaticInitTransformer(Method classInit) { info = ReflectUtils.getMethodInfo(classInit); if (!TypeUtils.isStatic(info.getModifiers())) { throw new IllegalArgumentException(classInit + " is not static"); } Type[] types = info.getSignature().getArgumentTypes(); if (types.length != 1 || !types[0].equals(Constants.TYPE_CLASS) || !info.getSignature().getReturnType().equals(Type.VOID_TYPE)) { throw new IllegalArgumentException(classInit + " illegal signature"); } } protected void init() { if (!TypeUtils.isInterface(getAccess())) { CodeEmitter e = getStaticHook(); EmitUtils.load_class_this(e); e.invoke(info); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/FieldProvider.java0000644000175000017500000000173110066633126025575 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; public interface FieldProvider { String[] getFieldNames(); Class[] getFieldTypes(); void setField(int index, Object value); Object getField(int index); void setField(String name, Object value); Object getField(String name); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AccessFieldTransformer.java0000644000175000017500000000444110402432046027420 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; public class AccessFieldTransformer extends ClassEmitterTransformer { private Callback callback; public AccessFieldTransformer(Callback callback) { this.callback = callback; } public interface Callback { String getPropertyName(Type owner, String fieldName); } public void declare_field(int access, final String name, Type type, Object value) { super.declare_field(access, name, type, value); String property = TypeUtils.upperFirst(callback.getPropertyName(getClassType(), name)); if (property != null) { CodeEmitter e; e = begin_method(Constants.ACC_PUBLIC, new Signature("get" + property, type, Constants.TYPES_EMPTY), null); e.load_this(); e.getfield(name); e.return_value(); e.end_method(); e = begin_method(Constants.ACC_PUBLIC, new Signature("set" + property, Type.VOID_TYPE, new Type[]{ type }), null); e.load_this(); e.load_arg(0); e.putfield(name); e.return_value(); e.end_method(); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AbstractInterceptFieldCallback.java0000644000175000017500000000501010066633126031033 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; /** * @author Chris Nokleberg */ public class AbstractInterceptFieldCallback implements InterceptFieldCallback { public int writeInt(Object obj, String name, int oldValue, int newValue) { return newValue; } public char writeChar(Object obj, String name, char oldValue, char newValue) { return newValue; } public byte writeByte(Object obj, String name, byte oldValue, byte newValue) { return newValue; } public boolean writeBoolean(Object obj, String name, boolean oldValue, boolean newValue) { return newValue; } public short writeShort(Object obj, String name, short oldValue, short newValue) { return newValue; } public float writeFloat(Object obj, String name, float oldValue, float newValue) { return newValue; } public double writeDouble(Object obj, String name, double oldValue, double newValue) { return newValue; } public long writeLong(Object obj, String name, long oldValue, long newValue) { return newValue; } public Object writeObject(Object obj, String name, Object oldValue, Object newValue) { return newValue; } public int readInt(Object obj, String name, int oldValue) { return oldValue; } public char readChar(Object obj, String name, char oldValue) { return oldValue; } public byte readByte(Object obj, String name, byte oldValue) { return oldValue; } public boolean readBoolean(Object obj, String name, boolean oldValue) { return oldValue; } public short readShort(Object obj, String name, short oldValue) { return oldValue; } public float readFloat(Object obj, String name, float oldValue) { return oldValue; } public double readDouble(Object obj, String name, double oldValue) { return oldValue; } public long readLong(Object obj, String name, long oldValue) { return oldValue; } public Object readObject(Object obj, String name, Object oldValue) { return oldValue; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AddInitTransformer.java0000644000175000017500000000425110402432046026566 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import java.lang.reflect.Method; import net.sf.cglib.core.CodeEmitter; import net.sf.cglib.core.Constants; import net.sf.cglib.core.MethodInfo; import net.sf.cglib.core.ReflectUtils; import net.sf.cglib.core.Signature; import net.sf.cglib.transform.ClassEmitterTransformer; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; /** * @author Mark Hobson */ public class AddInitTransformer extends ClassEmitterTransformer { private MethodInfo info; public AddInitTransformer(Method method) { info = ReflectUtils.getMethodInfo(method); Type[] types = info.getSignature().getArgumentTypes(); if (types.length != 1 || !types[0].equals(Constants.TYPE_OBJECT) || !info.getSignature().getReturnType().equals(Type.VOID_TYPE)) { throw new IllegalArgumentException(method + " illegal signature"); } } public CodeEmitter begin_method(int access, Signature sig, Type[] exceptions) { final CodeEmitter emitter = super.begin_method(access, sig, exceptions); if (sig.getName().equals(Constants.CONSTRUCTOR_NAME)) { return new CodeEmitter(emitter) { public void visitInsn(int opcode) { if (opcode == Constants.RETURN) { load_this(); invoke(info); } super.visitInsn(opcode); } }; } return emitter; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AddPropertyTransformer.java0000644000175000017500000000302010066633126027510 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Type; public class AddPropertyTransformer extends ClassEmitterTransformer { private final String[] names; private final Type[] types; public AddPropertyTransformer(Map props) { int size = props.size(); names = (String[])props.keySet().toArray(new String[size]); types = new Type[size]; for (int i = 0; i < size; i++) { types[i] = (Type)props.get(names[i]); } } public AddPropertyTransformer(String[] names, Type[] types) { this.names = names; this.types = types; } public void end_class() { if (!TypeUtils.isAbstract(getAccess())) { EmitUtils.add_properties(this, names, types); } super.end_class(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/InterceptFieldCallback.java0000644000175000017500000000377310066633126027365 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; /** * @author Juozas Baliuka */ public interface InterceptFieldCallback { int writeInt(Object obj, String name, int oldValue, int newValue); char writeChar(Object obj, String name, char oldValue, char newValue); byte writeByte(Object obj, String name, byte oldValue, byte newValue); boolean writeBoolean(Object obj, String name, boolean oldValue, boolean newValue); short writeShort(Object obj, String name, short oldValue, short newValue); float writeFloat(Object obj, String name, float oldValue, float newValue); double writeDouble(Object obj, String name, double oldValue, double newValue); long writeLong(Object obj, String name, long oldValue, long newValue); Object writeObject(Object obj, String name, Object oldValue, Object newValue); int readInt(Object obj, String name, int oldValue); char readChar(Object obj, String name, char oldValue); byte readByte(Object obj, String name, byte oldValue); boolean readBoolean(Object obj, String name, boolean oldValue); short readShort(Object obj, String name, short oldValue); float readFloat(Object obj, String name, float oldValue); double readDouble(Object obj, String name, double oldValue); long readLong(Object obj, String name, long oldValue); Object readObject(Object obj, String name, Object oldValue); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/InterceptFieldFilter.java0000644000175000017500000000152310066633126027105 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import org.objectweb.asm.Type; public interface InterceptFieldFilter { boolean acceptRead(Type owner, String name); boolean acceptWrite(Type owner, String name); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/InterceptFieldEnabled.java0000644000175000017500000000151410066633126027212 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; public interface InterceptFieldEnabled { void setInterceptFieldCallback(InterceptFieldCallback callback); InterceptFieldCallback getInterceptFieldCallback(); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/FieldProviderTransformer.java0000644000175000017500000002017710402432046030015 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Attribute; import org.objectweb.asm.Label; import org.objectweb.asm.Type; public class FieldProviderTransformer extends ClassEmitterTransformer { private static final String FIELD_NAMES = "CGLIB$FIELD_NAMES"; private static final String FIELD_TYPES = "CGLIB$FIELD_TYPES"; private static final Type FIELD_PROVIDER = TypeUtils.parseType("net.sf.cglib.transform.impl.FieldProvider"); private static final Type ILLEGAL_ARGUMENT_EXCEPTION = TypeUtils.parseType("IllegalArgumentException"); private static final Signature PROVIDER_GET = TypeUtils.parseSignature("Object getField(String)"); private static final Signature PROVIDER_SET = TypeUtils.parseSignature("void setField(String, Object)"); private static final Signature PROVIDER_SET_BY_INDEX = TypeUtils.parseSignature("void setField(int, Object)"); private static final Signature PROVIDER_GET_BY_INDEX = TypeUtils.parseSignature("Object getField(int)"); private static final Signature PROVIDER_GET_TYPES = TypeUtils.parseSignature("Class[] getFieldTypes()"); private static final Signature PROVIDER_GET_NAMES = TypeUtils.parseSignature("String[] getFieldNames()"); private int access; private Map fields; public void begin_class(int version, int access, String className, Type superType, Type[] interfaces, String sourceFile) { if (!TypeUtils.isAbstract(access)) { interfaces = TypeUtils.add(interfaces, FIELD_PROVIDER); } this.access = access; fields = new HashMap(); super.begin_class(version, access, className, superType, interfaces, sourceFile); } public void declare_field(int access, String name, Type type, Object value) { super.declare_field(access, name, type, value); if (!TypeUtils.isStatic(access)) { fields.put(name, type); } } public void end_class() { if (!TypeUtils.isInterface(access)) { try { generate(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } super.end_class(); } private void generate() throws Exception { final String[] names = (String[])fields.keySet().toArray(new String[fields.size()]); int indexes[] = new int[names.length]; for (int i = 0; i < indexes.length; i++) { indexes[i] = i; } super.declare_field(Constants.PRIVATE_FINAL_STATIC, FIELD_NAMES, Constants.TYPE_STRING_ARRAY, null); super.declare_field(Constants.PRIVATE_FINAL_STATIC, FIELD_TYPES, Constants.TYPE_CLASS_ARRAY, null); // use separate methods here because each process switch inner class needs a final CodeEmitter initFieldProvider(names); getNames(); getTypes(); getField(names); setField(names); setByIndex(names, indexes); getByIndex(names, indexes); } private void initFieldProvider(String[] names) { CodeEmitter e = getStaticHook(); EmitUtils.push_object(e, names); e.putstatic(getClassType(), FIELD_NAMES, Constants.TYPE_STRING_ARRAY); e.push(names.length); e.newarray(Constants.TYPE_CLASS); e.dup(); for(int i = 0; i < names.length; i++ ){ e.dup(); e.push(i); Type type = (Type)fields.get(names[i]); EmitUtils.load_class(e, type); e.aastore(); } e.putstatic(getClassType(), FIELD_TYPES, Constants.TYPE_CLASS_ARRAY); } private void getNames() { CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, PROVIDER_GET_NAMES, null); e.getstatic(getClassType(), FIELD_NAMES, Constants.TYPE_STRING_ARRAY); e.return_value(); e.end_method(); } private void getTypes() { CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, PROVIDER_GET_TYPES, null); e.getstatic(getClassType(), FIELD_TYPES, Constants.TYPE_CLASS_ARRAY); e.return_value(); e.end_method(); } private void setByIndex(final String[] names, final int[] indexes) throws Exception { final CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, PROVIDER_SET_BY_INDEX, null); e.load_this(); e.load_arg(1); e.load_arg(0); e.process_switch(indexes, new ProcessSwitchCallback() { public void processCase(int key, Label end) throws Exception { Type type = (Type)fields.get(names[key]); e.unbox(type); e.putfield(names[key]); e.return_value(); } public void processDefault() throws Exception { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field index"); } }); e.end_method(); } private void getByIndex(final String[] names, final int[] indexes) throws Exception { final CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, PROVIDER_GET_BY_INDEX, null); e.load_this(); e.load_arg(0); e.process_switch(indexes, new ProcessSwitchCallback() { public void processCase(int key, Label end) throws Exception { Type type = (Type)fields.get(names[key]); e.getfield(names[key]); e.box(type); e.return_value(); } public void processDefault() throws Exception { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field index"); } }); e.end_method(); } // TODO: if this is used to enhance class files SWITCH_STYLE_TRIE should be used // to avoid JVM hashcode implementation incompatibilities private void getField(String[] names) throws Exception { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, PROVIDER_GET, null); e.load_this(); e.load_arg(0); EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { Type type = (Type)fields.get(key); e.getfield((String)key); e.box(type); e.return_value(); } public void processDefault() { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field name"); } }); e.end_method(); } private void setField(String[] names) throws Exception { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, PROVIDER_SET, null); e.load_this(); e.load_arg(1); e.load_arg(0); EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { Type type = (Type)fields.get(key); e.unbox(type); e.putfield((String)key); e.return_value(); } public void processDefault() { e.throw_exception(ILLEGAL_ARGUMENT_EXCEPTION, "Unknown field name"); } }); e.end_method(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/AddDelegateTransformer.java0000644000175000017500000001102310402432046027370 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import java.lang.reflect.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; /** * @author Juozas Baliuka */ public class AddDelegateTransformer extends ClassEmitterTransformer { private static final String DELEGATE = "$CGLIB_DELEGATE"; private static final Signature CSTRUCT_OBJECT = TypeUtils.parseSignature("void (Object)"); private Class[] delegateIf; private Class delegateImpl; private Type delegateType; /** Creates a new instance of AddDelegateTransformer */ public AddDelegateTransformer(Class delegateIf[], Class delegateImpl) { try { delegateImpl.getConstructor(new Class[]{ Object.class }); this.delegateIf = delegateIf; this.delegateImpl = delegateImpl; delegateType = Type.getType(delegateImpl); } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } public void begin_class(int version, int access, String className, Type superType, Type[] interfaces, String sourceFile) { if(!TypeUtils.isInterface(access)){ Type[] all = TypeUtils.add(interfaces, TypeUtils.getTypes(delegateIf)); super.begin_class(version, access, className, superType, all, sourceFile); declare_field(Constants.ACC_PRIVATE | Constants.ACC_TRANSIENT, DELEGATE, delegateType, null); for (int i = 0; i < delegateIf.length; i++) { Method[] methods = delegateIf[i].getMethods(); for (int j = 0; j < methods.length; j++) { if (Modifier.isAbstract(methods[j].getModifiers())) { addDelegate(methods[j]); } } } }else{ super.begin_class(version, access, className, superType, interfaces, sourceFile); } } public CodeEmitter begin_method(int access, Signature sig, Type[] exceptions) { final CodeEmitter e = super.begin_method(access, sig, exceptions); if (sig.getName().equals(Constants.CONSTRUCTOR_NAME)) { return new CodeEmitter(e) { private boolean transformInit = true; public void visitMethodInsn(int opcode, String owner, String name, String desc) { super.visitMethodInsn(opcode, owner, name, desc); if (transformInit && opcode == Constants.INVOKESPECIAL) { load_this(); new_instance(delegateType); dup(); load_this(); invoke_constructor(delegateType, CSTRUCT_OBJECT); putfield(DELEGATE); transformInit = false; } } }; } return e; } private void addDelegate(Method m) { Method delegate; try { delegate = delegateImpl.getMethod(m.getName(), m.getParameterTypes()); if (!delegate.getReturnType().getName().equals(m.getReturnType().getName())){ throw new IllegalArgumentException("Invalid delegate signature " + delegate); } } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } final Signature sig = ReflectUtils.getSignature(m); Type[] exceptions = TypeUtils.getTypes(m.getExceptionTypes()); CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, sig, exceptions); e.load_this(); e.getfield(DELEGATE); e.load_args(); e.invoke_virtual(delegateType, sig); e.return_value(); e.end_method(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/UndeclaredThrowableStrategy.java0000644000175000017500000000463412250620400030471 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.core.ClassGenerator; import net.sf.cglib.core.DefaultGeneratorStrategy; import net.sf.cglib.core.GeneratorStrategy; import net.sf.cglib.core.TypeUtils; import net.sf.cglib.transform.ClassTransformer; import net.sf.cglib.transform.MethodFilter; import net.sf.cglib.transform.MethodFilterTransformer; import net.sf.cglib.transform.TransformingClassGenerator; /** * A {@link GeneratorStrategy} suitable for use with {@link net.sf.cglib.Enhancer} which * causes all undeclared exceptions thrown from within a proxied method to be wrapped * in an alternative exception of your choice. */ public class UndeclaredThrowableStrategy extends DefaultGeneratorStrategy { private Class wrapper; /** * Create a new instance of this strategy. * @param wrapper a class which extends either directly or * indirectly from Throwable and which has at least one * constructor that takes a single argument of type * Throwable, for example * java.lang.reflect.UndeclaredThrowableException.class */ public UndeclaredThrowableStrategy(Class wrapper) { this.wrapper = wrapper; } private static final MethodFilter TRANSFORM_FILTER = new MethodFilter() { public boolean accept(int access, String name, String desc, String signature, String[] exceptions) { return !TypeUtils.isPrivate(access) && name.indexOf('$') < 0; } }; protected ClassGenerator transform(ClassGenerator cg) throws Exception { ClassTransformer tr = new UndeclaredThrowableTransformer(wrapper); tr = new MethodFilterTransformer(TRANSFORM_FILTER, tr); return new TransformingClassGenerator(cg, tr); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/UndeclaredThrowableTransformer.java0000644000175000017500000000444010402432046031170 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import java.lang.reflect.Constructor; import net.sf.cglib.core.*; import net.sf.cglib.transform.*; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; import org.objectweb.asm.ClassVisitor; public class UndeclaredThrowableTransformer extends ClassEmitterTransformer { private Type wrapper; public UndeclaredThrowableTransformer(Class wrapper) { this.wrapper = Type.getType(wrapper); boolean found = false; Constructor[] cstructs = wrapper.getConstructors(); for (int i = 0; i < cstructs.length; i++) { Class[] types = cstructs[i].getParameterTypes(); if (types.length == 1 && types[0].equals(Throwable.class)) { found = true; break; } } if (!found) throw new IllegalArgumentException(wrapper + " does not have a single-arg constructor that takes a Throwable"); } public CodeEmitter begin_method(int access, final Signature sig, final Type[] exceptions) { CodeEmitter e = super.begin_method(access, sig, exceptions); if (TypeUtils.isAbstract(access) || sig.equals(Constants.SIG_STATIC)) { return e; } return new CodeEmitter(e) { private Block handler; /* init */ { handler = begin_block(); } public void visitMaxs(int maxStack, int maxLocals) { handler.end(); EmitUtils.wrap_undeclared_throwable(this, handler, exceptions, wrapper); super.visitMaxs(maxStack, maxLocals); } }; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/impl/InterceptFieldTransformer.java0000644000175000017500000001734712250620400030161 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform.impl; import net.sf.cglib.transform.*; import net.sf.cglib.core.*; import org.objectweb.asm.Label; import org.objectweb.asm.Type; /** * @author Juozas Baliuka, Chris Nokleberg */ public class InterceptFieldTransformer extends ClassEmitterTransformer { private static final String CALLBACK_FIELD = "$CGLIB_READ_WRITE_CALLBACK"; private static final Type CALLBACK = TypeUtils.parseType("net.sf.cglib.transform.impl.InterceptFieldCallback"); private static final Type ENABLED = TypeUtils.parseType("net.sf.cglib.transform.impl.InterceptFieldEnabled"); private static final Signature ENABLED_SET = new Signature("setInterceptFieldCallback", Type.VOID_TYPE, new Type[]{ CALLBACK }); private static final Signature ENABLED_GET = new Signature("getInterceptFieldCallback", CALLBACK, new Type[0]); private InterceptFieldFilter filter; public InterceptFieldTransformer(InterceptFieldFilter filter) { this.filter = filter; } public void begin_class(int version, int access, String className, Type superType, Type[] interfaces, String sourceFile) { if (!TypeUtils.isInterface(access)) { super.begin_class(version, access, className, superType, TypeUtils.add(interfaces, ENABLED), sourceFile); super.declare_field(Constants.ACC_PRIVATE | Constants.ACC_TRANSIENT, CALLBACK_FIELD, CALLBACK, null); CodeEmitter e; e = super.begin_method(Constants.ACC_PUBLIC, ENABLED_GET, null); e.load_this(); e.getfield(CALLBACK_FIELD); e.return_value(); e.end_method(); e = super.begin_method(Constants.ACC_PUBLIC, ENABLED_SET, null); e.load_this(); e.load_arg(0); e.putfield(CALLBACK_FIELD); e.return_value(); e.end_method(); } else { super.begin_class(version, access, className, superType, interfaces, sourceFile); } } public void declare_field(int access, String name, Type type, Object value) { super.declare_field(access, name, type, value); if (!TypeUtils.isStatic(access)) { if (filter.acceptRead(getClassType(), name)) { addReadMethod(name, type); } if (filter.acceptWrite(getClassType(), name)) { addWriteMethod(name, type); } } } private void addReadMethod(String name, Type type) { CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, readMethodSig(name, type.getDescriptor()), null); e.load_this(); e.getfield(name); e.load_this(); e.invoke_interface(ENABLED,ENABLED_GET); Label intercept = e.make_label(); e.ifnonnull(intercept); e.return_value(); e.mark(intercept); Local result = e.make_local(type); e.store_local(result); e.load_this(); e.invoke_interface(ENABLED,ENABLED_GET); e.load_this(); e.push(name); e.load_local(result); e.invoke_interface(CALLBACK, readCallbackSig(type)); if (!TypeUtils.isPrimitive(type)) { e.checkcast(type); } e.return_value(); e.end_method(); } private void addWriteMethod(String name, Type type) { CodeEmitter e = super.begin_method(Constants.ACC_PUBLIC, writeMethodSig(name, type.getDescriptor()), null); e.load_this(); e.dup(); e.invoke_interface(ENABLED,ENABLED_GET); Label skip = e.make_label(); e.ifnull(skip); e.load_this(); e.invoke_interface(ENABLED,ENABLED_GET); e.load_this(); e.push(name); e.load_this(); e.getfield(name); e.load_arg(0); e.invoke_interface(CALLBACK, writeCallbackSig(type)); if (!TypeUtils.isPrimitive(type)) { e.checkcast(type); } Label go = e.make_label(); e.goTo(go); e.mark(skip); e.load_arg(0); e.mark(go); e.putfield(name); e.return_value(); e.end_method(); } public CodeEmitter begin_method(int access, Signature sig, Type[] exceptions) { return new CodeEmitter(super.begin_method(access, sig, exceptions)) { public void visitFieldInsn(int opcode, String owner, String name, String desc) { Type towner = TypeUtils.fromInternalName(owner); switch (opcode) { case Constants.GETFIELD: if (filter.acceptRead(towner, name)) { helper(towner, readMethodSig(name, desc)); return; } break; case Constants.PUTFIELD: if (filter.acceptWrite(towner, name)) { helper(towner, writeMethodSig(name, desc)); return; } break; } super.visitFieldInsn(opcode, owner, name, desc); } private void helper(Type owner, Signature sig) { invoke_virtual(owner, sig); } }; } private static Signature readMethodSig(String name, String desc) { return new Signature("$cglib_read_" + name, "()" + desc); } private static Signature writeMethodSig(String name, String desc) { return new Signature("$cglib_write_" + name, "(" + desc + ")V"); } private static Signature readCallbackSig(Type type) { Type remap = remap(type); return new Signature("read" + callbackName(remap), remap, new Type[]{ Constants.TYPE_OBJECT, Constants.TYPE_STRING, remap }); } private static Signature writeCallbackSig(Type type) { Type remap = remap(type); return new Signature("write" + callbackName(remap), remap, new Type[]{ Constants.TYPE_OBJECT, Constants.TYPE_STRING, remap, remap }); } private static Type remap(Type type) { switch (type.getSort()) { case Type.OBJECT: case Type.ARRAY: return Constants.TYPE_OBJECT; default: return type; } } private static String callbackName(Type type) { return (type == Constants.TYPE_OBJECT) ? "Object" : TypeUtils.upperFirst(TypeUtils.getClassName(type)); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/MethodVisitorTee.java0000644000175000017500000001246712250620400025330 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import org.objectweb.asm.*; public class MethodVisitorTee extends MethodVisitor { private final MethodVisitor mv1; private final MethodVisitor mv2; public MethodVisitorTee(MethodVisitor mv1, MethodVisitor mv2) { super(Opcodes.ASM4); this.mv1 = mv1; this.mv2 = mv2; } public void visitFrame(int type, int nLocal, Object[] local, int nStack, Object[] stack) { mv1.visitFrame(type, nLocal, local, nStack, stack); mv2.visitFrame(type, nLocal, local, nStack, stack); } public AnnotationVisitor visitAnnotationDefault() { return AnnotationVisitorTee.getInstance(mv1.visitAnnotationDefault(), mv2.visitAnnotationDefault()); } public AnnotationVisitor visitAnnotation(String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitAnnotation(desc, visible), mv2.visitAnnotation(desc, visible)); } public AnnotationVisitor visitParameterAnnotation(int parameter, String desc, boolean visible) { return AnnotationVisitorTee.getInstance(mv1.visitParameterAnnotation(parameter, desc, visible), mv2.visitParameterAnnotation(parameter, desc, visible)); } public void visitAttribute(Attribute attr) { mv1.visitAttribute(attr); mv2.visitAttribute(attr); } public void visitCode() { mv1.visitCode(); mv2.visitCode(); } public void visitInsn(int opcode) { mv1.visitInsn(opcode); mv2.visitInsn(opcode); } public void visitIntInsn(int opcode, int operand) { mv1.visitIntInsn(opcode, operand); mv2.visitIntInsn(opcode, operand); } public void visitVarInsn(int opcode, int var) { mv1.visitVarInsn(opcode, var); mv2.visitVarInsn(opcode, var); } public void visitTypeInsn(int opcode, String desc) { mv1.visitTypeInsn(opcode, desc); mv2.visitTypeInsn(opcode, desc); } public void visitFieldInsn(int opcode, String owner, String name, String desc) { mv1.visitFieldInsn(opcode, owner, name, desc); mv2.visitFieldInsn(opcode, owner, name, desc); } public void visitMethodInsn(int opcode, String owner, String name, String desc) { mv1.visitMethodInsn(opcode, owner, name, desc); mv2.visitMethodInsn(opcode, owner, name, desc); } public void visitJumpInsn(int opcode, Label label) { mv1.visitJumpInsn(opcode, label); mv2.visitJumpInsn(opcode, label); } public void visitLabel(Label label) { mv1.visitLabel(label); mv2.visitLabel(label); } public void visitLdcInsn(Object cst) { mv1.visitLdcInsn(cst); mv2.visitLdcInsn(cst); } public void visitIincInsn(int var, int increment) { mv1.visitIincInsn(var, increment); mv2.visitIincInsn(var, increment); } public void visitTableSwitchInsn(int min, int max, Label dflt, Label labels[]) { mv1.visitTableSwitchInsn(min, max, dflt, labels); mv2.visitTableSwitchInsn(min, max, dflt, labels); } public void visitLookupSwitchInsn(Label dflt, int keys[], Label labels[]) { mv1.visitLookupSwitchInsn(dflt, keys, labels); mv2.visitLookupSwitchInsn(dflt, keys, labels); } public void visitMultiANewArrayInsn(String desc, int dims) { mv1.visitMultiANewArrayInsn(desc, dims); mv2.visitMultiANewArrayInsn(desc, dims); } public void visitTryCatchBlock(Label start, Label end, Label handler, String type) { mv1.visitTryCatchBlock(start, end, handler, type); mv2.visitTryCatchBlock(start, end, handler, type); } public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) { mv1.visitLocalVariable(name, desc, signature, start, end, index); mv2.visitLocalVariable(name, desc, signature, start, end, index); } public void visitLineNumber(int line, Label start) { mv1.visitLineNumber(line, start); mv2.visitLineNumber(line, start); } public void visitMaxs(int maxStack, int maxLocals) { mv1.visitMaxs(maxStack, maxLocals); mv2.visitMaxs(maxStack, maxLocals); } public void visitEnd() { mv1.visitEnd(); mv2.visitEnd(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/transform/TransformingClassLoader.java0000644000175000017500000000235510066633126026667 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.transform; import java.util.*; import net.sf.cglib.core.ClassGenerator; import org.objectweb.asm.*; public class TransformingClassLoader extends AbstractClassLoader { private ClassTransformerFactory t; public TransformingClassLoader(ClassLoader parent, ClassFilter filter, ClassTransformerFactory t) { super(parent, parent, filter); this.t = t; } protected ClassGenerator getGenerator(ClassReader r) { ClassTransformer t2 = (ClassTransformer)t.newInstance(); return new TransformingClassGenerator(super.getGenerator(r), t2); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/0000755000175000017500000000000012250627450020306 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BeanCopier.java0000644000175000017500000001504710402432050023152 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.PropertyDescriptor; import java.lang.reflect.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; import java.util.*; /** * @author Chris Nokleberg */ abstract public class BeanCopier { private static final BeanCopierKey KEY_FACTORY = (BeanCopierKey)KeyFactory.create(BeanCopierKey.class); private static final Type CONVERTER = TypeUtils.parseType("net.sf.cglib.core.Converter"); private static final Type BEAN_COPIER = TypeUtils.parseType("net.sf.cglib.beans.BeanCopier"); private static final Signature COPY = new Signature("copy", Type.VOID_TYPE, new Type[]{ Constants.TYPE_OBJECT, Constants.TYPE_OBJECT, CONVERTER }); private static final Signature CONVERT = TypeUtils.parseSignature("Object convert(Object, Class, Object)"); interface BeanCopierKey { public Object newInstance(String source, String target, boolean useConverter); } public static BeanCopier create(Class source, Class target, boolean useConverter) { Generator gen = new Generator(); gen.setSource(source); gen.setTarget(target); gen.setUseConverter(useConverter); return gen.create(); } abstract public void copy(Object from, Object to, Converter converter); public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(BeanCopier.class.getName()); private Class source; private Class target; private boolean useConverter; public Generator() { super(SOURCE); } public void setSource(Class source) { if(!Modifier.isPublic(source.getModifiers())){ setNamePrefix(source.getName()); } this.source = source; } public void setTarget(Class target) { if(!Modifier.isPublic(target.getModifiers())){ setNamePrefix(target.getName()); } this.target = target; } public void setUseConverter(boolean useConverter) { this.useConverter = useConverter; } protected ClassLoader getDefaultClassLoader() { return source.getClassLoader(); } public BeanCopier create() { Object key = KEY_FACTORY.newInstance(source.getName(), target.getName(), useConverter); return (BeanCopier)super.create(key); } public void generateClass(ClassVisitor v) { Type sourceType = Type.getType(source); Type targetType = Type.getType(target); ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), BEAN_COPIER, null, Constants.SOURCE_FILE); EmitUtils.null_constructor(ce); CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, COPY, null); PropertyDescriptor[] getters = ReflectUtils.getBeanGetters(source); PropertyDescriptor[] setters = ReflectUtils.getBeanGetters(target); Map names = new HashMap(); for (int i = 0; i < getters.length; i++) { names.put(getters[i].getName(), getters[i]); } Local targetLocal = e.make_local(); Local sourceLocal = e.make_local(); if (useConverter) { e.load_arg(1); e.checkcast(targetType); e.store_local(targetLocal); e.load_arg(0); e.checkcast(sourceType); e.store_local(sourceLocal); } else { e.load_arg(1); e.checkcast(targetType); e.load_arg(0); e.checkcast(sourceType); } for (int i = 0; i < setters.length; i++) { PropertyDescriptor setter = setters[i]; PropertyDescriptor getter = (PropertyDescriptor)names.get(setter.getName()); if (getter != null) { MethodInfo read = ReflectUtils.getMethodInfo(getter.getReadMethod()); MethodInfo write = ReflectUtils.getMethodInfo(setter.getWriteMethod()); if (useConverter) { Type setterType = write.getSignature().getArgumentTypes()[0]; e.load_local(targetLocal); e.load_arg(2); e.load_local(sourceLocal); e.invoke(read); e.box(read.getSignature().getReturnType()); EmitUtils.load_class(e, setterType); e.push(write.getSignature().getName()); e.invoke_interface(CONVERTER, CONVERT); e.unbox_or_zero(setterType); e.invoke(write); } else if (compatible(getter, setter)) { e.dup2(); e.invoke(read); e.invoke(write); } } } e.return_value(); e.end_method(); ce.end_class(); } private static boolean compatible(PropertyDescriptor getter, PropertyDescriptor setter) { // TODO: allow automatic widening conversions? return setter.getPropertyType().isAssignableFrom(getter.getPropertyType()); } protected Object firstInstance(Class type) { return ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BulkBean.java0000644000175000017500000001057710312456122022637 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; /** * @author Juozas Baliuka */ abstract public class BulkBean { private static final BulkBeanKey KEY_FACTORY = (BulkBeanKey)KeyFactory.create(BulkBeanKey.class); interface BulkBeanKey { public Object newInstance(String target, String[] getters, String[] setters, String[] types); } protected Class target; protected String[] getters, setters; protected Class[] types; protected BulkBean() { } abstract public void getPropertyValues(Object bean, Object[] values); abstract public void setPropertyValues(Object bean, Object[] values); public Object[] getPropertyValues(Object bean) { Object[] values = new Object[getters.length]; getPropertyValues(bean, values); return values; } public Class[] getPropertyTypes() { return (Class[])types.clone(); } public String[] getGetters() { return (String[])getters.clone(); } public String[] getSetters() { return (String[])setters.clone(); } public static BulkBean create(Class target, String[] getters, String[] setters, Class[] types) { Generator gen = new Generator(); gen.setTarget(target); gen.setGetters(getters); gen.setSetters(setters); gen.setTypes(types); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(BulkBean.class.getName()); private Class target; private String[] getters; private String[] setters; private Class[] types; public Generator() { super(SOURCE); } public void setTarget(Class target) { this.target = target; } public void setGetters(String[] getters) { this.getters = getters; } public void setSetters(String[] setters) { this.setters = setters; } public void setTypes(Class[] types) { this.types = types; } protected ClassLoader getDefaultClassLoader() { return target.getClassLoader(); } public BulkBean create() { setNamePrefix(target.getName()); String targetClassName = target.getName(); String[] typeClassNames = ReflectUtils.getNames(types); Object key = KEY_FACTORY.newInstance(targetClassName, getters, setters, typeClassNames); return (BulkBean)super.create(key); } public void generateClass(ClassVisitor v) throws Exception { new BulkBeanEmitter(v, getClassName(), target, getters, setters, types); } protected Object firstInstance(Class type) { BulkBean instance = (BulkBean)ReflectUtils.newInstance(type); instance.target = target; int length = getters.length; instance.getters = new String[length]; System.arraycopy(getters, 0, instance.getters, 0, length); instance.setters = new String[length]; System.arraycopy(setters, 0, instance.setters, 0, length); instance.types = new Class[types.length]; System.arraycopy(types, 0, instance.types, 0, types.length); return instance; } protected Object nextInstance(Object instance) { return instance; } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BulkBeanException.java0000644000175000017500000000234610066633132024515 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import net.sf.cglib.core.CodeGenerationException; public class BulkBeanException extends RuntimeException { private int index; private Throwable cause; public BulkBeanException(String message, int index) { super(message); this.index = index; } public BulkBeanException(Throwable cause, int index) { super(cause.getMessage()); this.index = index; this.cause = cause; } public int getIndex() { return index; } public Throwable getCause() { return cause; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/FixedKeySet.java0000644000175000017500000000211710066633132023333 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.util.*; public /* need it for class loading */ class FixedKeySet extends AbstractSet { private Set set; private int size; public FixedKeySet(String[] keys) { size = keys.length; set = Collections.unmodifiableSet(new HashSet(Arrays.asList(keys))); } public Iterator iterator() { return set.iterator(); } public int size() { return size; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BulkBeanEmitter.java0000644000175000017500000001470110402432050024154 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; class BulkBeanEmitter extends ClassEmitter { private static final Signature GET_PROPERTY_VALUES = TypeUtils.parseSignature("void getPropertyValues(Object, Object[])"); private static final Signature SET_PROPERTY_VALUES = TypeUtils.parseSignature("void setPropertyValues(Object, Object[])"); private static final Signature CSTRUCT_EXCEPTION = TypeUtils.parseConstructor("Throwable, int"); private static final Type BULK_BEAN = TypeUtils.parseType("net.sf.cglib.beans.BulkBean"); private static final Type BULK_BEAN_EXCEPTION = TypeUtils.parseType("net.sf.cglib.beans.BulkBeanException"); public BulkBeanEmitter(ClassVisitor v, String className, Class target, String[] getterNames, String[] setterNames, Class[] types) { super(v); Method[] getters = new Method[getterNames.length]; Method[] setters = new Method[setterNames.length]; validate(target, getterNames, setterNames, types, getters, setters); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, BULK_BEAN, null, Constants.SOURCE_FILE); EmitUtils.null_constructor(this); generateGet(target, getters); generateSet(target, setters); end_class(); } private void generateGet(final Class target, final Method[] getters) { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, GET_PROPERTY_VALUES, null); if (getters.length >= 0) { e.load_arg(0); e.checkcast(Type.getType(target)); Local bean = e.make_local(); e.store_local(bean); for (int i = 0; i < getters.length; i++) { if (getters[i] != null) { MethodInfo getter = ReflectUtils.getMethodInfo(getters[i]); e.load_arg(1); e.push(i); e.load_local(bean); e.invoke(getter); e.box(getter.getSignature().getReturnType()); e.aastore(); } } } e.return_value(); e.end_method(); } private void generateSet(final Class target, final Method[] setters) { // setPropertyValues CodeEmitter e = begin_method(Constants.ACC_PUBLIC, SET_PROPERTY_VALUES, null); if (setters.length > 0) { Local index = e.make_local(Type.INT_TYPE); e.push(0); e.store_local(index); e.load_arg(0); e.checkcast(Type.getType(target)); e.load_arg(1); Block handler = e.begin_block(); int lastIndex = 0; for (int i = 0; i < setters.length; i++) { if (setters[i] != null) { MethodInfo setter = ReflectUtils.getMethodInfo(setters[i]); int diff = i - lastIndex; if (diff > 0) { e.iinc(index, diff); lastIndex = i; } e.dup2(); e.aaload(i); e.unbox(setter.getSignature().getArgumentTypes()[0]); e.invoke(setter); } } handler.end(); e.return_value(); e.catch_exception(handler, Constants.TYPE_THROWABLE); e.new_instance(BULK_BEAN_EXCEPTION); e.dup_x1(); e.swap(); e.load_local(index); e.invoke_constructor(BULK_BEAN_EXCEPTION, CSTRUCT_EXCEPTION); e.athrow(); } else { e.return_value(); } e.end_method(); } private static void validate(Class target, String[] getters, String[] setters, Class[] types, Method[] getters_out, Method[] setters_out) { int i = -1; if (setters.length != types.length || getters.length != types.length) { throw new BulkBeanException("accessor array length must be equal type array length", i); } try { for (i = 0; i < types.length; i++) { if (getters[i] != null) { Method method = ReflectUtils.findDeclaredMethod(target, getters[i], null); if (method.getReturnType() != types[i]) { throw new BulkBeanException("Specified type " + types[i] + " does not match declared type " + method.getReturnType(), i); } if (Modifier.isPrivate(method.getModifiers())) { throw new BulkBeanException("Property is private", i); } getters_out[i] = method; } if (setters[i] != null) { Method method = ReflectUtils.findDeclaredMethod(target, setters[i], new Class[]{ types[i] }); if (Modifier.isPrivate(method.getModifiers()) ){ throw new BulkBeanException("Property is private", i); } setters_out[i] = method; } } } catch (NoSuchMethodException e) { throw new BulkBeanException("Cannot find specified property", i); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BeanMapEmitter.java0000644000175000017500000001720510402432050023776 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.*; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; class BeanMapEmitter extends ClassEmitter { private static final Type BEAN_MAP = TypeUtils.parseType("net.sf.cglib.beans.BeanMap"); private static final Type FIXED_KEY_SET = TypeUtils.parseType("net.sf.cglib.beans.FixedKeySet"); private static final Signature CSTRUCT_OBJECT = TypeUtils.parseConstructor("Object"); private static final Signature CSTRUCT_STRING_ARRAY = TypeUtils.parseConstructor("String[]"); private static final Signature BEAN_MAP_GET = TypeUtils.parseSignature("Object get(Object, Object)"); private static final Signature BEAN_MAP_PUT = TypeUtils.parseSignature("Object put(Object, Object, Object)"); private static final Signature KEY_SET = TypeUtils.parseSignature("java.util.Set keySet()"); private static final Signature NEW_INSTANCE = new Signature("newInstance", BEAN_MAP, new Type[]{ Constants.TYPE_OBJECT }); private static final Signature GET_PROPERTY_TYPE = TypeUtils.parseSignature("Class getPropertyType(String)"); public BeanMapEmitter(ClassVisitor v, String className, Class type, int require) { super(v); begin_class(Constants.V1_2, Constants.ACC_PUBLIC, className, BEAN_MAP, null, Constants.SOURCE_FILE); EmitUtils.null_constructor(this); EmitUtils.factory_method(this, NEW_INSTANCE); generateConstructor(); Map getters = makePropertyMap(ReflectUtils.getBeanGetters(type)); Map setters = makePropertyMap(ReflectUtils.getBeanSetters(type)); Map allProps = new HashMap(); allProps.putAll(getters); allProps.putAll(setters); if (require != 0) { for (Iterator it = allProps.keySet().iterator(); it.hasNext();) { String name = (String)it.next(); if ((((require & BeanMap.REQUIRE_GETTER) != 0) && !getters.containsKey(name)) || (((require & BeanMap.REQUIRE_SETTER) != 0) && !setters.containsKey(name))) { it.remove(); getters.remove(name); setters.remove(name); } } } generateGet(type, getters); generatePut(type, setters); String[] allNames = getNames(allProps); generateKeySet(allNames); generateGetPropertyType(allProps, allNames); end_class(); } private Map makePropertyMap(PropertyDescriptor[] props) { Map names = new HashMap(); for (int i = 0; i < props.length; i++) { names.put(((PropertyDescriptor)props[i]).getName(), props[i]); } return names; } private String[] getNames(Map propertyMap) { return (String[])propertyMap.keySet().toArray(new String[propertyMap.size()]); } private void generateConstructor() { CodeEmitter e = begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT, null); e.load_this(); e.load_arg(0); e.super_invoke_constructor(CSTRUCT_OBJECT); e.return_value(); e.end_method(); } private void generateGet(Class type, final Map getters) { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, BEAN_MAP_GET, null); e.load_arg(0); e.checkcast(Type.getType(type)); e.load_arg(1); e.checkcast(Constants.TYPE_STRING); EmitUtils.string_switch(e, getNames(getters), Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { PropertyDescriptor pd = (PropertyDescriptor)getters.get(key); MethodInfo method = ReflectUtils.getMethodInfo(pd.getReadMethod()); e.invoke(method); e.box(method.getSignature().getReturnType()); e.return_value(); } public void processDefault() { e.aconst_null(); e.return_value(); } }); e.end_method(); } private void generatePut(Class type, final Map setters) { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, BEAN_MAP_PUT, null); e.load_arg(0); e.checkcast(Type.getType(type)); e.load_arg(1); e.checkcast(Constants.TYPE_STRING); EmitUtils.string_switch(e, getNames(setters), Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { PropertyDescriptor pd = (PropertyDescriptor)setters.get(key); if (pd.getReadMethod() == null) { e.aconst_null(); } else { MethodInfo read = ReflectUtils.getMethodInfo(pd.getReadMethod()); e.dup(); e.invoke(read); e.box(read.getSignature().getReturnType()); } e.swap(); // move old value behind bean e.load_arg(2); // new value MethodInfo write = ReflectUtils.getMethodInfo(pd.getWriteMethod()); e.unbox(write.getSignature().getArgumentTypes()[0]); e.invoke(write); e.return_value(); } public void processDefault() { // fall-through } }); e.aconst_null(); e.return_value(); e.end_method(); } private void generateKeySet(String[] allNames) { // static initializer declare_field(Constants.ACC_STATIC | Constants.ACC_PRIVATE, "keys", FIXED_KEY_SET, null); CodeEmitter e = begin_static(); e.new_instance(FIXED_KEY_SET); e.dup(); EmitUtils.push_array(e, allNames); e.invoke_constructor(FIXED_KEY_SET, CSTRUCT_STRING_ARRAY); e.putfield("keys"); e.return_value(); e.end_method(); // keySet e = begin_method(Constants.ACC_PUBLIC, KEY_SET, null); e.load_this(); e.getfield("keys"); e.return_value(); e.end_method(); } private void generateGetPropertyType(final Map allProps, String[] allNames) { final CodeEmitter e = begin_method(Constants.ACC_PUBLIC, GET_PROPERTY_TYPE, null); e.load_arg(0); EmitUtils.string_switch(e, allNames, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label end) { PropertyDescriptor pd = (PropertyDescriptor)allProps.get(key); EmitUtils.load_class(e, Type.getType(pd.getPropertyType())); e.return_value(); } public void processDefault() { e.aconst_null(); e.return_value(); } }); e.end_method(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/ImmutableBean.java0000644000175000017500000001050210402432050023637 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; /** * @author Chris Nokleberg */ public class ImmutableBean { private static final Type ILLEGAL_STATE_EXCEPTION = TypeUtils.parseType("IllegalStateException"); private static final Signature CSTRUCT_OBJECT = TypeUtils.parseConstructor("Object"); private static final Class[] OBJECT_CLASSES = { Object.class }; private static final String FIELD_NAME = "CGLIB$RWBean"; private ImmutableBean() { } public static Object create(Object bean) { Generator gen = new Generator(); gen.setBean(bean); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(ImmutableBean.class.getName()); private Object bean; private Class target; public Generator() { super(SOURCE); } public void setBean(Object bean) { this.bean = bean; target = bean.getClass(); } protected ClassLoader getDefaultClassLoader() { return target.getClassLoader(); } public Object create() { String name = target.getName(); setNamePrefix(name); return super.create(name); } public void generateClass(ClassVisitor v) { Type targetType = Type.getType(target); ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), targetType, null, Constants.SOURCE_FILE); ce.declare_field(Constants.ACC_FINAL | Constants.ACC_PRIVATE, FIELD_NAME, targetType, null); CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, CSTRUCT_OBJECT, null); e.load_this(); e.super_invoke_constructor(); e.load_this(); e.load_arg(0); e.checkcast(targetType); e.putfield(FIELD_NAME); e.return_value(); e.end_method(); PropertyDescriptor[] descriptors = ReflectUtils.getBeanProperties(target); Method[] getters = ReflectUtils.getPropertyMethods(descriptors, true, false); Method[] setters = ReflectUtils.getPropertyMethods(descriptors, false, true); for (int i = 0; i < getters.length; i++) { MethodInfo getter = ReflectUtils.getMethodInfo(getters[i]); e = EmitUtils.begin_method(ce, getter, Constants.ACC_PUBLIC); e.load_this(); e.getfield(FIELD_NAME); e.invoke(getter); e.return_value(); e.end_method(); } for (int i = 0; i < setters.length; i++) { MethodInfo setter = ReflectUtils.getMethodInfo(setters[i]); e = EmitUtils.begin_method(ce, setter, Constants.ACC_PUBLIC); e.throw_exception(ILLEGAL_STATE_EXCEPTION, "Bean is immutable"); e.end_method(); } ce.end_class(); } protected Object firstInstance(Class type) { return ReflectUtils.newInstance(type, OBJECT_CLASSES, new Object[]{ bean }); } // TODO: optimize protected Object nextInstance(Object instance) { return firstInstance(instance.getClass()); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BeanMap.java0000644000175000017500000002414510066633132022457 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.*; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; /** * A Map-based view of a JavaBean. The default set of keys is the * union of all property names (getters or setters). An attempt to set * a read-only property will be ignored, and write-only properties will * be returned as null. Removal of objects is not a * supported (the key set is fixed). * @author Chris Nokleberg */ abstract public class BeanMap implements Map { /** * Limit the properties reflected in the key set of the map * to readable properties. * @see BeanMap.Generator#setRequire */ public static final int REQUIRE_GETTER = 1; /** * Limit the properties reflected in the key set of the map * to writable properties. * @see BeanMap.Generator#setRequire */ public static final int REQUIRE_SETTER = 2; /** * Helper method to create a new BeanMap. For finer * control over the generated instance, use a new instance of * BeanMap.Generator instead of this static method. * @param bean the JavaBean underlying the map * @return a new BeanMap instance */ public static BeanMap create(Object bean) { Generator gen = new Generator(); gen.setBean(bean); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(BeanMap.class.getName()); private static final BeanMapKey KEY_FACTORY = (BeanMapKey)KeyFactory.create(BeanMapKey.class, KeyFactory.CLASS_BY_NAME); interface BeanMapKey { public Object newInstance(Class type, int require); } private Object bean; private Class beanClass; private int require; public Generator() { super(SOURCE); } /** * Set the bean that the generated map should reflect. The bean may be swapped * out for another bean of the same type using {@link #setBean}. * Calling this method overrides any value previously set using {@link #setBeanClass}. * You must call either this method or {@link #setBeanClass} before {@link #create}. * @param bean the initial bean */ public void setBean(Object bean) { this.bean = bean; if (bean != null) beanClass = bean.getClass(); } /** * Set the class of the bean that the generated map should support. * You must call either this method or {@link #setBeanClass} before {@link #create}. * @param beanClass the class of the bean */ public void setBeanClass(Class beanClass) { this.beanClass = beanClass; } /** * Limit the properties reflected by the generated map. * @param require any combination of {@link #REQUIRE_GETTER} and * {@link #REQUIRE_SETTER}; default is zero (any property allowed) */ public void setRequire(int require) { this.require = require; } protected ClassLoader getDefaultClassLoader() { return beanClass.getClassLoader(); } /** * Create a new instance of the BeanMap. An existing * generated class will be reused if possible. */ public BeanMap create() { if (beanClass == null) throw new IllegalArgumentException("Class of bean unknown"); setNamePrefix(beanClass.getName()); return (BeanMap)super.create(KEY_FACTORY.newInstance(beanClass, require)); } public void generateClass(ClassVisitor v) throws Exception { new BeanMapEmitter(v, getClassName(), beanClass, require); } protected Object firstInstance(Class type) { return ((BeanMap)ReflectUtils.newInstance(type)).newInstance(bean); } protected Object nextInstance(Object instance) { return ((BeanMap)instance).newInstance(bean); } } /** * Create a new BeanMap instance using the specified bean. * This is faster than using the {@link #create} static method. * @param bean the JavaBean underlying the map * @return a new BeanMap instance */ abstract public BeanMap newInstance(Object bean); /** * Get the type of a property. * @param name the name of the JavaBean property * @return the type of the property, or null if the property does not exist */ abstract public Class getPropertyType(String name); protected Object bean; protected BeanMap() { } protected BeanMap(Object bean) { setBean(bean); } public Object get(Object key) { return get(bean, key); } public Object put(Object key, Object value) { return put(bean, key, value); } /** * Get the property of a bean. This allows a BeanMap * to be used statically for multiple beans--the bean instance tied to the * map is ignored and the bean passed to this method is used instead. * @param bean the bean to query; must be compatible with the type of * this BeanMap * @param key must be a String * @return the current value, or null if there is no matching property */ abstract public Object get(Object bean, Object key); /** * Set the property of a bean. This allows a BeanMap * to be used statically for multiple beans--the bean instance tied to the * map is ignored and the bean passed to this method is used instead. * @param key must be a String * @return the old value, if there was one, or null */ abstract public Object put(Object bean, Object key, Object value); /** * Change the underlying bean this map should use. * @param bean the new JavaBean * @see #getBean */ public void setBean(Object bean) { this.bean = bean; } /** * Return the bean currently in use by this map. * @return the current JavaBean * @see #setBean */ public Object getBean() { return bean; } public void clear() { throw new UnsupportedOperationException(); } public boolean containsKey(Object key) { return keySet().contains(key); } public boolean containsValue(Object value) { for (Iterator it = keySet().iterator(); it.hasNext();) { Object v = get(it.next()); if (((value == null) && (v == null)) || value.equals(v)) return true; } return false; } public int size() { return keySet().size(); } public boolean isEmpty() { return size() == 0; } public Object remove(Object key) { throw new UnsupportedOperationException(); } public void putAll(Map t) { for (Iterator it = t.keySet().iterator(); it.hasNext();) { Object key = it.next(); put(key, t.get(key)); } } public boolean equals(Object o) { if (o == null || !(o instanceof Map)) { return false; } Map other = (Map)o; if (size() != other.size()) { return false; } for (Iterator it = keySet().iterator(); it.hasNext();) { Object key = it.next(); if (!other.containsKey(key)) { return false; } Object v1 = get(key); Object v2 = other.get(key); if (!((v1 == null) ? v2 == null : v1.equals(v2))) { return false; } } return true; } public int hashCode() { int code = 0; for (Iterator it = keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = get(key); code += ((key == null) ? 0 : key.hashCode()) ^ ((value == null) ? 0 : value.hashCode()); } return code; } // TODO: optimize public Set entrySet() { HashMap copy = new HashMap(); for (Iterator it = keySet().iterator(); it.hasNext();) { Object key = it.next(); copy.put(key, get(key)); } return Collections.unmodifiableMap(copy).entrySet(); } public Collection values() { Set keys = keySet(); List values = new ArrayList(keys.size()); for (Iterator it = keys.iterator(); it.hasNext();) { values.add(get(it.next())); } return Collections.unmodifiableCollection(values); } /* * @see java.util.AbstractMap#toString */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append('{'); for (Iterator it = keySet().iterator(); it.hasNext();) { Object key = it.next(); sb.append(key); sb.append('='); sb.append(get(key)); if (it.hasNext()) { sb.append(", "); } } sb.append('}'); return sb.toString(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/beans/BeanGenerator.java0000644000175000017500000001136210305457236023672 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.beans; import java.beans.PropertyDescriptor; import java.util.*; import net.sf.cglib.core.*; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Type; /** * @author Juozas Baliuka, Chris Nokleberg */ public class BeanGenerator extends AbstractClassGenerator { private static final Source SOURCE = new Source(BeanGenerator.class.getName()); private static final BeanGeneratorKey KEY_FACTORY = (BeanGeneratorKey)KeyFactory.create(BeanGeneratorKey.class); interface BeanGeneratorKey { public Object newInstance(String superclass, Map props); } private Class superclass; private Map props = new HashMap(); private boolean classOnly; public BeanGenerator() { super(SOURCE); } /** * Set the class which the generated class will extend. The class * must not be declared as final, and must have a non-private * no-argument constructor. * @param superclass class to extend, or null to extend Object */ public void setSuperclass(Class superclass) { if (superclass != null && superclass.equals(Object.class)) { superclass = null; } this.superclass = superclass; } public void addProperty(String name, Class type) { if (props.containsKey(name)) { throw new IllegalArgumentException("Duplicate property name \"" + name + "\""); } props.put(name, Type.getType(type)); } protected ClassLoader getDefaultClassLoader() { if (superclass != null) { return superclass.getClassLoader(); } else { return null; } } public Object create() { classOnly = false; return createHelper(); } public Object createClass() { classOnly = true; return createHelper(); } private Object createHelper() { if (superclass != null) { setNamePrefix(superclass.getName()); } String superName = (superclass != null) ? superclass.getName() : "java.lang.Object"; Object key = KEY_FACTORY.newInstance(superName, props); return super.create(key); } public void generateClass(ClassVisitor v) throws Exception { int size = props.size(); String[] names = (String[])props.keySet().toArray(new String[size]); Type[] types = new Type[size]; for (int i = 0; i < size; i++) { types[i] = (Type)props.get(names[i]); } ClassEmitter ce = new ClassEmitter(v); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), superclass != null ? Type.getType(superclass) : Constants.TYPE_OBJECT, null, null); EmitUtils.null_constructor(ce); EmitUtils.add_properties(ce, names, types); ce.end_class(); } protected Object firstInstance(Class type) { if (classOnly) { return type; } else { return ReflectUtils.newInstance(type); } } protected Object nextInstance(Object instance) { Class protoclass = (instance instanceof Class) ? (Class)instance : instance.getClass(); if (classOnly) { return protoclass; } else { return ReflectUtils.newInstance(protoclass); } } public static void addProperties(BeanGenerator gen, Map props) { for (Iterator it = props.keySet().iterator(); it.hasNext();) { String name = (String)it.next(); gen.addProperty(name, (Class)props.get(name)); } } public static void addProperties(BeanGenerator gen, Class type) { addProperties(gen, ReflectUtils.getBeanProperties(type)); } public static void addProperties(BeanGenerator gen, PropertyDescriptor[] descriptors) { for (int i = 0; i < descriptors.length; i++) { gen.addProperty(descriptors[i].getName(), descriptors[i].getPropertyType()); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/0000755000175000017500000000000012250627450020146 5ustar miguelmiguelcglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Transformer.java0000644000175000017500000000133610066633130023311 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; public interface Transformer { Object transform(Object value); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/AbstractClassGenerator.java0000644000175000017500000002042210315775700025413 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.io.*; import java.util.*; import java.lang.ref.*; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.Type; /** * Abstract class for all code-generating CGLIB utilities. * In addition to caching generated classes for performance, it provides hooks for * customizing the ClassLoader, name of the generated class, and transformations * applied before generation. */ abstract public class AbstractClassGenerator implements ClassGenerator { private static final Object NAME_KEY = new Object(); private static final ThreadLocal CURRENT = new ThreadLocal(); private GeneratorStrategy strategy = DefaultGeneratorStrategy.INSTANCE; private NamingPolicy namingPolicy = DefaultNamingPolicy.INSTANCE; private Source source; private ClassLoader classLoader; private String namePrefix; private Object key; private boolean useCache = true; private String className; private boolean attemptLoad; protected static class Source { String name; Map cache = new WeakHashMap(); public Source(String name) { this.name = name; } } protected AbstractClassGenerator(Source source) { this.source = source; } protected void setNamePrefix(String namePrefix) { this.namePrefix = namePrefix; } final protected String getClassName() { if (className == null) className = getClassName(getClassLoader()); return className; } private String getClassName(final ClassLoader loader) { final Set nameCache = getClassNameCache(loader); return namingPolicy.getClassName(namePrefix, source.name, key, new Predicate() { public boolean evaluate(Object arg) { return nameCache.contains(arg); } }); } private Set getClassNameCache(ClassLoader loader) { return (Set)((Map)source.cache.get(loader)).get(NAME_KEY); } /** * Set the ClassLoader in which the class will be generated. * Concrete subclasses of AbstractClassGenerator (such as Enhancer) * will try to choose an appropriate default if this is unset. *

* Classes are cached per-ClassLoader using a WeakHashMap, to allow * the generated classes to be removed when the associated loader is garbage collected. * @param classLoader the loader to generate the new class with, or null to use the default */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Override the default naming policy. * @see DefaultNamingPolicy * @param namingPolicy the custom policy, or null to use the default */ public void setNamingPolicy(NamingPolicy namingPolicy) { if (namingPolicy == null) namingPolicy = DefaultNamingPolicy.INSTANCE; this.namingPolicy = namingPolicy; } /** * @see #setNamingPolicy */ public NamingPolicy getNamingPolicy() { return namingPolicy; } /** * Whether use and update the static cache of generated classes * for a class with the same properties. Default is true. */ public void setUseCache(boolean useCache) { this.useCache = useCache; } /** * @see #setUseCache */ public boolean getUseCache() { return useCache; } /** * If set, CGLIB will attempt to load classes from the specified * ClassLoader before generating them. Because generated * class names are not guaranteed to be unique, the default is false. */ public void setAttemptLoad(boolean attemptLoad) { this.attemptLoad = attemptLoad; } public boolean getAttemptLoad() { return attemptLoad; } /** * Set the strategy to use to create the bytecode from this generator. * By default an instance of {@see DefaultGeneratorStrategy} is used. */ public void setStrategy(GeneratorStrategy strategy) { if (strategy == null) strategy = DefaultGeneratorStrategy.INSTANCE; this.strategy = strategy; } /** * @see #setStrategy */ public GeneratorStrategy getStrategy() { return strategy; } /** * Used internally by CGLIB. Returns the AbstractClassGenerator * that is being used to generate a class in the current thread. */ public static AbstractClassGenerator getCurrent() { return (AbstractClassGenerator)CURRENT.get(); } public ClassLoader getClassLoader() { ClassLoader t = classLoader; if (t == null) { t = getDefaultClassLoader(); } if (t == null) { t = getClass().getClassLoader(); } if (t == null) { t = Thread.currentThread().getContextClassLoader(); } if (t == null) { throw new IllegalStateException("Cannot determine classloader"); } return t; } abstract protected ClassLoader getDefaultClassLoader(); protected Object create(Object key) { try { Class gen = null; synchronized (source) { ClassLoader loader = getClassLoader(); Map cache2 = null; cache2 = (Map)source.cache.get(loader); if (cache2 == null) { cache2 = new HashMap(); cache2.put(NAME_KEY, new HashSet()); source.cache.put(loader, cache2); } else if (useCache) { Reference ref = (Reference)cache2.get(key); gen = (Class) (( ref == null ) ? null : ref.get()); } if (gen == null) { Object save = CURRENT.get(); CURRENT.set(this); try { this.key = key; if (attemptLoad) { try { gen = loader.loadClass(getClassName()); } catch (ClassNotFoundException e) { // ignore } } if (gen == null) { byte[] b = strategy.generate(this); String className = ClassNameReader.getClassName(new ClassReader(b)); getClassNameCache(loader).add(className); gen = ReflectUtils.defineClass(className, b, loader); } if (useCache) { cache2.put(key, new WeakReference(gen)); } return firstInstance(gen); } finally { CURRENT.set(save); } } } return firstInstance(gen); } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } abstract protected Object firstInstance(Class type) throws Exception; abstract protected Object nextInstance(Object instance) throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/VisibilityPredicate.java0000644000175000017500000000301110066633130024747 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.*; import org.objectweb.asm.Type; public class VisibilityPredicate implements Predicate { private boolean protectedOk; private String pkg; public VisibilityPredicate(Class source, boolean protectedOk) { this.protectedOk = protectedOk; pkg = TypeUtils.getPackageName(Type.getType(source)); } public boolean evaluate(Object arg) { int mod = (arg instanceof Member) ? ((Member)arg).getModifiers() : ((Integer)arg).intValue(); if (Modifier.isPrivate(mod)) { return false; } else if (Modifier.isPublic(mod)) { return true; } else if (Modifier.isProtected(mod)) { return protectedOk; } else { return pkg.equals(TypeUtils.getPackageName(Type.getType(((Member)arg).getDeclaringClass()))); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ClassGenerator.java0000644000175000017500000000144010066633132023721 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.ClassVisitor; public interface ClassGenerator { void generateClass(ClassVisitor v) throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/LocalVariablesSorter.java0000644000175000017500000001264512250620376025103 0ustar miguelmiguel/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2005 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package net.sf.cglib.core; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; /** * A {@link MethodVisitor} that renumbers local variables in their order of * appearance. This adapter allows one to easily add new local variables to a * method. * * @author Chris Nokleberg * @author Eric Bruneton */ public class LocalVariablesSorter extends MethodVisitor { /** * Mapping from old to new local variable indexes. A local variable at index * i of size 1 is remapped to 'mapping[2*i]', while a local variable at * index i of size 2 is remapped to 'mapping[2*i+1]'. */ private static class State { int[] mapping = new int[40]; int nextLocal; } protected final int firstLocal; private final State state; public LocalVariablesSorter( final int access, final String desc, final MethodVisitor mv) { super(Opcodes.ASM4, mv); state = new State(); Type[] args = Type.getArgumentTypes(desc); state.nextLocal = ((Opcodes.ACC_STATIC & access) != 0) ? 0 : 1; for (int i = 0; i < args.length; i++) { state.nextLocal += args[i].getSize(); } firstLocal = state.nextLocal; } public LocalVariablesSorter(LocalVariablesSorter lvs) { super(Opcodes.ASM4, lvs.mv); state = lvs.state; firstLocal = lvs.firstLocal; } public void visitVarInsn(final int opcode, final int var) { int size; switch (opcode) { case Opcodes.LLOAD: case Opcodes.LSTORE: case Opcodes.DLOAD: case Opcodes.DSTORE: size = 2; break; default: size = 1; } mv.visitVarInsn(opcode, remap(var, size)); } public void visitIincInsn(final int var, final int increment) { mv.visitIincInsn(remap(var, 1), increment); } public void visitMaxs(final int maxStack, final int maxLocals) { mv.visitMaxs(maxStack, state.nextLocal); } public void visitLocalVariable( final String name, final String desc, final String signature, final Label start, final Label end, final int index) { mv.visitLocalVariable(name, desc, signature, start, end, remap(index)); } // ------------- protected int newLocal(final int size) { int var = state.nextLocal; state.nextLocal += size; return var; } private int remap(final int var, final int size) { if (var < firstLocal) { return var; } int key = 2 * var + size - 1; int length = state.mapping.length; if (key >= length) { int[] newMapping = new int[Math.max(2 * length, key + 1)]; System.arraycopy(state.mapping, 0, newMapping, 0, length); state.mapping = newMapping; } int value = state.mapping[key]; if (value == 0) { value = state.nextLocal + 1; state.mapping[key] = value; state.nextLocal += size; } return value - 1; } private int remap(final int var) { if (var < firstLocal) { return var; } int key = 2 * var; int value = key < state.mapping.length ? state.mapping[key] : 0; if (value == 0) { value = key + 1 < state.mapping.length ? state.mapping[key + 1] : 0; } if (value == 0) { throw new IllegalStateException("Unknown local variable " + var); } return value - 1; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/GeneratorStrategy.java0000644000175000017500000000346610066633132024470 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; /** * The GeneratorStrategyClass. By providing your * own strategy you may examine or modify the generated class before * it is loaded. Typically this will be accomplished by subclassing * {@link DefaultGeneratorStrategy} and overriding the appropriate * protected method. * @see AbstractClassGenerator#setStrategy */ public interface GeneratorStrategy { /** * Generate the class. * @param cg a class generator on which you can call {@link ClassGenerator#generateClass} * @return a byte array containing the bits of a valid Class */ byte[] generate(ClassGenerator cg) throws Exception; /** * The GeneratorStrategy in use does not currently, but may * in the future, affect the caching of classes generated by {@link * AbstractClassGenerator}, so this is a reminder that you should * correctly implement equals and hashCode * to avoid generating too many classes. */ boolean equals(Object o); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ProcessArrayCallback.java0000644000175000017500000000141110066633132025035 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Type; public interface ProcessArrayCallback { void processElement(Type type); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Signature.java0000644000175000017500000000404610066633130022751 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Type; /** * A representation of a method signature, containing the method name, * return type, and parameter types. */ public class Signature { private String name; private String desc; public Signature(String name, String desc) { // TODO: better error checking if (name.indexOf('(') >= 0) { throw new IllegalArgumentException("Name '" + name + "' is invalid"); } this.name = name; this.desc = desc; } public Signature(String name, Type returnType, Type[] argumentTypes) { this(name, Type.getMethodDescriptor(returnType, argumentTypes)); } public String getName() { return name; } public String getDescriptor() { return desc; } public Type getReturnType() { return Type.getReturnType(desc); } public Type[] getArgumentTypes() { return Type.getArgumentTypes(desc); } public String toString() { return name + desc; } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof Signature)) return false; Signature other = (Signature)o; return name.equals(other.name) && desc.equals(other.desc); } public int hashCode() { return name.hashCode() ^ desc.hashCode(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/DuplicatesPredicate.java0000644000175000017500000000164710066633132024734 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.Method; import java.util.*; public class DuplicatesPredicate implements Predicate { private Set unique = new HashSet(); public boolean evaluate(Object arg) { return unique.add(MethodWrapper.create((Method)arg)); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/NamingPolicy.java0000644000175000017500000000375010066633132023404 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.util.Set; /** * Customize the generated class name for {@link AbstractClassGenerator}-based utilities. */ public interface NamingPolicy { /** * Choose a name for a generated class. * @param prefix a dotted-name chosen by the generating class (possibly to put the generated class in a particular package) * @param source the fully-qualified class name of the generating class (for example "net.sf.cglib.Enhancer") * @param key A key object representing the state of the parameters; for caching to work properly, equal keys should result * in the same generated class name. The default policy incorporates key.hashCode() into the class name. * @param names a predicate that returns true if the given classname has already been used in the same ClassLoader. * @return the fully-qualified class name */ String getClassName(String prefix, String source, Object key, Predicate names); /** * The NamingPolicy in use does not currently, but may * in the future, affect the caching of classes generated by {@link * AbstractClassGenerator}, so this is a reminder that you should * correctly implement equals and hashCode * to avoid generating too many classes. */ boolean equals(Object o); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/TinyBitSet.java0000644000175000017500000000351310066633130023044 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; public class TinyBitSet { private static int[] T = new int[256]; private int value = 0; private static int gcount(int x) { int c = 0; while (x != 0) { c++; x &= (x - 1); } return c; } static { for(int j = 0; j < 256; j++) { T[j] = gcount(j); } } private static int topbit(int i) { int j; for (j = 0; i != 0; i ^= j) { j = i & -i; } return j; } private static int log2(int i) { int j = 0; for (j = 0; i != 0; i >>= 1) { j++; } return j; } public int length() { return log2(topbit(value)); } public int cardinality() { int w = value; int c = 0; while (w != 0) { c += T[w & 255]; w >>= 8; } return c; } public boolean get(int index) { return (value & (1 << index)) != 0; } public void set(int index) { value |= (1 << index); } public void clear(int index) { value &= ~(1 << index); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ClassInfo.java0000644000175000017500000000261410066633132022672 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; abstract public class ClassInfo { protected ClassInfo() { } abstract public Type getType(); abstract public Type getSuperType(); abstract public Type[] getInterfaces(); abstract public int getModifiers(); public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof ClassInfo)) return false; return getType().equals(((ClassInfo)o).getType()); } public int hashCode() { return getType().hashCode(); } public String toString() { // TODO: include modifiers, superType, interfaces return getType().getClassName(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Constants.java0000644000175000017500000000700010402432050022745 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Type; /** * @author Juozas Baliuka baliuka@mwm.lt * @version $Id: Constants.java,v 1.21 2006/03/05 02:43:19 herbyderby Exp $ */ public interface Constants extends org.objectweb.asm.Opcodes { public static final Class[] EMPTY_CLASS_ARRAY = {}; public static final Type[] TYPES_EMPTY = {}; public static final Signature SIG_STATIC = TypeUtils.parseSignature("void ()"); public static final Type TYPE_OBJECT_ARRAY = TypeUtils.parseType("Object[]"); public static final Type TYPE_CLASS_ARRAY = TypeUtils.parseType("Class[]"); public static final Type TYPE_STRING_ARRAY = TypeUtils.parseType("String[]"); public static final Type TYPE_OBJECT = TypeUtils.parseType("Object"); public static final Type TYPE_CLASS = TypeUtils.parseType("Class"); public static final Type TYPE_CLASS_LOADER = TypeUtils.parseType("ClassLoader"); public static final Type TYPE_CHARACTER = TypeUtils.parseType("Character"); public static final Type TYPE_BOOLEAN = TypeUtils.parseType("Boolean"); public static final Type TYPE_DOUBLE = TypeUtils.parseType("Double"); public static final Type TYPE_FLOAT = TypeUtils.parseType("Float"); public static final Type TYPE_LONG = TypeUtils.parseType("Long"); public static final Type TYPE_INTEGER = TypeUtils.parseType("Integer"); public static final Type TYPE_SHORT = TypeUtils.parseType("Short"); public static final Type TYPE_BYTE = TypeUtils.parseType("Byte"); public static final Type TYPE_NUMBER = TypeUtils.parseType("Number"); public static final Type TYPE_STRING = TypeUtils.parseType("String"); public static final Type TYPE_THROWABLE = TypeUtils.parseType("Throwable"); public static final Type TYPE_BIG_INTEGER = TypeUtils.parseType("java.math.BigInteger"); public static final Type TYPE_BIG_DECIMAL = TypeUtils.parseType("java.math.BigDecimal"); public static final Type TYPE_STRING_BUFFER = TypeUtils.parseType("StringBuffer"); public static final Type TYPE_RUNTIME_EXCEPTION = TypeUtils.parseType("RuntimeException"); public static final Type TYPE_ERROR = TypeUtils.parseType("Error"); public static final Type TYPE_SYSTEM = TypeUtils.parseType("System"); public static final Type TYPE_SIGNATURE = TypeUtils.parseType("net.sf.cglib.core.Signature"); public static final String CONSTRUCTOR_NAME = ""; public static final String STATIC_NAME = ""; public static final String SOURCE_FILE = ""; public static final String SUID_FIELD_NAME = "serialVersionUID"; public static final int PRIVATE_FINAL_STATIC = ACC_PRIVATE | ACC_FINAL | ACC_STATIC; public static final int SWITCH_STYLE_TRIE = 0; public static final int SWITCH_STYLE_HASH = 1; public static final int SWITCH_STYLE_HASHONLY = 2; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/EmitUtils.java0000644000175000017500000011121010402432050022707 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.math.BigDecimal; import java.math.BigInteger; import java.util.*; import org.objectweb.asm.Label; import org.objectweb.asm.Type; public class EmitUtils { private static final Signature CSTRUCT_NULL = TypeUtils.parseConstructor(""); private static final Signature CSTRUCT_THROWABLE = TypeUtils.parseConstructor("Throwable"); private static final Signature GET_NAME = TypeUtils.parseSignature("String getName()"); private static final Signature HASH_CODE = TypeUtils.parseSignature("int hashCode()"); private static final Signature EQUALS = TypeUtils.parseSignature("boolean equals(Object)"); private static final Signature STRING_LENGTH = TypeUtils.parseSignature("int length()"); private static final Signature STRING_CHAR_AT = TypeUtils.parseSignature("char charAt(int)"); private static final Signature FOR_NAME = TypeUtils.parseSignature("Class forName(String)"); private static final Signature DOUBLE_TO_LONG_BITS = TypeUtils.parseSignature("long doubleToLongBits(double)"); private static final Signature FLOAT_TO_INT_BITS = TypeUtils.parseSignature("int floatToIntBits(float)"); private static final Signature TO_STRING = TypeUtils.parseSignature("String toString()"); private static final Signature APPEND_STRING = TypeUtils.parseSignature("StringBuffer append(String)"); private static final Signature APPEND_INT = TypeUtils.parseSignature("StringBuffer append(int)"); private static final Signature APPEND_DOUBLE = TypeUtils.parseSignature("StringBuffer append(double)"); private static final Signature APPEND_FLOAT = TypeUtils.parseSignature("StringBuffer append(float)"); private static final Signature APPEND_CHAR = TypeUtils.parseSignature("StringBuffer append(char)"); private static final Signature APPEND_LONG = TypeUtils.parseSignature("StringBuffer append(long)"); private static final Signature APPEND_BOOLEAN = TypeUtils.parseSignature("StringBuffer append(boolean)"); private static final Signature LENGTH = TypeUtils.parseSignature("int length()"); private static final Signature SET_LENGTH = TypeUtils.parseSignature("void setLength(int)"); private static final Signature GET_DECLARED_METHOD = TypeUtils.parseSignature("java.lang.reflect.Method getDeclaredMethod(String, Class[])"); public static final ArrayDelimiters DEFAULT_DELIMITERS = new ArrayDelimiters("{", ", ", "}"); private EmitUtils() { } public static void factory_method(ClassEmitter ce, Signature sig) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, sig, null); e.new_instance_this(); e.dup(); e.load_args(); e.invoke_constructor_this(TypeUtils.parseConstructor(sig.getArgumentTypes())); e.return_value(); e.end_method(); } public static void null_constructor(ClassEmitter ce) { CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, CSTRUCT_NULL, null); e.load_this(); e.super_invoke_constructor(); e.return_value(); e.end_method(); } /** * Process an array on the stack. Assumes the top item on the stack * is an array of the specified type. For each element in the array, * puts the element on the stack and triggers the callback. * @param type the type of the array (type.isArray() must be true) * @param callback the callback triggered for each element */ public static void process_array(CodeEmitter e, Type type, ProcessArrayCallback callback) { Type componentType = TypeUtils.getComponentType(type); Local array = e.make_local(); Local loopvar = e.make_local(Type.INT_TYPE); Label loopbody = e.make_label(); Label checkloop = e.make_label(); e.store_local(array); e.push(0); e.store_local(loopvar); e.goTo(checkloop); e.mark(loopbody); e.load_local(array); e.load_local(loopvar); e.array_load(componentType); callback.processElement(componentType); e.iinc(loopvar, 1); e.mark(checkloop); e.load_local(loopvar); e.load_local(array); e.arraylength(); e.if_icmp(e.LT, loopbody); } /** * Process two arrays on the stack in parallel. Assumes the top two items on the stack * are arrays of the specified class. The arrays must be the same length. For each pair * of elements in the arrays, puts the pair on the stack and triggers the callback. * @param type the type of the arrays (type.isArray() must be true) * @param callback the callback triggered for each pair of elements */ public static void process_arrays(CodeEmitter e, Type type, ProcessArrayCallback callback) { Type componentType = TypeUtils.getComponentType(type); Local array1 = e.make_local(); Local array2 = e.make_local(); Local loopvar = e.make_local(Type.INT_TYPE); Label loopbody = e.make_label(); Label checkloop = e.make_label(); e.store_local(array1); e.store_local(array2); e.push(0); e.store_local(loopvar); e.goTo(checkloop); e.mark(loopbody); e.load_local(array1); e.load_local(loopvar); e.array_load(componentType); e.load_local(array2); e.load_local(loopvar); e.array_load(componentType); callback.processElement(componentType); e.iinc(loopvar, 1); e.mark(checkloop); e.load_local(loopvar); e.load_local(array1); e.arraylength(); e.if_icmp(e.LT, loopbody); } public static void string_switch(CodeEmitter e, String[] strings, int switchStyle, ObjectSwitchCallback callback) { try { switch (switchStyle) { case Constants.SWITCH_STYLE_TRIE: string_switch_trie(e, strings, callback); break; case Constants.SWITCH_STYLE_HASH: string_switch_hash(e, strings, callback, false); break; case Constants.SWITCH_STYLE_HASHONLY: string_switch_hash(e, strings, callback, true); break; default: throw new IllegalArgumentException("unknown switch style " + switchStyle); } } catch (RuntimeException ex) { throw ex; } catch (Error ex) { throw ex; } catch (Exception ex) { throw new CodeGenerationException(ex); } } private static void string_switch_trie(final CodeEmitter e, String[] strings, final ObjectSwitchCallback callback) throws Exception { final Label def = e.make_label(); final Label end = e.make_label(); final Map buckets = CollectionUtils.bucket(Arrays.asList(strings), new Transformer() { public Object transform(Object value) { return new Integer(((String)value).length()); } }); e.dup(); e.invoke_virtual(Constants.TYPE_STRING, STRING_LENGTH); e.process_switch(getSwitchKeys(buckets), new ProcessSwitchCallback() { public void processCase(int key, Label ignore_end) throws Exception { List bucket = (List)buckets.get(new Integer(key)); stringSwitchHelper(e, bucket, callback, def, end, 0); } public void processDefault() { e.goTo(def); } }); e.mark(def); e.pop(); callback.processDefault(); e.mark(end); } private static void stringSwitchHelper(final CodeEmitter e, List strings, final ObjectSwitchCallback callback, final Label def, final Label end, final int index) throws Exception { final int len = ((String)strings.get(0)).length(); final Map buckets = CollectionUtils.bucket(strings, new Transformer() { public Object transform(Object value) { return new Integer(((String)value).charAt(index)); } }); e.dup(); e.push(index); e.invoke_virtual(Constants.TYPE_STRING, STRING_CHAR_AT); e.process_switch(getSwitchKeys(buckets), new ProcessSwitchCallback() { public void processCase(int key, Label ignore_end) throws Exception { List bucket = (List)buckets.get(new Integer(key)); if (index + 1 == len) { e.pop(); callback.processCase(bucket.get(0), end); } else { stringSwitchHelper(e, bucket, callback, def, end, index + 1); } } public void processDefault() { e.goTo(def); } }); } static int[] getSwitchKeys(Map buckets) { int[] keys = new int[buckets.size()]; int index = 0; for (Iterator it = buckets.keySet().iterator(); it.hasNext();) { keys[index++] = ((Integer)it.next()).intValue(); } Arrays.sort(keys); return keys; } private static void string_switch_hash(final CodeEmitter e, final String[] strings, final ObjectSwitchCallback callback, final boolean skipEquals) throws Exception { final Map buckets = CollectionUtils.bucket(Arrays.asList(strings), new Transformer() { public Object transform(Object value) { return new Integer(value.hashCode()); } }); final Label def = e.make_label(); final Label end = e.make_label(); e.dup(); e.invoke_virtual(Constants.TYPE_OBJECT, HASH_CODE); e.process_switch(getSwitchKeys(buckets), new ProcessSwitchCallback() { public void processCase(int key, Label ignore_end) throws Exception { List bucket = (List)buckets.get(new Integer(key)); Label next = null; if (skipEquals && bucket.size() == 1) { if (skipEquals) e.pop(); callback.processCase((String)bucket.get(0), end); } else { for (Iterator it = bucket.iterator(); it.hasNext();) { String string = (String)it.next(); if (next != null) { e.mark(next); } if (it.hasNext()) { e.dup(); } e.push(string); e.invoke_virtual(Constants.TYPE_OBJECT, EQUALS); if (it.hasNext()) { e.if_jump(e.EQ, next = e.make_label()); e.pop(); } else { e.if_jump(e.EQ, def); } callback.processCase(string, end); } } } public void processDefault() { e.pop(); } }); e.mark(def); callback.processDefault(); e.mark(end); } public static void load_class_this(CodeEmitter e) { load_class_helper(e, e.getClassEmitter().getClassType()); } public static void load_class(CodeEmitter e, Type type) { if (TypeUtils.isPrimitive(type)) { if (type == Type.VOID_TYPE) { throw new IllegalArgumentException("cannot load void type"); } e.getstatic(TypeUtils.getBoxedType(type), "TYPE", Constants.TYPE_CLASS); } else { load_class_helper(e, type); } } private static void load_class_helper(CodeEmitter e, final Type type) { if (e.isStaticHook()) { // have to fall back on non-optimized load e.push(TypeUtils.emulateClassGetName(type)); e.invoke_static(Constants.TYPE_CLASS, FOR_NAME); } else { ClassEmitter ce = e.getClassEmitter(); String typeName = TypeUtils.emulateClassGetName(type); // TODO: can end up with duplicated field names when using chained transformers; incorporate static hook # somehow String fieldName = "CGLIB$load_class$" + TypeUtils.escapeType(typeName); if (!ce.isFieldDeclared(fieldName)) { ce.declare_field(Constants.PRIVATE_FINAL_STATIC, fieldName, Constants.TYPE_CLASS, null); CodeEmitter hook = ce.getStaticHook(); hook.push(typeName); hook.invoke_static(Constants.TYPE_CLASS, FOR_NAME); hook.putstatic(ce.getClassType(), fieldName, Constants.TYPE_CLASS); } e.getfield(fieldName); } } public static void push_array(CodeEmitter e, Object[] array) { e.push(array.length); e.newarray(Type.getType(remapComponentType(array.getClass().getComponentType()))); for (int i = 0; i < array.length; i++) { e.dup(); e.push(i); push_object(e, array[i]); e.aastore(); } } private static Class remapComponentType(Class componentType) { if (componentType.equals(Type.class)) return Class.class; return componentType; } public static void push_object(CodeEmitter e, Object obj) { if (obj == null) { e.aconst_null(); } else { Class type = obj.getClass(); if (type.isArray()) { push_array(e, (Object[])obj); } else if (obj instanceof String) { e.push((String)obj); } else if (obj instanceof Type) { load_class(e, (Type)obj); } else if (obj instanceof Class) { load_class(e, Type.getType((Class)obj)); } else if (obj instanceof BigInteger) { e.new_instance(Constants.TYPE_BIG_INTEGER); e.dup(); e.push(obj.toString()); e.invoke_constructor(Constants.TYPE_BIG_INTEGER); } else if (obj instanceof BigDecimal) { e.new_instance(Constants.TYPE_BIG_DECIMAL); e.dup(); e.push(obj.toString()); e.invoke_constructor(Constants.TYPE_BIG_DECIMAL); } else { throw new IllegalArgumentException("unknown type: " + obj.getClass()); } } } public static void hash_code(CodeEmitter e, Type type, int multiplier, Customizer customizer) { if (TypeUtils.isArray(type)) { hash_array(e, type, multiplier, customizer); } else { e.swap(Type.INT_TYPE, type); e.push(multiplier); e.math(e.MUL, Type.INT_TYPE); e.swap(type, Type.INT_TYPE); if (TypeUtils.isPrimitive(type)) { hash_primitive(e, type); } else { hash_object(e, type, customizer); } e.math(e.ADD, Type.INT_TYPE); } } private static void hash_array(final CodeEmitter e, Type type, final int multiplier, final Customizer customizer) { Label skip = e.make_label(); Label end = e.make_label(); e.dup(); e.ifnull(skip); EmitUtils.process_array(e, type, new ProcessArrayCallback() { public void processElement(Type type) { hash_code(e, type, multiplier, customizer); } }); e.goTo(end); e.mark(skip); e.pop(); e.mark(end); } private static void hash_object(CodeEmitter e, Type type, Customizer customizer) { // (f == null) ? 0 : f.hashCode(); Label skip = e.make_label(); Label end = e.make_label(); e.dup(); e.ifnull(skip); if (customizer != null) { customizer.customize(e, type); } e.invoke_virtual(Constants.TYPE_OBJECT, HASH_CODE); e.goTo(end); e.mark(skip); e.pop(); e.push(0); e.mark(end); } private static void hash_primitive(CodeEmitter e, Type type) { switch (type.getSort()) { case Type.BOOLEAN: // f ? 0 : 1 e.push(1); e.math(e.XOR, Type.INT_TYPE); break; case Type.FLOAT: // Float.floatToIntBits(f) e.invoke_static(Constants.TYPE_FLOAT, FLOAT_TO_INT_BITS); break; case Type.DOUBLE: // Double.doubleToLongBits(f), hash_code(Long.TYPE) e.invoke_static(Constants.TYPE_DOUBLE, DOUBLE_TO_LONG_BITS); // fall through case Type.LONG: hash_long(e); } } private static void hash_long(CodeEmitter e) { // (int)(f ^ (f >>> 32)) e.dup2(); e.push(32); e.math(e.USHR, Type.LONG_TYPE); e.math(e.XOR, Type.LONG_TYPE); e.cast_numeric(Type.LONG_TYPE, Type.INT_TYPE); } // public static void not_equals(CodeEmitter e, Type type, Label notEquals) { // not_equals(e, type, notEquals, null); // } /** * Branches to the specified label if the top two items on the stack * are not equal. The items must both be of the specified * class. Equality is determined by comparing primitive values * directly and by invoking the equals method for * Objects. Arrays are recursively processed in the same manner. */ public static void not_equals(final CodeEmitter e, Type type, final Label notEquals, final Customizer customizer) { (new ProcessArrayCallback() { public void processElement(Type type) { not_equals_helper(e, type, notEquals, customizer, this); } }).processElement(type); } private static void not_equals_helper(CodeEmitter e, Type type, Label notEquals, Customizer customizer, ProcessArrayCallback callback) { if (TypeUtils.isPrimitive(type)) { e.if_cmp(type, e.NE, notEquals); } else { Label end = e.make_label(); nullcmp(e, notEquals, end); if (TypeUtils.isArray(type)) { Label checkContents = e.make_label(); e.dup2(); e.arraylength(); e.swap(); e.arraylength(); e.if_icmp(e.EQ, checkContents); e.pop2(); e.goTo(notEquals); e.mark(checkContents); EmitUtils.process_arrays(e, type, callback); } else { if (customizer != null) { customizer.customize(e, type); e.swap(); customizer.customize(e, type); } e.invoke_virtual(Constants.TYPE_OBJECT, EQUALS); e.if_jump(e.EQ, notEquals); } e.mark(end); } } /** * If both objects on the top of the stack are non-null, does nothing. * If one is null, or both are null, both are popped off and execution * branches to the respective label. * @param oneNull label to branch to if only one of the objects is null * @param bothNull label to branch to if both of the objects are null */ private static void nullcmp(CodeEmitter e, Label oneNull, Label bothNull) { e.dup2(); Label nonNull = e.make_label(); Label oneNullHelper = e.make_label(); Label end = e.make_label(); e.ifnonnull(nonNull); e.ifnonnull(oneNullHelper); e.pop2(); e.goTo(bothNull); e.mark(nonNull); e.ifnull(oneNullHelper); e.goTo(end); e.mark(oneNullHelper); e.pop2(); e.goTo(oneNull); e.mark(end); } /* public static void to_string(CodeEmitter e, Type type, ArrayDelimiters delims, Customizer customizer) { e.new_instance(Constants.TYPE_STRING_BUFFER); e.dup(); e.invoke_constructor(Constants.TYPE_STRING_BUFFER); e.swap(); append_string(e, type, delims, customizer); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, TO_STRING); } */ public static void append_string(final CodeEmitter e, Type type, final ArrayDelimiters delims, final Customizer customizer) { final ArrayDelimiters d = (delims != null) ? delims : DEFAULT_DELIMITERS; ProcessArrayCallback callback = new ProcessArrayCallback() { public void processElement(Type type) { append_string_helper(e, type, d, customizer, this); e.push(d.inside); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); } }; append_string_helper(e, type, d, customizer, callback); } private static void append_string_helper(CodeEmitter e, Type type, ArrayDelimiters delims, Customizer customizer, ProcessArrayCallback callback) { Label skip = e.make_label(); Label end = e.make_label(); if (TypeUtils.isPrimitive(type)) { switch (type.getSort()) { case Type.INT: case Type.SHORT: case Type.BYTE: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_INT); break; case Type.DOUBLE: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_DOUBLE); break; case Type.FLOAT: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_FLOAT); break; case Type.LONG: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_LONG); break; case Type.BOOLEAN: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_BOOLEAN); break; case Type.CHAR: e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_CHAR); break; } } else if (TypeUtils.isArray(type)) { e.dup(); e.ifnull(skip); e.swap(); if (delims != null && delims.before != null && !"".equals(delims.before)) { e.push(delims.before); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); e.swap(); } EmitUtils.process_array(e, type, callback); shrinkStringBuffer(e, 2); if (delims != null && delims.after != null && !"".equals(delims.after)) { e.push(delims.after); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); } } else { e.dup(); e.ifnull(skip); if (customizer != null) { customizer.customize(e, type); } e.invoke_virtual(Constants.TYPE_OBJECT, TO_STRING); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); } e.goTo(end); e.mark(skip); e.pop(); e.push("null"); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); e.mark(end); } private static void shrinkStringBuffer(CodeEmitter e, int amt) { e.dup(); e.dup(); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, LENGTH); e.push(amt); e.math(e.SUB, Type.INT_TYPE); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, SET_LENGTH); } public static class ArrayDelimiters { private String before; private String inside; private String after; public ArrayDelimiters(String before, String inside, String after) { this.before = before; this.inside = inside; this.after = after; } } public static void load_method(CodeEmitter e, MethodInfo method) { load_class(e, method.getClassInfo().getType()); e.push(method.getSignature().getName()); push_object(e, method.getSignature().getArgumentTypes()); e.invoke_virtual(Constants.TYPE_CLASS, GET_DECLARED_METHOD); } private interface ParameterTyper { Type[] getParameterTypes(MethodInfo member); } public static void method_switch(CodeEmitter e, List methods, ObjectSwitchCallback callback) { member_switch_helper(e, methods, callback, true); } public static void constructor_switch(CodeEmitter e, List constructors, ObjectSwitchCallback callback) { member_switch_helper(e, constructors, callback, false); } private static void member_switch_helper(final CodeEmitter e, List members, final ObjectSwitchCallback callback, boolean useName) { try { final Map cache = new HashMap(); final ParameterTyper cached = new ParameterTyper() { public Type[] getParameterTypes(MethodInfo member) { Type[] types = (Type[])cache.get(member); if (types == null) { cache.put(member, types = member.getSignature().getArgumentTypes()); } return types; } }; final Label def = e.make_label(); final Label end = e.make_label(); if (useName) { e.swap(); final Map buckets = CollectionUtils.bucket(members, new Transformer() { public Object transform(Object value) { return ((MethodInfo)value).getSignature().getName(); } }); String[] names = (String[])buckets.keySet().toArray(new String[buckets.size()]); EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label dontUseEnd) throws Exception { member_helper_size(e, (List)buckets.get(key), callback, cached, def, end); } public void processDefault() throws Exception { e.goTo(def); } }); } else { member_helper_size(e, members, callback, cached, def, end); } e.mark(def); e.pop(); callback.processDefault(); e.mark(end); } catch (RuntimeException ex) { throw ex; } catch (Error ex) { throw ex; } catch (Exception ex) { throw new CodeGenerationException(ex); } } private static void member_helper_size(final CodeEmitter e, List members, final ObjectSwitchCallback callback, final ParameterTyper typer, final Label def, final Label end) throws Exception { final Map buckets = CollectionUtils.bucket(members, new Transformer() { public Object transform(Object value) { return new Integer(typer.getParameterTypes((MethodInfo)value).length); } }); e.dup(); e.arraylength(); e.process_switch(EmitUtils.getSwitchKeys(buckets), new ProcessSwitchCallback() { public void processCase(int key, Label dontUseEnd) throws Exception { List bucket = (List)buckets.get(new Integer(key)); member_helper_type(e, bucket, callback, typer, def, end, new BitSet()); } public void processDefault() throws Exception { e.goTo(def); } }); } private static void member_helper_type(final CodeEmitter e, List members, final ObjectSwitchCallback callback, final ParameterTyper typer, final Label def, final Label end, final BitSet checked) throws Exception { if (members.size() == 1) { MethodInfo member = (MethodInfo)members.get(0); Type[] types = typer.getParameterTypes(member); // need to check classes that have not already been checked via switches for (int i = 0; i < types.length; i++) { if (checked == null || !checked.get(i)) { e.dup(); e.aaload(i); e.invoke_virtual(Constants.TYPE_CLASS, GET_NAME); e.push(TypeUtils.emulateClassGetName(types[i])); e.invoke_virtual(Constants.TYPE_OBJECT, EQUALS); e.if_jump(e.EQ, def); } } e.pop(); callback.processCase(member, end); } else { // choose the index that has the best chance of uniquely identifying member Type[] example = typer.getParameterTypes((MethodInfo)members.get(0)); Map buckets = null; int index = -1; for (int i = 0; i < example.length; i++) { final int j = i; Map test = CollectionUtils.bucket(members, new Transformer() { public Object transform(Object value) { return TypeUtils.emulateClassGetName(typer.getParameterTypes((MethodInfo)value)[j]); } }); if (buckets == null || test.size() > buckets.size()) { buckets = test; index = i; } } if (buckets == null || buckets.size() == 1) { // TODO: switch by returnType // must have two methods with same name, types, and different return types e.goTo(def); } else { checked.set(index); e.dup(); e.aaload(index); e.invoke_virtual(Constants.TYPE_CLASS, GET_NAME); final Map fbuckets = buckets; String[] names = (String[])buckets.keySet().toArray(new String[buckets.size()]); EmitUtils.string_switch(e, names, Constants.SWITCH_STYLE_HASH, new ObjectSwitchCallback() { public void processCase(Object key, Label dontUseEnd) throws Exception { member_helper_type(e, (List)fbuckets.get(key), callback, typer, def, end, checked); } public void processDefault() throws Exception { e.goTo(def); } }); } } } public static void wrap_throwable(Block block, Type wrapper) { CodeEmitter e = block.getCodeEmitter(); e.catch_exception(block, Constants.TYPE_THROWABLE); e.new_instance(wrapper); e.dup_x1(); e.swap(); e.invoke_constructor(wrapper, CSTRUCT_THROWABLE); e.athrow(); } public static void add_properties(ClassEmitter ce, String[] names, Type[] types) { for (int i = 0; i < names.length; i++) { String fieldName = "$cglib_prop_" + names[i]; ce.declare_field(Constants.ACC_PRIVATE, fieldName, types[i], null); EmitUtils.add_property(ce, names[i], types[i], fieldName); } } public static void add_property(ClassEmitter ce, String name, Type type, String fieldName) { String property = TypeUtils.upperFirst(name); CodeEmitter e; e = ce.begin_method(Constants.ACC_PUBLIC, new Signature("get" + property, type, Constants.TYPES_EMPTY), null); e.load_this(); e.getfield(fieldName); e.return_value(); e.end_method(); e = ce.begin_method(Constants.ACC_PUBLIC, new Signature("set" + property, Type.VOID_TYPE, new Type[]{ type }), null); e.load_this(); e.load_arg(0); e.putfield(fieldName); e.return_value(); e.end_method(); } /* generates: } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch ( e) { throw e; } catch (Throwable e) { throw new (e); } */ public static void wrap_undeclared_throwable(CodeEmitter e, Block handler, Type[] exceptions, Type wrapper) { Set set = (exceptions == null) ? Collections.EMPTY_SET : new HashSet(Arrays.asList(exceptions)); if (set.contains(Constants.TYPE_THROWABLE)) return; boolean needThrow = exceptions != null; if (!set.contains(Constants.TYPE_RUNTIME_EXCEPTION)) { e.catch_exception(handler, Constants.TYPE_RUNTIME_EXCEPTION); needThrow = true; } if (!set.contains(Constants.TYPE_ERROR)) { e.catch_exception(handler, Constants.TYPE_ERROR); needThrow = true; } if (exceptions != null) { for (int i = 0; i < exceptions.length; i++) { e.catch_exception(handler, exceptions[i]); } } if (needThrow) { e.athrow(); } // e -> eo -> oeo -> ooe -> o e.catch_exception(handler, Constants.TYPE_THROWABLE); e.new_instance(wrapper); e.dup_x1(); e.swap(); e.invoke_constructor(wrapper, CSTRUCT_THROWABLE); e.athrow(); } public static CodeEmitter begin_method(ClassEmitter e, MethodInfo method) { return begin_method(e, method, method.getModifiers()); } public static CodeEmitter begin_method(ClassEmitter e, MethodInfo method, int access) { return e.begin_method(access, method.getSignature(), method.getExceptionTypes()); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/DebuggingClassWriter.java0000644000175000017500000001046012250624654025073 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import java.io.*; import java.lang.reflect.Constructor; public class DebuggingClassWriter extends ClassVisitor { public static final String DEBUG_LOCATION_PROPERTY = "cglib.debugLocation"; private static String debugLocation; private static Constructor traceCtor; private String className; private String superName; static { debugLocation = System.getProperty(DEBUG_LOCATION_PROPERTY); if (debugLocation != null) { System.err.println("CGLIB debugging enabled, writing to '" + debugLocation + "'"); try { Class clazz = Class.forName("org.objectweb.asm.util.TraceClassVisitor"); traceCtor = clazz.getConstructor(new Class[]{ClassVisitor.class, PrintWriter.class}); } catch (Throwable ignore) { } } } public DebuggingClassWriter(int flags) { super(Opcodes.ASM4, new ClassWriter(flags)); } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { className = name.replace('/', '.'); this.superName = superName.replace('/', '.'); super.visit(version, access, name, signature, superName, interfaces); } public String getClassName() { return className; } public String getSuperName() { return superName; } public byte[] toByteArray() { return (byte[]) java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public Object run() { byte[] b = ((ClassWriter) DebuggingClassWriter.super.cv).toByteArray(); if (debugLocation != null) { String dirs = className.replace('.', File.separatorChar); try { new File(debugLocation + File.separatorChar + dirs).getParentFile().mkdirs(); File file = new File(new File(debugLocation), dirs + ".class"); OutputStream out = new BufferedOutputStream(new FileOutputStream(file)); try { out.write(b); } finally { out.close(); } if (traceCtor != null) { file = new File(new File(debugLocation), dirs + ".asm"); out = new BufferedOutputStream(new FileOutputStream(file)); try { ClassReader cr = new ClassReader(b); PrintWriter pw = new PrintWriter(new OutputStreamWriter(out)); ClassVisitor tcv = (ClassVisitor)traceCtor.newInstance(new Object[]{null, pw}); cr.accept(tcv, 0); pw.flush(); } finally { out.close(); } } } catch (Exception e) { throw new CodeGenerationException(e); } } return b; } }); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Converter.java0000644000175000017500000000137010066633132022756 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; public interface Converter { Object convert(Object value, Class target, Object context); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/DefaultGeneratorStrategy.java0000644000175000017500000000331412250620376025770 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.ClassWriter; public class DefaultGeneratorStrategy implements GeneratorStrategy { public static final DefaultGeneratorStrategy INSTANCE = new DefaultGeneratorStrategy(); public byte[] generate(ClassGenerator cg) throws Exception { DebuggingClassWriter cw = getClassVisitor(); transform(cg).generateClass(cw); return transform(cw.toByteArray()); } protected DebuggingClassWriter getClassVisitor() throws Exception { return new DebuggingClassWriter(ClassWriter.COMPUTE_MAXS); } protected final ClassWriter getClassWriter() { // Cause compile / runtime errors for people who implemented the old // interface without using @Override throw new UnsupportedOperationException("You are calling " + "getClassWriter, which no longer exists in this cglib version."); } protected byte[] transform(byte[] b) throws Exception { return b; } protected ClassGenerator transform(ClassGenerator cg) throws Exception { return cg; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ClassNameReader.java0000644000175000017500000000443412250620376024007 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.ClassReader; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Opcodes; import java.util.*; // TODO: optimize (ClassReader buffers entire class before accept) public class ClassNameReader { private ClassNameReader() { } private static final EarlyExitException EARLY_EXIT = new EarlyExitException(); private static class EarlyExitException extends RuntimeException { } public static String getClassName(ClassReader r) { return getClassInfo(r)[0]; } public static String[] getClassInfo(ClassReader r) { final List array = new ArrayList(); try { r.accept(new ClassVisitor(Opcodes.ASM4, null) { public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { array.add( name.replace('/', '.') ); if(superName != null){ array.add( superName.replace('/', '.') ); } for(int i = 0; i < interfaces.length; i++ ){ array.add( interfaces[i].replace('/', '.') ); } throw EARLY_EXIT; } }, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } catch (EarlyExitException e) { } return (String[])array.toArray( new String[]{} ); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/MethodInfoTransformer.java0000644000175000017500000000247010066633132025270 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.*; public class MethodInfoTransformer implements Transformer { private static final MethodInfoTransformer INSTANCE = new MethodInfoTransformer(); public static MethodInfoTransformer getInstance() { return INSTANCE; } public Object transform(Object value) { if (value instanceof Method) { return ReflectUtils.getMethodInfo((Method)value); } else if (value instanceof Constructor) { return ReflectUtils.getMethodInfo((Constructor)value); } else { throw new IllegalArgumentException("cannot get method info for " + value); } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Local.java0000644000175000017500000000175610066633132022051 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Type; public class Local { private Type type; private int index; public Local(int index, Type type) { this.type = type; this.index = index; } public int getIndex() { return index; } public Type getType() { return type; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ReflectUtils.java0000644000175000017500000004276011132421266023422 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.beans.*; import java.lang.reflect.*; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.*; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; /** * @version $Id: ReflectUtils.java,v 1.30 2009/01/11 19:47:49 herbyderby Exp $ */ public class ReflectUtils { private ReflectUtils() { } private static final Map primitives = new HashMap(8); private static final Map transforms = new HashMap(8); private static final ClassLoader defaultLoader = ReflectUtils.class.getClassLoader(); private static Method DEFINE_CLASS; private static final ProtectionDomain PROTECTION_DOMAIN; static { PROTECTION_DOMAIN = (ProtectionDomain)AccessController.doPrivileged(new PrivilegedAction() { public Object run() { return ReflectUtils.class.getProtectionDomain(); } }); AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { Class loader = Class.forName("java.lang.ClassLoader"); // JVM crash w/o this DEFINE_CLASS = loader.getDeclaredMethod("defineClass", new Class[]{ String.class, byte[].class, Integer.TYPE, Integer.TYPE, ProtectionDomain.class }); DEFINE_CLASS.setAccessible(true); } catch (ClassNotFoundException e) { throw new CodeGenerationException(e); } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } return null; } }); } private static final String[] CGLIB_PACKAGES = { "java.lang", }; static { primitives.put("byte", Byte.TYPE); primitives.put("char", Character.TYPE); primitives.put("double", Double.TYPE); primitives.put("float", Float.TYPE); primitives.put("int", Integer.TYPE); primitives.put("long", Long.TYPE); primitives.put("short", Short.TYPE); primitives.put("boolean", Boolean.TYPE); transforms.put("byte", "B"); transforms.put("char", "C"); transforms.put("double", "D"); transforms.put("float", "F"); transforms.put("int", "I"); transforms.put("long", "J"); transforms.put("short", "S"); transforms.put("boolean", "Z"); } public static Type[] getExceptionTypes(Member member) { if (member instanceof Method) { return TypeUtils.getTypes(((Method)member).getExceptionTypes()); } else if (member instanceof Constructor) { return TypeUtils.getTypes(((Constructor)member).getExceptionTypes()); } else { throw new IllegalArgumentException("Cannot get exception types of a field"); } } public static Signature getSignature(Member member) { if (member instanceof Method) { return new Signature(member.getName(), Type.getMethodDescriptor((Method)member)); } else if (member instanceof Constructor) { Type[] types = TypeUtils.getTypes(((Constructor)member).getParameterTypes()); return new Signature(Constants.CONSTRUCTOR_NAME, Type.getMethodDescriptor(Type.VOID_TYPE, types)); } else { throw new IllegalArgumentException("Cannot get signature of a field"); } } public static Constructor findConstructor(String desc) { return findConstructor(desc, defaultLoader); } public static Constructor findConstructor(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); String className = desc.substring(0, lparen).trim(); return getClass(className, loader).getConstructor(parseTypes(desc, loader)); } catch (ClassNotFoundException e) { throw new CodeGenerationException(e); } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } public static Method findMethod(String desc) { return findMethod(desc, defaultLoader); } public static Method findMethod(String desc, ClassLoader loader) { try { int lparen = desc.indexOf('('); int dot = desc.lastIndexOf('.', lparen); String className = desc.substring(0, dot).trim(); String methodName = desc.substring(dot + 1, lparen).trim(); return getClass(className, loader).getDeclaredMethod(methodName, parseTypes(desc, loader)); } catch (ClassNotFoundException e) { throw new CodeGenerationException(e); } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } private static Class[] parseTypes(String desc, ClassLoader loader) throws ClassNotFoundException { int lparen = desc.indexOf('('); int rparen = desc.indexOf(')', lparen); List params = new ArrayList(); int start = lparen + 1; for (;;) { int comma = desc.indexOf(',', start); if (comma < 0) { break; } params.add(desc.substring(start, comma).trim()); start = comma + 1; } if (start < rparen) { params.add(desc.substring(start, rparen).trim()); } Class[] types = new Class[params.size()]; for (int i = 0; i < types.length; i++) { types[i] = getClass((String)params.get(i), loader); } return types; } private static Class getClass(String className, ClassLoader loader) throws ClassNotFoundException { return getClass(className, loader, CGLIB_PACKAGES); } private static Class getClass(String className, ClassLoader loader, String[] packages) throws ClassNotFoundException { String save = className; int dimensions = 0; int index = 0; while ((index = className.indexOf("[]", index) + 1) > 0) { dimensions++; } StringBuffer brackets = new StringBuffer(className.length() - dimensions); for (int i = 0; i < dimensions; i++) { brackets.append('['); } className = className.substring(0, className.length() - 2 * dimensions); String prefix = (dimensions > 0) ? brackets + "L" : ""; String suffix = (dimensions > 0) ? ";" : ""; try { return Class.forName(prefix + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } for (int i = 0; i < packages.length; i++) { try { return Class.forName(prefix + packages[i] + '.' + className + suffix, false, loader); } catch (ClassNotFoundException ignore) { } } if (dimensions == 0) { Class c = (Class)primitives.get(className); if (c != null) { return c; } } else { String transform = (String)transforms.get(className); if (transform != null) { try { return Class.forName(brackets + transform, false, loader); } catch (ClassNotFoundException ignore) { } } } throw new ClassNotFoundException(save); } public static Object newInstance(Class type) { return newInstance(type, Constants.EMPTY_CLASS_ARRAY, null); } public static Object newInstance(Class type, Class[] parameterTypes, Object[] args) { return newInstance(getConstructor(type, parameterTypes), args); } public static Object newInstance(final Constructor cstruct, final Object[] args) { boolean flag = cstruct.isAccessible(); try { cstruct.setAccessible(true); Object result = cstruct.newInstance(args); return result; } catch (InstantiationException e) { throw new CodeGenerationException(e); } catch (IllegalAccessException e) { throw new CodeGenerationException(e); } catch (InvocationTargetException e) { throw new CodeGenerationException(e.getTargetException()); } finally { cstruct.setAccessible(flag); } } public static Constructor getConstructor(Class type, Class[] parameterTypes) { try { Constructor constructor = type.getDeclaredConstructor(parameterTypes); constructor.setAccessible(true); return constructor; } catch (NoSuchMethodException e) { throw new CodeGenerationException(e); } } public static String[] getNames(Class[] classes) { if (classes == null) return null; String[] names = new String[classes.length]; for (int i = 0; i < names.length; i++) { names[i] = classes[i].getName(); } return names; } public static Class[] getClasses(Object[] objects) { Class[] classes = new Class[objects.length]; for (int i = 0; i < objects.length; i++) { classes[i] = objects[i].getClass(); } return classes; } public static Method findNewInstance(Class iface) { Method m = findInterfaceMethod(iface); if (!m.getName().equals("newInstance")) { throw new IllegalArgumentException(iface + " missing newInstance method"); } return m; } public static Method[] getPropertyMethods(PropertyDescriptor[] properties, boolean read, boolean write) { Set methods = new HashSet(); for (int i = 0; i < properties.length; i++) { PropertyDescriptor pd = properties[i]; if (read) { methods.add(pd.getReadMethod()); } if (write) { methods.add(pd.getWriteMethod()); } } methods.remove(null); return (Method[])methods.toArray(new Method[methods.size()]); } public static PropertyDescriptor[] getBeanProperties(Class type) { return getPropertiesHelper(type, true, true); } public static PropertyDescriptor[] getBeanGetters(Class type) { return getPropertiesHelper(type, true, false); } public static PropertyDescriptor[] getBeanSetters(Class type) { return getPropertiesHelper(type, false, true); } private static PropertyDescriptor[] getPropertiesHelper(Class type, boolean read, boolean write) { try { BeanInfo info = Introspector.getBeanInfo(type, Object.class); PropertyDescriptor[] all = info.getPropertyDescriptors(); if (read && write) { return all; } List properties = new ArrayList(all.length); for (int i = 0; i < all.length; i++) { PropertyDescriptor pd = all[i]; if ((read && pd.getReadMethod() != null) || (write && pd.getWriteMethod() != null)) { properties.add(pd); } } return (PropertyDescriptor[])properties.toArray(new PropertyDescriptor[properties.size()]); } catch (IntrospectionException e) { throw new CodeGenerationException(e); } } public static Method findDeclaredMethod(final Class type, final String methodName, final Class[] parameterTypes) throws NoSuchMethodException { Class cl = type; while (cl != null) { try { return cl.getDeclaredMethod(methodName, parameterTypes); } catch (NoSuchMethodException e) { cl = cl.getSuperclass(); } } throw new NoSuchMethodException(methodName); } public static List addAllMethods(final Class type, final List list) { list.addAll(java.util.Arrays.asList(type.getDeclaredMethods())); Class superclass = type.getSuperclass(); if (superclass != null) { addAllMethods(superclass, list); } Class[] interfaces = type.getInterfaces(); for (int i = 0; i < interfaces.length; i++) { addAllMethods(interfaces[i], list); } return list; } public static List addAllInterfaces(Class type, List list) { Class superclass = type.getSuperclass(); if (superclass != null) { list.addAll(Arrays.asList(type.getInterfaces())); addAllInterfaces(superclass, list); } return list; } public static Method findInterfaceMethod(Class iface) { if (!iface.isInterface()) { throw new IllegalArgumentException(iface + " is not an interface"); } Method[] methods = iface.getDeclaredMethods(); if (methods.length != 1) { throw new IllegalArgumentException("expecting exactly 1 method in " + iface); } return methods[0]; } public static Class defineClass(String className, byte[] b, ClassLoader loader) throws Exception { Object[] args = new Object[]{className, b, new Integer(0), new Integer(b.length), PROTECTION_DOMAIN }; Class c = (Class)DEFINE_CLASS.invoke(loader, args); // Force static initializers to run. Class.forName(className, true, loader); return c; } public static int findPackageProtected(Class[] classes) { for (int i = 0; i < classes.length; i++) { if (!Modifier.isPublic(classes[i].getModifiers())) { return i; } } return 0; } public static MethodInfo getMethodInfo(final Member member, final int modifiers) { final Signature sig = getSignature(member); return new MethodInfo() { private ClassInfo ci; public ClassInfo getClassInfo() { if (ci == null) ci = ReflectUtils.getClassInfo(member.getDeclaringClass()); return ci; } public int getModifiers() { return modifiers; } public Signature getSignature() { return sig; } public Type[] getExceptionTypes() { return ReflectUtils.getExceptionTypes(member); } public Attribute getAttribute() { return null; } }; } public static MethodInfo getMethodInfo(Member member) { return getMethodInfo(member, member.getModifiers()); } public static ClassInfo getClassInfo(final Class clazz) { final Type type = Type.getType(clazz); final Type sc = (clazz.getSuperclass() == null) ? null : Type.getType(clazz.getSuperclass()); return new ClassInfo() { public Type getType() { return type; } public Type getSuperType() { return sc; } public Type[] getInterfaces() { return TypeUtils.getTypes(clazz.getInterfaces()); } public int getModifiers() { return clazz.getModifiers(); } }; } // used by MethodInterceptorGenerated generated code public static Method[] findMethods(String[] namesAndDescriptors, Method[] methods) { Map map = new HashMap(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; map.put(method.getName() + Type.getMethodDescriptor(method), method); } Method[] result = new Method[namesAndDescriptors.length / 2]; for (int i = 0; i < result.length; i++) { result[i] = (Method)map.get(namesAndDescriptors[i * 2] + namesAndDescriptors[i * 2 + 1]); if (result[i] == null) { // TODO: error? } } return result; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/CodeEmitter.java0000644000175000017500000006637610402432050023222 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.io.*; import java.util.*; import org.objectweb.asm.*; /** * @author Juozas Baliuka, Chris Nokleberg */ public class CodeEmitter extends LocalVariablesSorter { private static final Signature BOOLEAN_VALUE = TypeUtils.parseSignature("boolean booleanValue()"); private static final Signature CHAR_VALUE = TypeUtils.parseSignature("char charValue()"); private static final Signature LONG_VALUE = TypeUtils.parseSignature("long longValue()"); private static final Signature DOUBLE_VALUE = TypeUtils.parseSignature("double doubleValue()"); private static final Signature FLOAT_VALUE = TypeUtils.parseSignature("float floatValue()"); private static final Signature INT_VALUE = TypeUtils.parseSignature("int intValue()"); private static final Signature CSTRUCT_NULL = TypeUtils.parseConstructor(""); private static final Signature CSTRUCT_STRING = TypeUtils.parseConstructor("String"); public static final int ADD = Constants.IADD; public static final int MUL = Constants.IMUL; public static final int XOR = Constants.IXOR; public static final int USHR = Constants.IUSHR; public static final int SUB = Constants.ISUB; public static final int DIV = Constants.IDIV; public static final int NEG = Constants.INEG; public static final int REM = Constants.IREM; public static final int AND = Constants.IAND; public static final int OR = Constants.IOR; public static final int GT = Constants.IFGT; public static final int LT = Constants.IFLT; public static final int GE = Constants.IFGE; public static final int LE = Constants.IFLE; public static final int NE = Constants.IFNE; public static final int EQ = Constants.IFEQ; private ClassEmitter ce; private State state; private static class State extends MethodInfo { ClassInfo classInfo; int access; Signature sig; Type[] argumentTypes; int localOffset; Type[] exceptionTypes; State(ClassInfo classInfo, int access, Signature sig, Type[] exceptionTypes) { this.classInfo = classInfo; this.access = access; this.sig = sig; this.exceptionTypes = exceptionTypes; localOffset = TypeUtils.isStatic(access) ? 0 : 1; argumentTypes = sig.getArgumentTypes(); } public ClassInfo getClassInfo() { return classInfo; } public int getModifiers() { return access; } public Signature getSignature() { return sig; } public Type[] getExceptionTypes() { return exceptionTypes; } public Attribute getAttribute() { // TODO return null; } } CodeEmitter(ClassEmitter ce, MethodVisitor mv, int access, Signature sig, Type[] exceptionTypes) { super(access, sig.getDescriptor(), mv); this.ce = ce; state = new State(ce.getClassInfo(), access, sig, exceptionTypes); } public CodeEmitter(CodeEmitter wrap) { super(wrap); this.ce = wrap.ce; this.state = wrap.state; } public boolean isStaticHook() { return false; } public Signature getSignature() { return state.sig; } public Type getReturnType() { return state.sig.getReturnType(); } public MethodInfo getMethodInfo() { return state; } public ClassEmitter getClassEmitter() { return ce; } public void end_method() { visitMaxs(0, 0); } public Block begin_block() { return new Block(this); } public void catch_exception(Block block, Type exception) { if (block.getEnd() == null) { throw new IllegalStateException("end of block is unset"); } mv.visitTryCatchBlock(block.getStart(), block.getEnd(), mark(), exception.getInternalName()); } public void goTo(Label label) { mv.visitJumpInsn(Constants.GOTO, label); } public void ifnull(Label label) { mv.visitJumpInsn(Constants.IFNULL, label); } public void ifnonnull(Label label) { mv.visitJumpInsn(Constants.IFNONNULL, label); } public void if_jump(int mode, Label label) { mv.visitJumpInsn(mode, label); } public void if_icmp(int mode, Label label) { if_cmp(Type.INT_TYPE, mode, label); } public void if_cmp(Type type, int mode, Label label) { int intOp = -1; int jumpmode = mode; switch (mode) { case GE: jumpmode = LT; break; case LE: jumpmode = GT; break; } switch (type.getSort()) { case Type.LONG: mv.visitInsn(Constants.LCMP); break; case Type.DOUBLE: mv.visitInsn(Constants.DCMPG); break; case Type.FLOAT: mv.visitInsn(Constants.FCMPG); break; case Type.ARRAY: case Type.OBJECT: switch (mode) { case EQ: mv.visitJumpInsn(Constants.IF_ACMPEQ, label); return; case NE: mv.visitJumpInsn(Constants.IF_ACMPNE, label); return; } throw new IllegalArgumentException("Bad comparison for type " + type); default: switch (mode) { case EQ: intOp = Constants.IF_ICMPEQ; break; case NE: intOp = Constants.IF_ICMPNE; break; case GE: swap(); /* fall through */ case LT: intOp = Constants.IF_ICMPLT; break; case LE: swap(); /* fall through */ case GT: intOp = Constants.IF_ICMPGT; break; } mv.visitJumpInsn(intOp, label); return; } if_jump(jumpmode, label); } public void pop() { mv.visitInsn(Constants.POP); } public void pop2() { mv.visitInsn(Constants.POP2); } public void dup() { mv.visitInsn(Constants.DUP); } public void dup2() { mv.visitInsn(Constants.DUP2); } public void dup_x1() { mv.visitInsn(Constants.DUP_X1); } public void dup_x2() { mv.visitInsn(Constants.DUP_X2); } public void dup2_x1() { mv.visitInsn(Constants.DUP2_X1); } public void dup2_x2() { mv.visitInsn(Constants.DUP2_X2); } public void swap() { mv.visitInsn(Constants.SWAP); } public void aconst_null() { mv.visitInsn(Constants.ACONST_NULL); } public void swap(Type prev, Type type) { if (type.getSize() == 1) { if (prev.getSize() == 1) { swap(); // same as dup_x1(), pop(); } else { dup_x2(); pop(); } } else { if (prev.getSize() == 1) { dup2_x1(); pop2(); } else { dup2_x2(); pop2(); } } } public void monitorenter() { mv.visitInsn(Constants.MONITORENTER); } public void monitorexit() { mv.visitInsn(Constants.MONITOREXIT); } public void math(int op, Type type) { mv.visitInsn(type.getOpcode(op)); } public void array_load(Type type) { mv.visitInsn(type.getOpcode(Constants.IALOAD)); } public void array_store(Type type) { mv.visitInsn(type.getOpcode(Constants.IASTORE)); } /** * Casts from one primitive numeric type to another */ public void cast_numeric(Type from, Type to) { if (from != to) { if (from == Type.DOUBLE_TYPE) { if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.D2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.D2L); } else { mv.visitInsn(Constants.D2I); cast_numeric(Type.INT_TYPE, to); } } else if (from == Type.FLOAT_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.F2D); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.F2L); } else { mv.visitInsn(Constants.F2I); cast_numeric(Type.INT_TYPE, to); } } else if (from == Type.LONG_TYPE) { if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.L2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.L2F); } else { mv.visitInsn(Constants.L2I); cast_numeric(Type.INT_TYPE, to); } } else { if (to == Type.BYTE_TYPE) { mv.visitInsn(Constants.I2B); } else if (to == Type.CHAR_TYPE) { mv.visitInsn(Constants.I2C); } else if (to == Type.DOUBLE_TYPE) { mv.visitInsn(Constants.I2D); } else if (to == Type.FLOAT_TYPE) { mv.visitInsn(Constants.I2F); } else if (to == Type.LONG_TYPE) { mv.visitInsn(Constants.I2L); } else if (to == Type.SHORT_TYPE) { mv.visitInsn(Constants.I2S); } } } } public void push(int i) { if (i < -1) { mv.visitLdcInsn(new Integer(i)); } else if (i <= 5) { mv.visitInsn(TypeUtils.ICONST(i)); } else if (i <= Byte.MAX_VALUE) { mv.visitIntInsn(Constants.BIPUSH, i); } else if (i <= Short.MAX_VALUE) { mv.visitIntInsn(Constants.SIPUSH, i); } else { mv.visitLdcInsn(new Integer(i)); } } public void push(long value) { if (value == 0L || value == 1L) { mv.visitInsn(TypeUtils.LCONST(value)); } else { mv.visitLdcInsn(new Long(value)); } } public void push(float value) { if (value == 0f || value == 1f || value == 2f) { mv.visitInsn(TypeUtils.FCONST(value)); } else { mv.visitLdcInsn(new Float(value)); } } public void push(double value) { if (value == 0d || value == 1d) { mv.visitInsn(TypeUtils.DCONST(value)); } else { mv.visitLdcInsn(new Double(value)); } } public void push(String value) { mv.visitLdcInsn(value); } public void newarray() { newarray(Constants.TYPE_OBJECT); } public void newarray(Type type) { if (TypeUtils.isPrimitive(type)) { mv.visitIntInsn(Constants.NEWARRAY, TypeUtils.NEWARRAY(type)); } else { emit_type(Constants.ANEWARRAY, type); } } public void arraylength() { mv.visitInsn(Constants.ARRAYLENGTH); } public void load_this() { if (TypeUtils.isStatic(state.access)) { throw new IllegalStateException("no 'this' pointer within static method"); } mv.visitVarInsn(Constants.ALOAD, 0); } /** * Pushes all of the arguments of the current method onto the stack. */ public void load_args() { load_args(0, state.argumentTypes.length); } /** * Pushes the specified argument of the current method onto the stack. * @param index the zero-based index into the argument list */ public void load_arg(int index) { load_local(state.argumentTypes[index], state.localOffset + skipArgs(index)); } // zero-based (see load_this) public void load_args(int fromArg, int count) { int pos = state.localOffset + skipArgs(fromArg); for (int i = 0; i < count; i++) { Type t = state.argumentTypes[fromArg + i]; load_local(t, pos); pos += t.getSize(); } } private int skipArgs(int numArgs) { int amount = 0; for (int i = 0; i < numArgs; i++) { amount += state.argumentTypes[i].getSize(); } return amount; } private void load_local(Type t, int pos) { // TODO: make t == null ok? mv.visitVarInsn(t.getOpcode(Constants.ILOAD), pos); } private void store_local(Type t, int pos) { // TODO: make t == null ok? mv.visitVarInsn(t.getOpcode(Constants.ISTORE), pos); } public void iinc(Local local, int amount) { mv.visitIincInsn(local.getIndex(), amount); } public void store_local(Local local) { store_local(local.getType(), local.getIndex()); } public void load_local(Local local) { load_local(local.getType(), local.getIndex()); } public void return_value() { mv.visitInsn(state.sig.getReturnType().getOpcode(Constants.IRETURN)); } public void getfield(String name) { ClassEmitter.FieldInfo info = ce.getFieldInfo(name); int opcode = TypeUtils.isStatic(info.access) ? Constants.GETSTATIC : Constants.GETFIELD; emit_field(opcode, ce.getClassType(), name, info.type); } public void putfield(String name) { ClassEmitter.FieldInfo info = ce.getFieldInfo(name); int opcode = TypeUtils.isStatic(info.access) ? Constants.PUTSTATIC : Constants.PUTFIELD; emit_field(opcode, ce.getClassType(), name, info.type); } public void super_getfield(String name, Type type) { emit_field(Constants.GETFIELD, ce.getSuperType(), name, type); } public void super_putfield(String name, Type type) { emit_field(Constants.PUTFIELD, ce.getSuperType(), name, type); } public void super_getstatic(String name, Type type) { emit_field(Constants.GETSTATIC, ce.getSuperType(), name, type); } public void super_putstatic(String name, Type type) { emit_field(Constants.PUTSTATIC, ce.getSuperType(), name, type); } public void getfield(Type owner, String name, Type type) { emit_field(Constants.GETFIELD, owner, name, type); } public void putfield(Type owner, String name, Type type) { emit_field(Constants.PUTFIELD, owner, name, type); } public void getstatic(Type owner, String name, Type type) { emit_field(Constants.GETSTATIC, owner, name, type); } public void putstatic(Type owner, String name, Type type) { emit_field(Constants.PUTSTATIC, owner, name, type); } // package-protected for EmitUtils, try to fix void emit_field(int opcode, Type ctype, String name, Type ftype) { mv.visitFieldInsn(opcode, ctype.getInternalName(), name, ftype.getDescriptor()); } public void super_invoke() { super_invoke(state.sig); } public void super_invoke(Signature sig) { emit_invoke(Constants.INVOKESPECIAL, ce.getSuperType(), sig); } public void invoke_constructor(Type type) { invoke_constructor(type, CSTRUCT_NULL); } public void super_invoke_constructor() { invoke_constructor(ce.getSuperType()); } public void invoke_constructor_this() { invoke_constructor(ce.getClassType()); } private void emit_invoke(int opcode, Type type, Signature sig) { if (sig.getName().equals(Constants.CONSTRUCTOR_NAME) && ((opcode == Constants.INVOKEVIRTUAL) || (opcode == Constants.INVOKESTATIC))) { // TODO: error } mv.visitMethodInsn(opcode, type.getInternalName(), sig.getName(), sig.getDescriptor()); } public void invoke_interface(Type owner, Signature sig) { emit_invoke(Constants.INVOKEINTERFACE, owner, sig); } public void invoke_virtual(Type owner, Signature sig) { emit_invoke(Constants.INVOKEVIRTUAL, owner, sig); } public void invoke_static(Type owner, Signature sig) { emit_invoke(Constants.INVOKESTATIC, owner, sig); } public void invoke_virtual_this(Signature sig) { invoke_virtual(ce.getClassType(), sig); } public void invoke_static_this(Signature sig) { invoke_static(ce.getClassType(), sig); } public void invoke_constructor(Type type, Signature sig) { emit_invoke(Constants.INVOKESPECIAL, type, sig); } public void invoke_constructor_this(Signature sig) { invoke_constructor(ce.getClassType(), sig); } public void super_invoke_constructor(Signature sig) { invoke_constructor(ce.getSuperType(), sig); } public void new_instance_this() { new_instance(ce.getClassType()); } public void new_instance(Type type) { emit_type(Constants.NEW, type); } private void emit_type(int opcode, Type type) { String desc; if (TypeUtils.isArray(type)) { desc = type.getDescriptor(); } else { desc = type.getInternalName(); } mv.visitTypeInsn(opcode, desc); } public void aaload(int index) { push(index); aaload(); } public void aaload() { mv.visitInsn(Constants.AALOAD); } public void aastore() { mv.visitInsn(Constants.AASTORE); } public void athrow() { mv.visitInsn(Constants.ATHROW); } public Label make_label() { return new Label(); } public Local make_local() { return make_local(Constants.TYPE_OBJECT); } public Local make_local(Type type) { return new Local(newLocal(type.getSize()), type); } public void checkcast_this() { checkcast(ce.getClassType()); } public void checkcast(Type type) { if (!type.equals(Constants.TYPE_OBJECT)) { emit_type(Constants.CHECKCAST, type); } } public void instance_of(Type type) { emit_type(Constants.INSTANCEOF, type); } public void instance_of_this() { instance_of(ce.getClassType()); } public void process_switch(int[] keys, ProcessSwitchCallback callback) { float density; if (keys.length == 0) { density = 0; } else { density = (float)keys.length / (keys[keys.length - 1] - keys[0] + 1); } process_switch(keys, callback, density >= 0.5f); } public void process_switch(int[] keys, ProcessSwitchCallback callback, boolean useTable) { if (!isSorted(keys)) throw new IllegalArgumentException("keys to switch must be sorted ascending"); Label def = make_label(); Label end = make_label(); try { if (keys.length > 0) { int len = keys.length; int min = keys[0]; int max = keys[len - 1]; int range = max - min + 1; if (useTable) { Label[] labels = new Label[range]; Arrays.fill(labels, def); for (int i = 0; i < len; i++) { labels[keys[i] - min] = make_label(); } mv.visitTableSwitchInsn(min, max, def, labels); for (int i = 0; i < range; i++) { Label label = labels[i]; if (label != def) { mark(label); callback.processCase(i + min, end); } } } else { Label[] labels = new Label[len]; for (int i = 0; i < len; i++) { labels[i] = make_label(); } mv.visitLookupSwitchInsn(def, keys, labels); for (int i = 0; i < len; i++) { mark(labels[i]); callback.processCase(keys[i], end); } } } mark(def); callback.processDefault(); mark(end); } catch (RuntimeException e) { throw e; } catch (Error e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } private static boolean isSorted(int[] keys) { for (int i = 1; i < keys.length; i++) { if (keys[i] < keys[i - 1]) return false; } return true; } public void mark(Label label) { mv.visitLabel(label); } Label mark() { Label label = make_label(); mv.visitLabel(label); return label; } public void push(boolean value) { push(value ? 1 : 0); } /** * Toggles the integer on the top of the stack from 1 to 0 or vice versa */ public void not() { push(1); math(XOR, Type.INT_TYPE); } public void throw_exception(Type type, String msg) { new_instance(type); dup(); push(msg); invoke_constructor(type, CSTRUCT_STRING); athrow(); } /** * If the argument is a primitive class, replaces the primitive value * on the top of the stack with the wrapped (Object) equivalent. For * example, char -> Character. * If the class is Void, a null is pushed onto the stack instead. * @param type the class indicating the current type of the top stack value */ public void box(Type type) { if (TypeUtils.isPrimitive(type)) { if (type == Type.VOID_TYPE) { aconst_null(); } else { Type boxed = TypeUtils.getBoxedType(type); new_instance(boxed); if (type.getSize() == 2) { // Pp -> Ppo -> oPpo -> ooPpo -> ooPp -> o dup_x2(); dup_x2(); pop(); } else { // p -> po -> opo -> oop -> o dup_x1(); swap(); } invoke_constructor(boxed, new Signature(Constants.CONSTRUCTOR_NAME, Type.VOID_TYPE, new Type[]{ type })); } } } /** * If the argument is a primitive class, replaces the object * on the top of the stack with the unwrapped (primitive) * equivalent. For example, Character -> char. * @param type the class indicating the desired type of the top stack value * @return true if the value was unboxed */ public void unbox(Type type) { Type t = Constants.TYPE_NUMBER; Signature sig = null; switch (type.getSort()) { case Type.VOID: return; case Type.CHAR: t = Constants.TYPE_CHARACTER; sig = CHAR_VALUE; break; case Type.BOOLEAN: t = Constants.TYPE_BOOLEAN; sig = BOOLEAN_VALUE; break; case Type.DOUBLE: sig = DOUBLE_VALUE; break; case Type.FLOAT: sig = FLOAT_VALUE; break; case Type.LONG: sig = LONG_VALUE; break; case Type.INT: case Type.SHORT: case Type.BYTE: sig = INT_VALUE; } if (sig == null) { checkcast(type); } else { checkcast(t); invoke_virtual(t, sig); } } /** * Allocates and fills an Object[] array with the arguments to the * current method. Primitive values are inserted as their boxed * (Object) equivalents. */ public void create_arg_array() { /* generates: Object[] args = new Object[]{ arg1, new Integer(arg2) }; */ push(state.argumentTypes.length); newarray(); for (int i = 0; i < state.argumentTypes.length; i++) { dup(); push(i); load_arg(i); box(state.argumentTypes[i]); aastore(); } } /** * Pushes a zero onto the stack if the argument is a primitive class, or a null otherwise. */ public void zero_or_null(Type type) { if (TypeUtils.isPrimitive(type)) { switch (type.getSort()) { case Type.DOUBLE: push(0d); break; case Type.LONG: push(0L); break; case Type.FLOAT: push(0f); break; case Type.VOID: aconst_null(); default: push(0); } } else { aconst_null(); } } /** * Unboxes the object on the top of the stack. If the object is null, the * unboxed primitive value becomes zero. */ public void unbox_or_zero(Type type) { if (TypeUtils.isPrimitive(type)) { if (type != Type.VOID_TYPE) { Label nonNull = make_label(); Label end = make_label(); dup(); ifnonnull(nonNull); pop(); zero_or_null(type); goTo(end); mark(nonNull); unbox(type); mark(end); } } else { checkcast(type); } } public void visitMaxs(int maxStack, int maxLocals) { if (!TypeUtils.isAbstract(state.access)) { mv.visitMaxs(0, 0); } } public void invoke(MethodInfo method, Type virtualType) { ClassInfo classInfo = method.getClassInfo(); Type type = classInfo.getType(); Signature sig = method.getSignature(); if (sig.getName().equals(Constants.CONSTRUCTOR_NAME)) { invoke_constructor(type, sig); } else if (TypeUtils.isInterface(classInfo.getModifiers())) { invoke_interface(type, sig); } else if (TypeUtils.isStatic(method.getModifiers())) { invoke_static(type, sig); } else { invoke_virtual(virtualType, sig); } } public void invoke(MethodInfo method) { invoke(method, method.getClassInfo().getType()); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ClassEmitter.java0000644000175000017500000002271512250620376023417 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import net.sf.cglib.transform.ClassTransformer; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.Type; import java.util.HashMap; import java.util.Map; /** * @author Juozas Baliuka, Chris Nokleberg */ public class ClassEmitter extends ClassTransformer { private ClassInfo classInfo; private Map fieldInfo; private static int hookCounter; private MethodVisitor rawStaticInit; private CodeEmitter staticInit; private CodeEmitter staticHook; private Signature staticHookSig; public ClassEmitter(ClassVisitor cv) { setTarget(cv); } public ClassEmitter() { super(Opcodes.ASM4); } public void setTarget(ClassVisitor cv) { this.cv = cv; fieldInfo = new HashMap(); // just to be safe staticInit = staticHook = null; staticHookSig = null; } synchronized private static int getNextHook() { return ++hookCounter; } public ClassInfo getClassInfo() { return classInfo; } public void begin_class(int version, final int access, String className, final Type superType, final Type[] interfaces, String source) { final Type classType = Type.getType("L" + className.replace('.', '/') + ";"); classInfo = new ClassInfo() { public Type getType() { return classType; } public Type getSuperType() { return (superType != null) ? superType : Constants.TYPE_OBJECT; } public Type[] getInterfaces() { return interfaces; } public int getModifiers() { return access; } }; cv.visit(version, access, classInfo.getType().getInternalName(), null, classInfo.getSuperType().getInternalName(), TypeUtils.toInternalNames(interfaces)); if (source != null) cv.visitSource(source, null); init(); } public CodeEmitter getStaticHook() { if (TypeUtils.isInterface(getAccess())) { throw new IllegalStateException("static hook is invalid for this class"); } if (staticHook == null) { staticHookSig = new Signature("CGLIB$STATICHOOK" + getNextHook(), "()V"); staticHook = begin_method(Constants.ACC_STATIC, staticHookSig, null); if (staticInit != null) { staticInit.invoke_static_this(staticHookSig); } } return staticHook; } protected void init() { } public int getAccess() { return classInfo.getModifiers(); } public Type getClassType() { return classInfo.getType(); } public Type getSuperType() { return classInfo.getSuperType(); } public void end_class() { if (staticHook != null && staticInit == null) { // force creation of static init begin_static(); } if (staticInit != null) { staticHook.return_value(); staticHook.end_method(); rawStaticInit.visitInsn(Constants.RETURN); rawStaticInit.visitMaxs(0, 0); staticInit = staticHook = null; staticHookSig = null; } cv.visitEnd(); } public CodeEmitter begin_method(int access, Signature sig, Type[] exceptions) { if (classInfo == null) throw new IllegalStateException("classInfo is null! " + this); MethodVisitor v = cv.visitMethod(access, sig.getName(), sig.getDescriptor(), null, TypeUtils.toInternalNames(exceptions)); if (sig.equals(Constants.SIG_STATIC) && !TypeUtils.isInterface(getAccess())) { rawStaticInit = v; MethodVisitor wrapped = new MethodVisitor(Opcodes.ASM4, v) { public void visitMaxs(int maxStack, int maxLocals) { // ignore } public void visitInsn(int insn) { if (insn != Constants.RETURN) { super.visitInsn(insn); } } }; staticInit = new CodeEmitter(this, wrapped, access, sig, exceptions); if (staticHook == null) { // force static hook creation getStaticHook(); } else { staticInit.invoke_static_this(staticHookSig); } return staticInit; } else if (sig.equals(staticHookSig)) { return new CodeEmitter(this, v, access, sig, exceptions) { public boolean isStaticHook() { return true; } }; } else { return new CodeEmitter(this, v, access, sig, exceptions); } } public CodeEmitter begin_static() { return begin_method(Constants.ACC_STATIC, Constants.SIG_STATIC, null); } public void declare_field(int access, String name, Type type, Object value) { FieldInfo existing = (FieldInfo)fieldInfo.get(name); FieldInfo info = new FieldInfo(access, name, type, value); if (existing != null) { if (!info.equals(existing)) { throw new IllegalArgumentException("Field \"" + name + "\" has been declared differently"); } } else { fieldInfo.put(name, info); cv.visitField(access, name, type.getDescriptor(), null, value); } } // TODO: make public? boolean isFieldDeclared(String name) { return fieldInfo.get(name) != null; } FieldInfo getFieldInfo(String name) { FieldInfo field = (FieldInfo)fieldInfo.get(name); if (field == null) { throw new IllegalArgumentException("Field " + name + " is not declared in " + getClassType().getClassName()); } return field; } static class FieldInfo { int access; String name; Type type; Object value; public FieldInfo(int access, String name, Type type, Object value) { this.access = access; this.name = name; this.type = type; this.value = value; } public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof FieldInfo)) return false; FieldInfo other = (FieldInfo)o; if (access != other.access || !name.equals(other.name) || !type.equals(other.type)) { return false; } if ((value == null) ^ (other.value == null)) return false; if (value != null && !value.equals(other.value)) return false; return true; } public int hashCode() { return access ^ name.hashCode() ^ type.hashCode() ^ ((value == null) ? 0 : value.hashCode()); } } public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { begin_class(version, access, name.replace('/', '.'), TypeUtils.fromInternalName(superName), TypeUtils.fromInternalNames(interfaces), null); // TODO } public void visitEnd() { end_class(); } public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { declare_field(access, name, Type.getType(desc), value); return null; // TODO } public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) { return begin_method(access, new Signature(name, desc), TypeUtils.fromInternalNames(exceptions)); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/KeyFactory.java0000644000175000017500000002417710402432050023067 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.Method; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.Type; /** * Generates classes to handle multi-valued keys, for use in things such as Maps and Sets. * Code for equals and hashCode methods follow the * the rules laid out in Effective Java by Joshua Bloch. *

* To generate a KeyFactory, you need to supply an interface which * describes the structure of the key. The interface should have a * single method named newInstance, which returns an * Object. The arguments array can be * anything--Objects, primitive values, or single or * multi-dimension arrays of either. For example: *

 *     private interface IntStringKey {
 *         public Object newInstance(int i, String s);
 *     }
 * 

* Once you have made a KeyFactory, you generate a new key by calling * the newInstance method defined by your interface. *

 *     IntStringKey factory = (IntStringKey)KeyFactory.create(IntStringKey.class);
 *     Object key1 = factory.newInstance(4, "Hello");
 *     Object key2 = factory.newInstance(4, "World");
 * 

* Note: * hashCode equality between two keys key1 and key2 is only guaranteed if * key1.equals(key2) and the keys were produced by the same factory. * * @version $Id: KeyFactory.java,v 1.26 2006/03/05 02:43:19 herbyderby Exp $ */ abstract public class KeyFactory { private static final Signature GET_NAME = TypeUtils.parseSignature("String getName()"); private static final Signature GET_CLASS = TypeUtils.parseSignature("Class getClass()"); private static final Signature HASH_CODE = TypeUtils.parseSignature("int hashCode()"); private static final Signature EQUALS = TypeUtils.parseSignature("boolean equals(Object)"); private static final Signature TO_STRING = TypeUtils.parseSignature("String toString()"); private static final Signature APPEND_STRING = TypeUtils.parseSignature("StringBuffer append(String)"); private static final Type KEY_FACTORY = TypeUtils.parseType("net.sf.cglib.core.KeyFactory"); //generated numbers: private final static int PRIMES[] = { 11, 73, 179, 331, 521, 787, 1213, 1823, 2609, 3691, 5189, 7247, 10037, 13931, 19289, 26627, 36683, 50441, 69403, 95401, 131129, 180179, 247501, 340057, 467063, 641371, 880603, 1209107, 1660097, 2279161, 3129011, 4295723, 5897291, 8095873, 11114263, 15257791, 20946017, 28754629, 39474179, 54189869, 74391461, 102123817, 140194277, 192456917, 264202273, 362693231, 497900099, 683510293, 938313161, 1288102441, 1768288259 }; public static final Customizer CLASS_BY_NAME = new Customizer() { public void customize(CodeEmitter e, Type type) { if (type.equals(Constants.TYPE_CLASS)) { e.invoke_virtual(Constants.TYPE_CLASS, GET_NAME); } } }; public static final Customizer OBJECT_BY_CLASS = new Customizer() { public void customize(CodeEmitter e, Type type) { e.invoke_virtual(Constants.TYPE_OBJECT, GET_CLASS); } }; protected KeyFactory() { } public static KeyFactory create(Class keyInterface) { return create(keyInterface, null); } public static KeyFactory create(Class keyInterface, Customizer customizer) { return create(keyInterface.getClassLoader(), keyInterface, customizer); } public static KeyFactory create(ClassLoader loader, Class keyInterface, Customizer customizer) { Generator gen = new Generator(); gen.setInterface(keyInterface); gen.setCustomizer(customizer); gen.setClassLoader(loader); return gen.create(); } public static class Generator extends AbstractClassGenerator { private static final Source SOURCE = new Source(KeyFactory.class.getName()); private Class keyInterface; private Customizer customizer; private int constant; private int multiplier; public Generator() { super(SOURCE); } protected ClassLoader getDefaultClassLoader() { return keyInterface.getClassLoader(); } public void setCustomizer(Customizer customizer) { this.customizer = customizer; } public void setInterface(Class keyInterface) { this.keyInterface = keyInterface; } public KeyFactory create() { setNamePrefix(keyInterface.getName()); return (KeyFactory)super.create(keyInterface.getName()); } public void setHashConstant(int constant) { this.constant = constant; } public void setHashMultiplier(int multiplier) { this.multiplier = multiplier; } protected Object firstInstance(Class type) { return ReflectUtils.newInstance(type); } protected Object nextInstance(Object instance) { return instance; } public void generateClass(ClassVisitor v) { ClassEmitter ce = new ClassEmitter(v); Method newInstance = ReflectUtils.findNewInstance(keyInterface); if (!newInstance.getReturnType().equals(Object.class)) { throw new IllegalArgumentException("newInstance method must return Object"); } Type[] parameterTypes = TypeUtils.getTypes(newInstance.getParameterTypes()); ce.begin_class(Constants.V1_2, Constants.ACC_PUBLIC, getClassName(), KEY_FACTORY, new Type[]{ Type.getType(keyInterface) }, Constants.SOURCE_FILE); EmitUtils.null_constructor(ce); EmitUtils.factory_method(ce, ReflectUtils.getSignature(newInstance)); int seed = 0; CodeEmitter e = ce.begin_method(Constants.ACC_PUBLIC, TypeUtils.parseConstructor(parameterTypes), null); e.load_this(); e.super_invoke_constructor(); e.load_this(); for (int i = 0; i < parameterTypes.length; i++) { seed += parameterTypes[i].hashCode(); ce.declare_field(Constants.ACC_PRIVATE | Constants.ACC_FINAL, getFieldName(i), parameterTypes[i], null); e.dup(); e.load_arg(i); e.putfield(getFieldName(i)); } e.return_value(); e.end_method(); // hash code e = ce.begin_method(Constants.ACC_PUBLIC, HASH_CODE, null); int hc = (constant != 0) ? constant : PRIMES[(int)(Math.abs(seed) % PRIMES.length)]; int hm = (multiplier != 0) ? multiplier : PRIMES[(int)(Math.abs(seed * 13) % PRIMES.length)]; e.push(hc); for (int i = 0; i < parameterTypes.length; i++) { e.load_this(); e.getfield(getFieldName(i)); EmitUtils.hash_code(e, parameterTypes[i], hm, customizer); } e.return_value(); e.end_method(); // equals e = ce.begin_method(Constants.ACC_PUBLIC, EQUALS, null); Label fail = e.make_label(); e.load_arg(0); e.instance_of_this(); e.if_jump(e.EQ, fail); for (int i = 0; i < parameterTypes.length; i++) { e.load_this(); e.getfield(getFieldName(i)); e.load_arg(0); e.checkcast_this(); e.getfield(getFieldName(i)); EmitUtils.not_equals(e, parameterTypes[i], fail, customizer); } e.push(1); e.return_value(); e.mark(fail); e.push(0); e.return_value(); e.end_method(); // toString e = ce.begin_method(Constants.ACC_PUBLIC, TO_STRING, null); e.new_instance(Constants.TYPE_STRING_BUFFER); e.dup(); e.invoke_constructor(Constants.TYPE_STRING_BUFFER); for (int i = 0; i < parameterTypes.length; i++) { if (i > 0) { e.push(", "); e.invoke_virtual(Constants.TYPE_STRING_BUFFER, APPEND_STRING); } e.load_this(); e.getfield(getFieldName(i)); EmitUtils.append_string(e, parameterTypes[i], EmitUtils.DEFAULT_DELIMITERS, customizer); } e.invoke_virtual(Constants.TYPE_STRING_BUFFER, TO_STRING); e.return_value(); e.end_method(); ce.end_class(); } private String getFieldName(int arg) { return "FIELD_" + arg; } } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ProcessSwitchCallback.java0000644000175000017500000000151710066633132025227 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Label; public interface ProcessSwitchCallback { void processCase(int key, Label end) throws Exception; void processDefault() throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/DefaultNamingPolicy.java0000644000175000017500000000457011132421266024710 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.util.Set; /** * The default policy used by {@link AbstractClassGenerator}. * Generates names such as *

net.sf.cglib.Foo$$EnhancerByCGLIB$$38272841

* This is composed of a prefix based on the name of the superclass, a fixed * string incorporating the CGLIB class responsible for generation, and a * hashcode derived from the parameters used to create the object. If the same * name has been previously been used in the same ClassLoader, a * suffix is added to ensure uniqueness. */ public class DefaultNamingPolicy implements NamingPolicy { public static final DefaultNamingPolicy INSTANCE = new DefaultNamingPolicy(); public String getClassName(String prefix, String source, Object key, Predicate names) { if (prefix == null) { prefix = "net.sf.cglib.empty.Object"; } else if (prefix.startsWith("java")) { prefix = "$" + prefix; } String base = prefix + "$$" + source.substring(source.lastIndexOf('.') + 1) + getTag() + "$$" + Integer.toHexString(key.hashCode()); String attempt = base; int index = 2; while (names.evaluate(attempt)) attempt = base + "_" + index++; return attempt; } /** * Returns a string which is incorporated into every generated class name. * By default returns "ByCGLIB" */ protected String getTag() { return "ByCGLIB"; } public int hashCode() { return getTag().hashCode(); } public boolean equals(Object o) { return (o instanceof DefaultNamingPolicy) && ((DefaultNamingPolicy) o).getTag().equals(getTag()); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ObjectSwitchCallback.java0000644000175000017500000000152310066633132025014 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Label; public interface ObjectSwitchCallback { void processCase(Object key, Label end) throws Exception; void processDefault() throws Exception; } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/ClassesKey.java0000644000175000017500000000176710066633132023067 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; public class ClassesKey { private static final Key FACTORY = (Key)KeyFactory.create(Key.class, KeyFactory.OBJECT_BY_CLASS); interface Key { Object newInstance(Object[] array); } private ClassesKey() { } public static Object create(Object[] array) { return FACTORY.newInstance(array); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/RejectModifierPredicate.java0000644000175000017500000000175610066633132025533 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.*; public class RejectModifierPredicate implements Predicate { private int rejectMask; public RejectModifierPredicate(int rejectMask) { this.rejectMask = rejectMask; } public boolean evaluate(Object arg) { return (((Member)arg).getModifiers() & rejectMask) == 0; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Customizer.java0000644000175000017500000000141110066633132023147 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Type; public interface Customizer { void customize(CodeEmitter e, Type type); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/MethodInfo.java0000644000175000017500000000265410402432050023037 0ustar miguelmiguel/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Attribute; import org.objectweb.asm.Type; abstract public class MethodInfo { protected MethodInfo() { } abstract public ClassInfo getClassInfo(); abstract public int getModifiers(); abstract public Signature getSignature(); abstract public Type[] getExceptionTypes(); public boolean equals(Object o) { if (o == null) return false; if (!(o instanceof MethodInfo)) return false; return getSignature().equals(((MethodInfo)o).getSignature()); } public int hashCode() { return getSignature().hashCode(); } public String toString() { // TODO: include modifiers, exceptions return getSignature().toString(); } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/MethodWrapper.java0000644000175000017500000000320310251072654023567 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.lang.reflect.Method; import java.util.*; public class MethodWrapper { private static final MethodWrapperKey KEY_FACTORY = (MethodWrapperKey)KeyFactory.create(MethodWrapperKey.class); /** Internal interface, only public due to ClassLoader issues. */ public interface MethodWrapperKey { public Object newInstance(String name, String[] parameterTypes, String returnType); } private MethodWrapper() { } public static Object create(Method method) { return KEY_FACTORY.newInstance(method.getName(), ReflectUtils.getNames(method.getParameterTypes()), method.getReturnType().getName()); } public static Set createSet(Collection methods) { Set set = new HashSet(); for (Iterator it = methods.iterator(); it.hasNext();) { set.add(create((Method)it.next())); } return set; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Predicate.java0000644000175000017500000000133410066633132022707 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; public interface Predicate { boolean evaluate(Object arg); } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/CodeGenerationException.java0000644000175000017500000000210510066633132025551 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; /** * @version $Id: CodeGenerationException.java,v 1.3 2004/06/24 21:15:21 herbyderby Exp $ */ public class CodeGenerationException extends RuntimeException { private Throwable cause; public CodeGenerationException(Throwable cause) { super(cause.getClass().getName() + "-->" + cause.getMessage()); this.cause = cause; } public Throwable getCause() { return cause; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/CollectionUtils.java0000644000175000017500000000462410066633132024130 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.util.*; import java.lang.reflect.Array; /** * @author Chris Nokleberg * @version $Id: CollectionUtils.java,v 1.7 2004/06/24 21:15:21 herbyderby Exp $ */ public class CollectionUtils { private CollectionUtils() { } public static Map bucket(Collection c, Transformer t) { Map buckets = new HashMap(); for (Iterator it = c.iterator(); it.hasNext();) { Object value = (Object)it.next(); Object key = t.transform(value); List bucket = (List)buckets.get(key); if (bucket == null) { buckets.put(key, bucket = new LinkedList()); } bucket.add(value); } return buckets; } public static void reverse(Map source, Map target) { for (Iterator it = source.keySet().iterator(); it.hasNext();) { Object key = it.next(); target.put(source.get(key), key); } } public static Collection filter(Collection c, Predicate p) { Iterator it = c.iterator(); while (it.hasNext()) { if (!p.evaluate(it.next())) { it.remove(); } } return c; } public static List transform(Collection c, Transformer t) { List result = new ArrayList(c.size()); for (Iterator it = c.iterator(); it.hasNext();) { result.add(t.transform(it.next())); } return result; } public static Map getIndexMap(List list) { Map indexes = new HashMap(); int index = 0; for (Iterator it = list.iterator(); it.hasNext();) { indexes.put(it.next(), new Integer(index++)); } return indexes; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/Block.java0000644000175000017500000000235610066633132022046 0ustar miguelmiguel/* * Copyright 2003 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import org.objectweb.asm.Label; public class Block { private CodeEmitter e; private Label start; private Label end; public Block(CodeEmitter e) { this.e = e; start = e.mark(); } public CodeEmitter getCodeEmitter() { return e; } public void end() { if (end != null) { throw new IllegalStateException("end of label already set"); } end = e.mark(); } public Label getStart() { return start; } public Label getEnd() { return end; } } cglib3-3.1+dfsg/src/proxy/net/sf/cglib/core/TypeUtils.java0000644000175000017500000003202712250620376022757 0ustar miguelmiguel/* * Copyright 2003,2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sf.cglib.core; import java.util.*; import org.objectweb.asm.Type; public class TypeUtils { private static final Map transforms = new HashMap(); private static final Map rtransforms = new HashMap(); private TypeUtils() { } static { transforms.put("void", "V"); transforms.put("byte", "B"); transforms.put("char", "C"); transforms.put("double", "D"); transforms.put("float", "F"); transforms.put("int", "I"); transforms.put("long", "J"); transforms.put("short", "S"); transforms.put("boolean", "Z"); CollectionUtils.reverse(transforms, rtransforms); } public static Type getType(String className) { return Type.getType("L" + className.replace('.', '/') + ";"); } public static boolean isFinal(int access) { return (Constants.ACC_FINAL & access) != 0; } public static boolean isStatic(int access) { return (Constants.ACC_STATIC & access) != 0; } public static boolean isProtected(int access) { return (Constants.ACC_PROTECTED & access) != 0; } public static boolean isPublic(int access) { return (Constants.ACC_PUBLIC & access) != 0; } public static boolean isAbstract(int access) { return (Constants.ACC_ABSTRACT & access) != 0; } public static boolean isInterface(int access) { return (Constants.ACC_INTERFACE & access) != 0; } public static boolean isPrivate(int access) { return (Constants.ACC_PRIVATE & access) != 0; } public static boolean isSynthetic(int access) { return (Constants.ACC_SYNTHETIC & access) != 0; } public static boolean isBridge(int access) { return (Constants.ACC_BRIDGE & access) != 0; } // getPackage returns null on JDK 1.2 public static String getPackageName(Type type) { return getPackageName(getClassName(type)); } public static String getPackageName(String className) { int idx = className.lastIndexOf('.'); return (idx < 0) ? "" : className.substring(0, idx); } public static String upperFirst(String s) { if (s == null || s.length() == 0) { return s; } return Character.toUpperCase(s.charAt(0)) + s.substring(1); } public static String getClassName(Type type) { if (isPrimitive(type)) { return (String)rtransforms.get(type.getDescriptor()); } else if (isArray(type)) { return getClassName(getComponentType(type)) + "[]"; } else { return type.getClassName(); } } public static Type[] add(Type[] types, Type extra) { if (types == null) { return new Type[]{ extra }; } else { List list = Arrays.asList(types); if (list.contains(extra)) { return types; } Type[] copy = new Type[types.length + 1]; System.arraycopy(types, 0, copy, 0, types.length); copy[types.length] = extra; return copy; } } public static Type[] add(Type[] t1, Type[] t2) { // TODO: set semantics? Type[] all = new Type[t1.length + t2.length]; System.arraycopy(t1, 0, all, 0, t1.length); System.arraycopy(t2, 0, all, t1.length, t2.length); return all; } public static Type fromInternalName(String name) { // TODO; primitives? return Type.getType("L" + name + ";"); } public static Type[] fromInternalNames(String[] names) { if (names == null) { return null; } Type[] types = new Type[names.length]; for (int i = 0; i < names.length; i++) { types[i] = fromInternalName(names[i]); } return types; } public static int getStackSize(Type[] types) { int size = 0; for (int i = 0; i < types.length; i++) { size += types[i].getSize(); } return size; } public static String[] toInternalNames(Type[] types) { if (types == null) { return null; } String[] names = new String[types.length]; for (int i = 0; i < types.length; i++) { names[i] = types[i].getInternalName(); } return names; } public static Signature parseSignature(String s) { int space = s.indexOf(' '); int lparen = s.indexOf('(', space); int rparen = s.indexOf(')', lparen); String returnType = s.substring(0, space); String methodName = s.substring(space + 1, lparen); StringBuffer sb = new StringBuffer(); sb.append('('); for (Iterator it = parseTypes(s, lparen + 1, rparen).iterator(); it.hasNext();) { sb.append(it.next()); } sb.append(')'); sb.append(map(returnType)); return new Signature(methodName, sb.toString()); } public static Type parseType(String s) { return Type.getType(map(s)); } public static Type[] parseTypes(String s) { List names = parseTypes(s, 0, s.length()); Type[] types = new Type[names.size()]; for (int i = 0; i < types.length; i++) { types[i] = Type.getType((String)names.get(i)); } return types; } public static Signature parseConstructor(Type[] types) { StringBuffer sb = new StringBuffer(); sb.append("("); for (int i = 0; i < types.length; i++) { sb.append(types[i].getDescriptor()); } sb.append(")"); sb.append("V"); return new Signature(Constants.CONSTRUCTOR_NAME, sb.toString()); } public static Signature parseConstructor(String sig) { return parseSignature("void (" + sig + ")"); // TODO } private static List parseTypes(String s, int mark, int end) { List types = new ArrayList(5); for (;;) { int next = s.indexOf(',', mark); if (next < 0) { break; } types.add(map(s.substring(mark, next).trim())); mark = next + 1; } types.add(map(s.substring(mark, end).trim())); return types; } private static String map(String type) { if (type.equals("")) { return type; } String t = (String)transforms.get(type); if (t != null) { return t; } else if (type.indexOf('.') < 0) { return map("java.lang." + type); } else { StringBuffer sb = new StringBuffer(); int index = 0; while ((index = type.indexOf("[]", index) + 1) > 0) { sb.append('['); } type = type.substring(0, type.length() - sb.length() * 2); sb.append('L').append(type.replace('.', '/')).append(';'); return sb.toString(); } } public static Type getBoxedType(Type type) { switch (type.getSort()) { case Type.CHAR: return Constants.TYPE_CHARACTER; case Type.BOOLEAN: return Constants.TYPE_BOOLEAN; case Type.DOUBLE: return Constants.TYPE_DOUBLE; case Type.FLOAT: return Constants.TYPE_FLOAT; case Type.LONG: return Constants.TYPE_LONG; case Type.INT: return Constants.TYPE_INTEGER; case Type.SHORT: return Constants.TYPE_SHORT; case Type.BYTE: return Constants.TYPE_BYTE; default: return type; } } public static Type getUnboxedType(Type type) { if (Constants.TYPE_INTEGER.equals(type)) { return Type.INT_TYPE; } else if (Constants.TYPE_BOOLEAN.equals(type)) { return Type.BOOLEAN_TYPE; } else if (Constants.TYPE_DOUBLE.equals(type)) { return Type.DOUBLE_TYPE; } else if (Constants.TYPE_LONG.equals(type)) { return Type.LONG_TYPE; } else if (Constants.TYPE_CHARACTER.equals(type)) { return Type.CHAR_TYPE; } else if (Constants.TYPE_BYTE.equals(type)) { return Type.BYTE_TYPE; } else if (Constants.TYPE_FLOAT.equals(type)) { return Type.FLOAT_TYPE; } else if (Constants.TYPE_SHORT.equals(type)) { return Type.SHORT_TYPE; } else { return type; } } public static boolean isArray(Type type) { return type.getSort() == Type.ARRAY; } public static Type getComponentType(Type type) { if (!isArray(type)) { throw new IllegalArgumentException("Type " + type + " is not an array"); } return Type.getType(type.getDescriptor().substring(1)); } public static boolean isPrimitive(Type type) { switch (type.getSort()) { case Type.ARRAY: case Type.OBJECT: return false; default: return true; } } public static String emulateClassGetName(Type type) { if (isArray(type)) { return type.getDescriptor().replace('/', '.'); } else { return getClassName(type); } } public static boolean isConstructor(MethodInfo method) { return method.getSignature().getName().equals(Constants.CONSTRUCTOR_NAME); } public static Type[] getTypes(Class[] classes) { if (classes == null) { return null; } Type[] types = new Type[classes.length]; for (int i = 0; i < classes.length; i++) { types[i] = Type.getType(classes[i]); } return types; } public static int ICONST(int value) { switch (value) { case -1: return Constants.ICONST_M1; case 0: return Constants.ICONST_0; case 1: return Constants.ICONST_1; case 2: return Constants.ICONST_2; case 3: return Constants.ICONST_3; case 4: return Constants.ICONST_4; case 5: return Constants.ICONST_5; } return -1; // error } public static int LCONST(long value) { if (value == 0L) { return Constants.LCONST_0; } else if (value == 1L) { return Constants.LCONST_1; } else { return -1; // error } } public static int FCONST(float value) { if (value == 0f) { return Constants.FCONST_0; } else if (value == 1f) { return Constants.FCONST_1; } else if (value == 2f) { return Constants.FCONST_2; } else { return -1; // error } } public static int DCONST(double value) { if (value == 0d) { return Constants.DCONST_0; } else if (value == 1d) { return Constants.DCONST_1; } else { return -1; // error } } public static int NEWARRAY(Type type) { switch (type.getSort()) { case Type.BYTE: return Constants.T_BYTE; case Type.CHAR: return Constants.T_CHAR; case Type.DOUBLE: return Constants.T_DOUBLE; case Type.FLOAT: return Constants.T_FLOAT; case Type.INT: return Constants.T_INT; case Type.LONG: return Constants.T_LONG; case Type.SHORT: return Constants.T_SHORT; case Type.BOOLEAN: return Constants.T_BOOLEAN; default: return -1; // error } } public static String escapeType(String s) { StringBuffer sb = new StringBuffer(); for (int i = 0, len = s.length(); i < len; i++) { char c = s.charAt(i); switch (c) { case '$': sb.append("$24"); break; case '.': sb.append("$2E"); break; case '[': sb.append("$5B"); break; case ';': sb.append("$3B"); break; case '(': sb.append("$28"); break; case ')': sb.append("$29"); break; case '/': sb.append("$2F"); break; default: sb.append(c); } } return sb.toString(); } } cglib3-3.1+dfsg/lib/0000755000175000017500000000000012250627450013536 5ustar miguelmiguelcglib3-3.1+dfsg/LICENSE0000644000175000017500000002644610066633132014006 0ustar miguelmiguel Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. cglib3-3.1+dfsg/NOTICE0000644000175000017500000000014710066633132013673 0ustar miguelmiguelThis product includes software developed by The Apache Software Foundation (http://www.apache.org/). cglib3-3.1+dfsg/META-INF/0000755000175000017500000000000012250630166014126 5ustar miguelmiguelcglib3-3.1+dfsg/META-INF/MANIFEST.MF0000644000175000017500000000014612250630164015557 0ustar miguelmiguelManifest-Version: 1.0 Ant-Version: Apache Ant 1.7.1 Created-By: 19.0-b09 (Sun Microsystems Inc.) cglib3-3.1+dfsg/build.xml0000644000175000017500000002437412250625724014625 0ustar miguelmiguel