
import java.net.*;
import java.util.*;
import java.io.*;

/**
 * Create a HTTP connection to the specified location
 **/
public class Load implements Runnable {

URL location;
boolean success = false;
boolean complete = false;
Exception offendingException = null;
ListenerList listeners = null;
final int id;
static int nextId = 1;

public Load(URL location) throws MalformedURLException {
	if(!location.getProtocol().equals("http")) {
		throw new MalformedURLException("Only http URLs allowed");
	}
	this.location = location;

	id = nextId;
	nextId++;
}

public Load(String location) throws MalformedURLException {
	this(new URL(location));
}

public String toString() {
	return "Load # "+id;
}

public void run() {
	HttpURLConnection connection;
	InputStream input;
	int dataByte;

	// System.out.println("load on "+location);

	try {
		connection = (HttpURLConnection)location.openConnection();
		connection.connect();
		input = connection.getInputStream();
		do {
			dataByte = input.read();
		} while(dataByte != -1);
		input.close();
		connection.disconnect();
		success = true;
		complete = true;
	} catch(IOException ioe) {
		success = false;
		complete = true;
		offendingException = ioe;
	}

	Enumeration e = ListenerList.elements(listeners);
	LoadListener ll;
	while(e.hasMoreElements()) {
		ll = (LoadListener)e.nextElement();
		// System.out.println("sending loadCOmplete to "+ll);
		ll.loadComplete(this);
	}

}

public boolean isSuccessful() {
	return success;
}

public boolean isComplete() {
	return complete;
}

public Exception getException() {
	return offendingException;
}

public void addLoadListener(LoadListener ll) {
	listeners = ListenerList.add(listeners,ll);
}

public void removeLoadListener(LoadListener ll) {
	listeners = ListenerList.remove(listeners,ll);
}

}
