Java Reference
In-Depth Information
Web Cache for Java
By default, Java does not cache anything. To install a system-wide cache of the URL class
will use, you need the following:
• A concrete subclass of ResponseCache
• A concrete subclass of CacheRequest
• A concrete subclass of CacheResponse
You install your subclass of ResponseCache that works with your subclass of CacheRe
quest and CacheResponse by passing it to the static method ResponseCache.setDe
fault() . This installs your cache object as the system default. A Java virtual machine
can only support a single shared cache.
Once a cache is installed whenever the system tries to load a new URL, it will first look
for it in the cache. If the cache returns the desired content, the URLConnection won't
need to connect to the remote server. However, if the requested data is not in the cache,
the protocol handler will download it. After it's done so, it will put its response into the
cache so the content is more quickly available the next time that URL is loaded.
Two abstract methods in the ResponseCache class store and retrieve data from the sys‐
tem's single cache:
public abstract CacheResponse get(URI uri, String requestMethod,
Map<String, List<String>> requestHeaders) throws IOException
public abstract CacheRequest put(URI uri, URLConnection connection)
throws IOException
The put() method returns a CacheRequest object that wraps an OutputStream into
which the URL will write cacheable data it reads. CacheRequest is an abstract class with
two methods, as shown in Example 7-7 .
Example 7-7. The CacheRequest class
package java . net ;
public abstract class CacheRequest {
public abstract OutputStream getBody () throws IOException ;
public abstract void abort ();
}
The getOutputStream() method in the subclass should return an OutputStream that
points into the cache's data store for the URI passed to the put() method at the same
time. For instance, if you're storing the data in a file, you'd return a FileOutput
Stream connected to that file. The protocol handler will copy the data it reads onto this
OutputStream . If a problem arises while copying (e.g., the server unexpectedly closes
Search WWH ::




Custom Search