Java Reference
In-Depth Information
};
}
Here, we're getting access to the raw java.io.OutputStream through the write() method
and outputting a simple string to the stream. I like to use an anonymous inner class imple-
mentation of the StreamingOutput interface rather than creating a separate public class.
Since the StreamingOutput interface is so tiny, I think it's beneficial to keep the output lo-
gic embedded within the original JAX-RS resource method so that the code is easier to fol-
low. Usually, you're not going to reuse this logic in other methods, so it doesn't make much
sense to create a specific class.
You may be asking yourself, “Why not just inject an OutputStream directly? Why have a
callback object to do streaming output?” That's a good question! The reason for having a
callback object is that it gives the JAX-RS implementation freedom to handle output
however it wants. For performance reasons, it may sometimes be beneficial for the JAX-RS
implementation to use a different thread other than the calling thread to output responses.
More importantly, many JAX-RS implementations have an interceptor model that abstracts
things out like automatic GZIP encoding or response caching. Streaming directly can usually
bypass these architectural constructs. Finally, the Servlet 3.0 specification has introduced the
idea of asynchronous responses. The callback model fits in very nicely with the idea of asyn-
chronous HTTP within the Servlet 3.0 specification.
java.io.InputStream, java.io.Reader
For reading request message bodies, you can use a raw InputStream or Reader for inputting
any media type. For example:
@Path ( "/" )
public
public class
class MyService
MyService {
@PUT
@Path ( "/stuff" )
public
public void
void putStuff ( InputStream is ) {
byte
byte [] bytes = readFromStream ( is );
String input = new
new String ( bytes );
System . out . println ( input );
}
private
private byte
byte [] readFromStream ( InputStream stream )
throws
throws IOException
{
ByteArrayOutputStream baos = new
new ByteArrayOutputStream ();
Search WWH ::




Custom Search