import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;

/**
 * An object that is responsible for retrieving classes from an
 * HTTP server and writing them to a local file
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class HTTPClassRetriever
{
    private String      uri;

    public static final String EXT = ".class";


    /**
     * Explicit Value Constructor
     * 
     * @param uri   The host and path to load from
     */
    public HTTPClassRetriever(String uri)
    {
	this.uri = uri;
    }

    /**
     * Retrieve the class using HTTP
     *
     * @param name  The name of the class (without the extension)
     * @param       The bytes that comprise the class
     */
    public void retrieveClass(String name) throws IOException
    {
	byte[]             bytes;
	FileOutputStream   out;

        bytes = requestBytes(name);
	out = new FileOutputStream(name+EXT);
	out.write(bytes);
    }

    /**
     * Request the bytes in the class using an HTTP GET request
     *
     * @param name  The name of the class (without the extension)
     * @param       The bytes that comprise the class
     */
    private byte[] requestBytes(String name) throws IOException
    {
       byte[]         bytes;
       InputStream    in;
       URL            u;

       u = new URL(uri + name + EXT);
        
       in    = u.openStream();
       bytes = new byte[in.available()];

       in.read(bytes);

       return bytes;
    }
}
