package com.atlassian.stash.internal.plugin;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Copy of {@link com.atlassian.plugin.osgi.hostcomponents.impl.DefaultComponentRegistrar.ContextClassLoaderSettingInvocationHandler}
 * which isn't restricted to private. If this class is ever made available we should delete this class
 */
public class ContextClassLoaderSettingInvocationHandler implements InvocationHandler {

    private final Object service;

    public ContextClassLoaderSettingInvocationHandler(final Object service) {
        this.service = service;
    }

    public Object invoke(final Object o, final Method method, final Object[] objects) throws Throwable {
        final Thread thread = Thread.currentThread();
        final ClassLoader ccl = thread.getContextClassLoader();
        try {
            thread.setContextClassLoader(service.getClass().getClassLoader());
            return method.invoke(service, objects);
        } catch (final InvocationTargetException e) {
            throw e.getTargetException();
        } finally {
            thread.setContextClassLoader(ccl);
        }
    }
}
