-
Notifications
You must be signed in to change notification settings - Fork 162
/
ClassLoaderAdapterCallback.java
443 lines (392 loc) · 15.1 KB
/
ClassLoaderAdapterCallback.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package org.jboss.forge.classloader;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import javassist.util.proxy.MethodFilter;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.ProxyFactory;
import javassist.util.proxy.ProxyObject;
import org.jboss.forge.container.exception.ContainerException;
import org.jboss.forge.container.util.Assert;
import org.jboss.forge.container.util.ClassLoaders;
public class ClassLoaderAdapterCallback implements MethodHandler
{
private static final ClassLoader JAVASSIST_LOADER = ProxyObject.class.getClassLoader();
private final ClassLoader fromLoader;
private final ClassLoader toLoader;
private final Object delegate;
public ClassLoaderAdapterCallback(ClassLoader fromLoader, ClassLoader toLoader, Object delegate)
{
this.fromLoader = fromLoader;
this.toLoader = toLoader;
this.delegate = delegate;
}
@Override
public Object invoke(final Object obj, final Method proxy, final Method method, final Object[] args)
throws Throwable
{
return ClassLoaders.executeIn(toLoader, new Callable<Object>()
{
@Override
public Object call() throws Exception
{
try
{
Method delegateMethod = getDelegateMethod(proxy);
List<Object> parameterValues = convertParameterValues(args, delegateMethod);
AccessibleObject.setAccessible(new AccessibleObject[] { delegateMethod }, true);
Object result = delegateMethod.invoke(delegate, parameterValues.toArray());
return enhanceResult(proxy, result);
}
catch (Throwable e)
{
throw new ContainerException(
"Could not invoke proxy method [" + delegate.getClass().getName() + "."
+ proxy.getName() + "()] in ClassLoader ["
+ toLoader + "]", e);
}
}
private Method getDelegateMethod(final Method proxy) throws ClassNotFoundException, NoSuchMethodException
{
Method delegateMethod = null;
try
{
List<Class<?>> parameterTypes = convertParameterTypes(proxy);
delegateMethod = delegate.getClass().getMethod(proxy.getName(),
parameterTypes.toArray(new Class<?>[parameterTypes.size()]));
}
catch (ClassNotFoundException e)
{
method: for (Method m : delegate.getClass().getMethods())
{
String methodName = proxy.getName();
String delegateMethodName = m.getName();
if (methodName.equals(delegateMethodName))
{
Class<?>[] methodParameterTypes = proxy.getParameterTypes();
Class<?>[] delegateParameterTypes = m.getParameterTypes();
if (methodParameterTypes.length == delegateParameterTypes.length)
{
for (int i = 0; i < methodParameterTypes.length; i++)
{
Class<?> methodType = methodParameterTypes[i];
Class<?> delegateType = delegateParameterTypes[i];
if (!methodType.getName().equals(delegateType.getName()))
{
continue method;
}
}
delegateMethod = m;
break;
}
}
}
if (delegateMethod == null)
throw e;
}
return delegateMethod;
}
});
}
private Object enhanceResult(final Method method, Object result)
{
if (result != null)
{
Class<?> returnType = method.getReturnType();
if (needsEnhancement(result))
{
if (!Modifier.isFinal(returnType.getModifiers()))
{
if (Object.class.equals(returnType) && !Object.class.equals(result))
{
result = enhance(fromLoader, toLoader, method, result,
ProxyTypeInspector.getCompatibleClassHierarchy(fromLoader,
ProxyTypeInspector.unwrapProxyTypes(result.getClass(), fromLoader, toLoader)));
}
else
{
result = enhance(fromLoader, toLoader, method, result, returnType);
}
}
else
{
result = enhance(fromLoader, toLoader, method,
ProxyTypeInspector.getCompatibleClassHierarchy(fromLoader,
ProxyTypeInspector.unwrapProxyTypes(returnType, fromLoader, toLoader)));
}
}
}
return result;
}
private boolean needsEnhancement(Object object)
{
Class<? extends Object> type = object.getClass();
return !type.getName().contains("java.lang")
&& !type.isPrimitive();
}
private List<Object> convertParameterValues(final Object[] args, Method delegateMethod)
{
List<Object> parameterValues = new ArrayList<Object>();
for (int i = 0; i < delegateMethod.getParameterTypes().length; i++)
{
final Class<?> delegateParameterType = delegateMethod.getParameterTypes()[i];
final Object parameterValue = args[i];
// If it is a class, use the toLoader loaded version
if (parameterValue instanceof Class<?>)
{
Class<?> paramClassValue = (Class<?>) parameterValue;
Class<?> loadedClass;
try
{
loadedClass = toLoader.loadClass(paramClassValue.getName());
}
catch (ClassNotFoundException e)
{
// Oh oh, there is no class with this type in the target.
// Trying with delegate ClassLoader;
try
{
loadedClass = delegate.getClass().getClassLoader().loadClass(paramClassValue.getName());
}
catch (ClassNotFoundException cnfe)
{
// No way, here is the original class and god bless you :)
loadedClass = paramClassValue;
}
}
parameterValues.add(loadedClass);
}
else if (delegateParameterType.isPrimitive() || parameterValue == null)
{
parameterValues.add(parameterValue);
}
else
{
final Class<?> parameterType = parameterValue.getClass();
if (!delegateParameterType.isAssignableFrom(parameterType))
{
Object delegateParameterValue = enhance(toLoader, fromLoader, parameterValue,
delegateParameterType);
parameterValues.add(delegateParameterValue);
}
else
{
parameterValues.add(parameterValue);
}
}
}
return parameterValues;
}
private List<Class<?>> convertParameterTypes(final Method method) throws ClassNotFoundException
{
List<Class<?>> parameterTypes = new ArrayList<Class<?>>();
for (int i = 0; i < method.getParameterTypes().length; i++)
{
Class<?> parameterType = method.getParameterTypes()[i];
if (parameterType.isPrimitive())
{
parameterTypes.add(parameterType);
}
else
{
Class<?> delegateParameterType = toLoader.loadClass(parameterType.getName());
parameterTypes.add(delegateParameterType);
}
}
return parameterTypes;
}
public static <T> T enhance(final ClassLoader fromLoader, final ClassLoader toLoader, final Object delegate,
final Class<?>... types)
{
return enhance(fromLoader, toLoader, null, delegate, types);
}
@SuppressWarnings("unchecked")
private static <T> T enhance(final ClassLoader fromLoader, final ClassLoader toLoader,
final Method sourceMethod,
final Object delegate, final Class<?>... types)
{
return ClassLoaders.executeIn(JAVASSIST_LOADER, new Callable<T>()
{
@Override
public T call() throws Exception
{
Class<?>[] hierarchy = null;
if (types == null || types.length == 0)
{
hierarchy = ProxyTypeInspector.getCompatibleClassHierarchy(toLoader,
ProxyTypeInspector.unwrapProxyTypes(delegate.getClass(), fromLoader, toLoader));
if (hierarchy == null || hierarchy.length == 0)
throw new IllegalArgumentException("Must specify at least one non-final type to enhance for Object: "
+ delegate);
}
else
hierarchy = Arrays.copy(types, new Class<?>[types.length]);
MethodFilter filter = new MethodFilter()
{
@Override
public boolean isHandled(Method method)
{
if (!method.getDeclaringClass().getName().contains("java.lang")
|| ("toString".equals(method.getName()) && method.getParameterTypes().length == 0))
return true;
return false;
}
};
Object enhancedResult = null;
ProxyFactory f = new ProxyFactory();
f.setUseCache(true);
if (!hierarchy[0].isInterface())
{
f.setSuperclass(hierarchy[0]);
hierarchy = Arrays.shiftLeft(hierarchy, new Class<?>[hierarchy.length - 1]);
}
if (hierarchy.length > 0)
f.setInterfaces(hierarchy);
f.setFilter(filter);
Class<?> c = f.createClass();
try
{
enhancedResult = c.newInstance();
}
catch (InstantiationException e)
{
throw new IllegalStateException(e);
}
catch (IllegalAccessException e)
{
throw new IllegalStateException(e);
}
try
{
((ProxyObject) enhancedResult)
.setHandler(new ClassLoaderAdapterCallback(fromLoader, toLoader, delegate));
}
catch (ClassCastException e)
{
Class<?>[] interfaces = enhancedResult.getClass().getInterfaces();
for (Class<?> javassistType : interfaces)
{
if (ProxyObject.class.getName().equals(javassistType.getName()))
{
String callbackClassName = ClassLoaderAdapterCallback.class.getName();
ClassLoader javassistLoader = javassistType.getClassLoader();
Constructor<?> callbackConstructor = javassistLoader.loadClass(callbackClassName)
.getConstructors()[0];
Class<?> typeArgument = javassistLoader.loadClass(MethodHandler.class.getName());
Method setHandlerMethod = javassistType.getMethod("setHandler", typeArgument);
setHandlerMethod.invoke(enhancedResult,
callbackConstructor.newInstance(fromLoader, toLoader, delegate));
}
}
}
return (T) enhancedResult;
}
});
}
/*
* Helper Types
*/
static class ProxyTypeInspector
{
public static Class<?>[] getCompatibleClassHierarchy(ClassLoader loader, Class<?> origin)
{
Set<Class<?>> hierarchy = new LinkedHashSet<Class<?>>();
Class<?> baseClass = origin;
while (Modifier.isFinal(baseClass.getModifiers()))
{
baseClass = baseClass.getSuperclass();
}
if (ClassLoaders.containsClass(loader, baseClass)
&& !Object.class.equals(baseClass)
&& (isInstantiable(baseClass) || baseClass.isInterface()))
{
hierarchy.add(ClassLoaders.loadClass(loader, baseClass));
}
baseClass = origin;
while (baseClass != null)
{
for (Class<?> type : baseClass.getInterfaces())
{
if (ClassLoaders.containsClass(loader, type))
hierarchy.add(ClassLoaders.loadClass(loader, type));
}
baseClass = baseClass.getSuperclass();
}
return hierarchy.toArray(new Class<?>[hierarchy.size()]);
}
private static boolean isInstantiable(Class<?> type)
{
try
{
type.getConstructor();
return true;
}
catch (SecurityException e)
{
}
catch (NoSuchMethodException e)
{
}
return false;
}
/*
* Helpers
*/
private static Class<?> unwrapProxyTypes(Class<?> type, ClassLoader... loaders)
{
Class<?> result = type;
for (ClassLoader loader : loaders)
{
try
{
if (result.getName().contains("$$EnhancerByCGLIB$$"))
{
String typeName = result.getName().replaceAll("^(.*)\\$\\$EnhancerByCGLIB\\$\\$.*", "$1");
result = loader.loadClass(typeName);
break;
}
else if (result.getName().contains("_javassist_"))
{
String typeName = result.getName().replaceAll("^(.*)_javassist_.*", "$1");
result = loader.loadClass(typeName);
break;
}
}
catch (ClassNotFoundException e)
{
}
}
return result;
}
}
static class Arrays
{
public static <ELEMENTTYPE> ELEMENTTYPE[] append(ELEMENTTYPE[] array, ELEMENTTYPE element)
{
final int length = array.length;
array = java.util.Arrays.copyOf(array, length + 1);
array[length] = element;
return array;
}
public static <ELEMENTTYPE> ELEMENTTYPE[] copy(ELEMENTTYPE[] source, ELEMENTTYPE[] target)
{
Assert.isTrue(source.length == target.length, "Source and destination arrays must be of the same length.");
System.arraycopy(source, 0, target, 0, source.length);
return target;
}
public static <ELEMENTTYPE> ELEMENTTYPE[] shiftLeft(ELEMENTTYPE[] source, ELEMENTTYPE[] target)
{
Assert.isTrue(source.length > 0, "Source array length cannot be zero.");
Assert.isTrue(source.length - 1 == target.length,
"Destination array must be one element shorter than the source array.");
System.arraycopy(source, 1, target, 0, target.length);
return target;
}
}
}