package dcj.util.Bandwidth;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
/**
* Source code from "Java Distributed Computing", by Jim Farley.
*
* Example: 8-4 ContentConsumer
* Description: A consumer of content streaming into an application.
*/
public class ContentConsumer
{
protected ContentProducer source = null;
protected ContentConsumer dest = null;
protected DataMonitor monitor = new DataMonitor();
public ContentConsumer(ContentProducer src) {
source = src;
}
public ContentConsumer(ContentConsumer dst) {
dest = dst;
}
public void setSource(ContentProducer p) {
source = p;
}
public void setDest(ContentConsumer c) {
dest = c;
}
// Consume data from our producer until it is exhausted.
public boolean consumeAll() {
boolean success = false;
if (source != null) {
byte[] data = source.produce(0);
while (data != null) {
success = consume(data);
data = source.produce(0);
}
}
return success;
}
// Consume a chunk of data
public boolean consume(byte[] data) {
// Log the start of the consumption cycle.
Date start = new Date();
boolean success;
success = preConsume(data);
if (success)
success = doConsume(data);
if (success)
success = postConsume(data);
// Mark the end of our consumption cycle
monitor.addSample(data.length, start, new Date());
// Pass the data on to the next consumer in the chain,
// if present.
if (dest != null) {
dest.consume(data);
}
return success;
}
protected boolean preConsume(byte[] data) {
return true;
}
// Default consumption procedure.
protected boolean doConsume(byte[] data) {
return true;
}
// Default post-consumption procedure: log the data consumption
// size and finish time with our monitor.
protected boolean postConsume(byte[] data) {
return true;
}
} |