package org.kohsuke.stapler;

import java.util.Map;
import java.util.WeakHashMap;
import java.io.File;
import java.net.URLClassLoader;
import java.net.URL;
import java.net.MalformedURLException;

/**
 * The stapler version of the {@link ClassLoader} object,
 * that retains some useful cache about a class loader.
 *
 * @author Kohsuke Kawaguchi
 */
public class MetaClassLoader extends TearOffSupport {
    public final MetaClassLoader parent;
    public final ClassLoader loader;

    public MetaClassLoader(ClassLoader loader) {
        this.loader = loader;
        this.parent = get(loader.getParent());
    }

    public static MetaClassLoader get(ClassLoader cl) {
        if(cl ==null)
            return null; // if no parent, delegate to the debug loader if available.
        
        synchronized(classMap) {
            MetaClassLoader mc = classMap.get(cl);
            if(mc==null) {
                mc = new MetaClassLoader(cl);
                classMap.put(cl,mc);
            }
            return mc;
        }
    }

    /**
     * If non-null, delegate to this classloader.
     */
    public static MetaClassLoader debugLoader = null;

    /**
     * All {@link MetaClass}es.
     *
     * Avoids class leaks by {@link WeakHashMap}.
     */
    private static final Map<ClassLoader,MetaClassLoader> classMap = new WeakHashMap<ClassLoader,MetaClassLoader>();

    static {
        try {
            String path = System.getProperty("stapler.resourcePath");
            if(path!=null) {
                debugLoader = new MetaClassLoader(
                    new URLClassLoader(new URL[]{new File(path).toURI().toURL()}));
            }
        } catch (MalformedURLException e) {
            throw new Error(e);
        }
    }
}

@@ -1519,123 +1519,288 @@
     
-debugLoader = new MetaClassLoader(%0A                    new URLClassLoader(new URL%5B%5D%7Bnew File(path).toURI().toURL()%7D
+String%5B%5D tokens = path.split(%22;%22);%0A                URL%5B%5D urls = new URL%5Btokens.length%5D;%0A                for (int i=0; i%3Ctokens.length; i++)%0A                    urls%5Bi%5D = new File(tokens%5Bi%5D).toURI().toURL();%0A                debugLoader = new MetaClassLoader(new URLClassLoader(urls
 ));%0A

support multiple locations in stapler.resourcePath, separated by ";"