package org.apache.slide.projector.engine;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.apache.slide.projector.Projector;
import org.apache.slide.projector.context.ProjectorContext;
import org.apache.slide.projector.repository.RepositoryException;
import org.apache.slide.projector.util.StreamHelper;
import org.apache.slide.projector.value.Streamable;
import org.apache.slide.projector.value.URI;
import org.apache.slide.projector.value.URIValue;

public class ProjectorClassLoader extends ClassLoader {
    URI uri;

    public ProjectorClassLoader(ClassLoader parent, URI uri) {
        super(parent);
        this.uri = uri;
    }

    public Class findClass(String name) throws ClassNotFoundException {
        ProjectorContext context = Projector.getSystemContext();
        try {
            URI rendererUri = new URIValue(uri.toString() + name.replace('.', '/') + ".class");
            Streamable resource = ((Streamable)Projector.getRepository().getResource(rendererUri, context.getCredentials()));
            if ( resource == null ) {
            	throw new ClassNotFoundException("Class " + name + " at URI '"+rendererUri+"' not found in collection '" + uri + "'!");
            }
            InputStream inputStream = resource.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream(1024);
            StreamHelper.copy(inputStream, outputStream);
            byte[] b = outputStream.toByteArray();
            return defineClass(name, b, 0, b.length);
        } catch (RepositoryException e) {
            throw new ClassNotFoundException("Class " + name + " not found in collection " + uri + "!", e);
        }
    }
}