Java Reference
In-Depth Information
the connection), the protocol handler calls the abort() method. This method should
then remove any data from the cache that has been stored for this request.
Example 7-8 demonstrates a basic CacheRequest subclass that passes back a
ByteArrayOutputStream . Later, the data can be retrieved using the getData() method,
a custom method in this subclass just retrieving the data Java wrote onto the Output
Stream this class supplied. An obvious alternative strategy would be to store results in
files and use a FileOutputStream instead.
Example 7-8. A concrete CacheRequest subclass
import java.io.* ;
import java.net.* ;
public class SimpleCacheRequest extends CacheRequest {
private ByteArrayOutputStream out = new ByteArrayOutputStream ();
@Override
public OutputStream getBody () throws IOException {
return out ;
}
@Override
public void abort () {
out . reset ();
}
public byte [] getData () {
if ( out . size () == 0 ) return null ;
else return out . toByteArray ();
}
}
The get() method in ResponseCache retrieves the data and headers from the cache and
returns them wrapped in a CacheResponse object. It returns null if the desired URI is
not in the cache, in which case the protocol handler loads the URI from the remote
server as normal. Again, this is an abstract class that you have to implement in a subclass.
Example 7-9 summarizes this class. It has two methods: one to return the data of the
request and one to return the headers. When caching the original response, you need
to store both. The headers should be returned in an unmodifiable map with keys that
are the HTTP header field names and values that are lists of values for each named
HTTP header.
Example 7-9. The CacheResponse class
public abstract class CacheResponse {
public abstract Map < String , List < String >> getHeaders () throws IOException ;
public abstract InputStream getBody () throws IOException ;
}
Search WWH ::




Custom Search