Debian Codegraph @

jmock-legacy/src/main/java/org/jmock/lib/legacy/ClassImposteriser.java

raw
1 package org.jmock.lib.legacy;
2
3 import net.sf.cglib.core.CodeGenerationException;
4 import net.sf.cglib.core.DefaultNamingPolicy;
5 import net.sf.cglib.core.NamingPolicy;
6 import net.sf.cglib.core.Predicate;
7 import net.sf.cglib.proxy.*;
8 import org.jmock.api.Imposteriser;
9 import org.jmock.api.Invocation;
10 import org.jmock.api.Invokable;
11 import org.jmock.internal.SearchingClassLoader;
12 import org.objenesis.Objenesis;
13 import org.objenesis.ObjenesisStd;
14
15 import java.lang.reflect.Constructor;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.Modifier;
18 import java.util.List;
19
20 /**
21 * This class lets you imposterise abstract and concrete classes
22 * <em>without</em> calling the constructors of the mocked class.
23 *
24 * @author npryce
25 *
26 * @deprecated Java11 support is weak, Migrate to org.jmock.lib.imposters.ByteBuddyClassImposteriser
27 */
28 public class ClassImposteriser implements Imposteriser {
29 public static final Imposteriser INSTANCE = new ClassImposteriser();
30
31 private ClassImposteriser() {}
32
33 private static final Method FINALIZE_METHOD = findFinalizeMethod();
34
35 private static final NamingPolicy NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES = new DefaultNamingPolicy() {
36 @Override
37 public String getClassName(String prefix, String source, Object key, Predicate names) {
38 return "org.jmock.codegen." + super.getClassName(prefix, source, key, names);
39 }
40 };
41
42 private static final CallbackFilter IGNORED_METHODS = new CallbackFilter() {
43 public int accept(Method method) {
44 if (method.isBridge())
45 return 1;
46 else if (method.equals(FINALIZE_METHOD))
47 return 1;
48 else
49 return 0;
50 }
51 };
52
53 private final Objenesis objenesis = new ObjenesisStd();
54
55 public boolean canImposterise(Class<?> type) {
56 return !type.isPrimitive() &&
57 !Modifier.isFinal(type.getModifiers()) &&
58 (type.isInterface() || !toStringMethodIsFinal(type));
59 }
60
61 @Override
62 public <T> T imposterise(final Invokable mockObject, Class<T> mockedType, Class<?>... ancilliaryTypes) {
63 if (!mockedType.isInterface() && toStringMethodIsFinal(mockedType)) {
64 throw new IllegalArgumentException(mockedType.getName() + " has a final toString method");
65 }
66
67 try {
68 setConstructorsAccessible(mockedType, true);
69 return mockedType.cast(proxy(proxyClass(mockedType, ancilliaryTypes), mockObject));
70 }
71 finally {
72 setConstructorsAccessible(mockedType, false);
73 }
74 }
75
76 private boolean toStringMethodIsFinal(Class<?> type) {
77 try {
78 Method toString = type.getMethod("toString");
79 return Modifier.isFinal(toString.getModifiers());
80
81 }
82 catch (SecurityException e) {
83 throw new IllegalStateException("not allowed to reflect on toString method", e);
84 }
85 catch (NoSuchMethodException e) {
86 throw new Error("no public toString method found", e);
87 }
88 }
89
90 private void setConstructorsAccessible(Class<?> mockedType, boolean accessible) {
91 for (Constructor<?> constructor : mockedType.getDeclaredConstructors()) {
92 constructor.setAccessible(accessible);
93 }
94 }
95
96 private Class<?> proxyClass(Class<?> possibleMockedType, Class<?>... ancilliaryTypes) {
97 final Class<?> mockedType =
98 possibleMockedType == Object.class ? ClassWithSuperclassToWorkAroundCglibBug.class : possibleMockedType;
99
100 final Enhancer enhancer = new Enhancer() {
101 @Override
102 @SuppressWarnings("unchecked")
103 protected void filterConstructors(Class sc, List constructors) {
104 // Don't filter
105 }
106 };
107 enhancer.setClassLoader(SearchingClassLoader.combineLoadersOf(mockedType, ancilliaryTypes));
108 enhancer.setUseFactory(true);
109 if (mockedType.isInterface()) {
110 enhancer.setSuperclass(Object.class);
111 enhancer.setInterfaces(prepend(mockedType, ancilliaryTypes));
112 }
113 else {
114 enhancer.setSuperclass(mockedType);
115 enhancer.setInterfaces(ancilliaryTypes);
116 }
117 enhancer.setCallbackTypes(new Class[]{InvocationHandler.class, NoOp.class});
118 enhancer.setCallbackFilter(IGNORED_METHODS);
119 if (protectedPackageNamespace(mockedType)) {
120 enhancer.setNamingPolicy(NAMING_POLICY_THAT_ALLOWS_IMPOSTERISATION_OF_CLASSES_IN_SIGNED_PACKAGES);
121 }
122
123 try {
124 return enhancer.createClass();
125 }
126 catch (CodeGenerationException e) {
127 // Note: I've only been able to manually test this. It exists to help people writing
128 // Eclipse plug-ins or using other environments that have sophisticated class loader
129 // structures.
130 throw new IllegalArgumentException("could not imposterise " + mockedType, e);
131 }
132 }
133
134 private Object proxy(Class<?> proxyClass, final Invokable mockObject) {
135 final Factory proxy = (Factory)objenesis.newInstance(proxyClass);
136 proxy.setCallbacks(new Callback[] {
137 new InvocationHandler() {
138 public Object invoke(Object receiver, Method method, Object[] args) throws Throwable {
139 return mockObject.invoke(new Invocation(receiver, method, args));
140 }
141 },
142 NoOp.INSTANCE
143 });
144 return proxy;
145 }
146
147 private Class<?>[] prepend(Class<?> first, Class<?>... rest) {
148 Class<?>[] all = new Class<?>[rest.length+1];
149 all[0] = first;
150 System.arraycopy(rest, 0, all, 1, rest.length);
151 return all;
152 }
153
154 private static Method findFinalizeMethod() {
155 try {
156 return Object.class.getDeclaredMethod("finalize");
157 } catch (NoSuchMethodException e) {
158 throw new IllegalStateException("Could not find finalize method on Object");
159 }
160 }
161
162 private boolean protectedPackageNamespace(Class<?> mockedType) {
163 return mockedType.getSigners() != null || mockedType.getName().startsWith("java.");
164 }
165
166
167 public static class ClassWithSuperclassToWorkAroundCglibBug {}
168 }