/*
 * File				: ClassPathHacker.java
 * Created			: Aug 23, 2007
 * License			: Copyright (c) 2006 - RanLogic
 * Original Author 	: Leandro Casadei
 * Modified by		: $LastChangedBy$
 * Last Modication  : $LastChangedDate$
 * Revision			: $LastChangedRevision$
 * 
 * 
 * 
 */

package com.lazerycode.jmeter.scytl;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

public class ClassPathHacker {

    @SuppressWarnings("unchecked")
    private static final Class<URL>[] parameters =
        new Class[] {URL.class };

    public static void addFile(final String s) throws IOException {
        File f = new File(s);
        addFile(f);
    }

    public static void addFile(final File f) throws IOException {
        addURL(f.toURI().toURL());
    }

    public static void addURL(final URL u) throws IOException {
        URLClassLoader sysloader =
            (URLClassLoader) Thread.currentThread()
                .getContextClassLoader();
        Class<URLClassLoader> sysclass = URLClassLoader.class;

        try {
            Method method =
                sysclass.getDeclaredMethod("addURL", parameters);
            method.setAccessible(true);
            method.invoke(sysloader, new Object[] {u });
        } catch (Throwable t) {
            t.printStackTrace();
            throw new IOException(
                "Error, could not add URL to system classloader");
        }

    }

}
