package dcj.examples.Bandwidth;
import dcj.util.Bandwidth.*;
import java.io.InputStream;
import java.lang.Runnable;
import java.util.Hashtable;
import java.net.*;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Class: HTMLPageLoader
* Example: 8-7
* Description: An object responsible for allocated bandwidth for loading
* elements of a web page.
* NOTE: This file contains incomplete example code only, which will
* not compile without additions and modifications.
*/
public class HTMLPageLoader implements Runnable {
Vector elements;
Vector focusElements;
Vector loadedElements;
boolean focusUpdate;
Hashtable elementConsumers = new Hashtable();
public void run() {
loadElements();
}
public HTMLPageLoader(Vector urlList) {
elements = urlList.clone();
}
public void addPageElement(URL addr) {
elements.addElement(addr);
}
public void focusElement(URL addr) {
synchronized (elements) {
if (!elements.contains(addr)) {
addPageElement(addr);
}
}
synchronized (focusElements) {
if (!focusElements.contains(addr)) {
focusElements.addElement(addr);
}
focusUpdate = true;
}
}
public void defocusElement(URL addr) {
synchronized (focusElements) {
if (focusElements.removeElement(addr)) {
focusUpdate = true;
}
}
}
public void loadElements() {
Vector localFocus = null;
boolean done = false;
boolean changedFocus = false;
Vector consumers;
synchronized (focusElements) {
if (!focusElements.isEmpty()) {
localFocus = (Vector)focusElements.clone();
}
}
synchronized (elements) {
if (localFocus == null) {
localFocus = elements.clone();
}
}
while (!done) {
Enumeration e = localFocus.elements();
while (e.hasMoreElements()) {
URL element = (URL)e.nextElement();
ContentConsumer c = getConsumer(element);
long byteCount = elementSize(element);
// Consume a maximum of 5 percent of the entire element
// in each loop.
if (byteCount > 20) {
byteCount = byteCount / 20;
}
c.consume(byteCount);
if (isComplete(element)) {
doneElements.addElement(element);
focusElements.removeElement(element);
localFocus.removeElement(element);
}
}
synchronized (focusElements) {
if (focusUpdate) {
localFocus = focusElements.clone();
focusUpdate = false;
changedFocus = true;
}
}
if (focusElements.isEmpty()) {
// No focus elements left, so we're either done loading
// the region the user is looking at, or we've finished
// the entire page.
if (doneElements.size() == elements.size()) {
done = true;
}
else {
localFocus = elements;
}
}
}
}
protected Vector getConsumer(URL item) {
ContentConsumer c;
// If the element has a consumer already,
// add it to the list
if (elementConsumers.contains(item)) {
c = (ContentConsumer)elementConsumers.get(item);
}
else {
try {
InputStream in = item.openStream();
StreamProducer sp = new StreamProducer(in);
c = makeConsumerFor(item);
c.setSource(sp);
elementConsumers.put(item, c);
}
catch (Exception e) { }
}
return c;
}
} |