summaryrefslogtreecommitdiffstats
path: root/sandbox/old/contrib/binding-osgi/src/main/java/org/apache/tuscany/osgi/util/ClassloaderHook.java
blob: 33f7706c3e1ea81e74d173aa6caebf73d1521606 (plain)
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
package org.apache.tuscany.osgi.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;

import org.osgi.framework.Bundle;

public class ClassloaderHook {

    /**
     * Return the BundleContext Classloader for the specified bundle.
     *
     * @param bundle The bundle whose BundleContext is desired.
     * @return The BundleContext classloader for the specified bundle.
     */
    ClassLoader getClassLoader(final Bundle bundle) {
        if (System.getSecurityManager() == null) {
            Object bundleLoader = invokeMethod(bundle, "checkLoader", null, null);
            return (ClassLoader) invokeMethod(bundleLoader, "createClassLoader", null, null);
        }
        return AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
            public ClassLoader run() {
                Object bundleLoader = invokeMethod(bundle, "checkLoader", null, null);
                return (ClassLoader) invokeMethod(bundleLoader, "createClassLoader", null, null);
            }
        });
    }

    /**
     * Throws an IllegalStateException if the reflection logic cannot find what it is looking for. This probably means
     * this class does not properly recognize the framework implementation.
     *
     * @param e Exception which indicates the reflection logic is confused.
     */
    protected void reflectionException(Exception e) {
        throw new IllegalStateException(
            "ClassLoaderHook does not recognize the framework implementation: " + e.getMessage());
    }

    private Object invokeMethod(Object target, String methodName, Class[] parms, Object[] args) {
        Method method;
        try {
            method = target.getClass().getMethod(methodName, parms);
            if (method != null) {
                return method.invoke(target, parms, args);
            }
        } catch (SecurityException e) {
            reflectionException(e);
        } catch (NoSuchMethodException e) {
            reflectionException(e);
        } catch (IllegalArgumentException e) {
            reflectionException(e);
        } catch (IllegalAccessException e) {
            reflectionException(e);
        } catch (InvocationTargetException e) {
            reflectionException(e);
        }
        return null;
    }


}