Skip to content

Streaming output from a Restlet resource

November 16, 2010

This is horrible.  But I am unashamed.  It’s extremely useful to me, too.

Say you have a Restlet resource that needs to do something that is going to run for a long time.  And say you want to know how it’s going, in realtime.

// Inside a Restlet Resource's represent(...) method

PipedInputStream pi = new PipedInputStream();
PipedOutputStream po = new PipedOutputStream(pi);
Representation ir = new OutputRepresentation(MediaType.TEXT_PLAIN){
@Override
public void write(OutputStream realOutput) throws IOException {
byte[] b = new byte[8];
int read;
while ((read = pi.read(b)) != -1) {
realOutput.write(b, 0, read);
realOutput.flush();
}
}
};
OutputStreamWriter ow = new OutputStreamWriter(po);
PrintWriter out = new PrintWriter(ow,true);

// ...

try {
new Thread(new LongRunningBeast(out)).start();
return ir;
} catch (Exception e) {
// return some error representation
}

(https://gist.github.com/701288 for a prettier version.  WordPress is being rude.)

This trick will let you kick off the LongRunningBeast in another thread, and stream content to “out” as if it were stdout or another relatively immediate trick.  The caller will get this content in realtime, and if it’s something like curl, will display that output in realtime.  Lovely!  Almost as good as interactive shell access.

About these ads

From → Uncategorized

One Comment
  1. Thanks.. This helped :)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: