package com.hammurapi.common;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Vector;

/**
 * Class loader which filters classes/resources from another classloader. This classloader can be
 * used for fine-grained loading of classes from a jar file which contains several logical groups of classes (e.g. packages)
 * which have to be loaded individually, e.g. they have different dependencies.
 * @author Pavel
 *
 */
public abstract class FilterClassLoader extends ClassLoader {

	private ClassLoader filtered;

	protected FilterClassLoader(ClassLoader filtered) {
		super();
		this.filtered = filtered;
	}

	protected FilterClassLoader(ClassLoader filtered, ClassLoader parent) {
		super(parent);
		this.filtered = filtered;
	}
	
	protected abstract boolean accept(String name);
	
	@Override
	protected URL findResource(String name) {
		return accept(name) ? filtered.getResource(name) : null;
	}
	
	@Override
	protected Enumeration<URL> findResources(String name) throws IOException {
		return accept(name) ? filtered.getResources(name) : new Vector<URL>().elements();
	}
	
	@Override
	protected Class<?> findClass(String name) throws ClassNotFoundException {
		if (accept(name.replace('.', '/')+".class")) {
			return filtered.loadClass(name);
		}
		return super.findClass(name);
	}
	
}
