Java Reference
In-Depth Information
Example 7-10 shows a simple CacheResponse subclass that is tied to a SimpleCacheRe
quest and a CacheControl . In this example, shared references pass data from the request
class to the response class. If you were storing responses in files, you'd just need to share
the filenames instead. Along with the SimpleCacheRequest object from which it will
read the data, you must also pass the original URLConnection object into the constructor.
This is used to read the HTTP header so it can be stored for later retrieval. The object
also keeps track of the expiration date and cache-control (if any) provided by the server
for the cached representation of the resource.
Example 7-10. A concrete CacheResponse subclass
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class SimpleCacheResponse extends CacheResponse {
private final Map < String , List < String >> headers ;
private final SimpleCacheRequest request ;
private final Date expires ;
private final CacheControl control ;
public SimpleCacheResponse (
SimpleCacheRequest request , URLConnection uc , CacheControl control )
throws IOException {
this . request = request ;
this . control = control ;
this . expires = new Date ( uc . getExpiration ());
this . headers = Collections . unmodifiableMap ( uc . getHeaderFields ());
}
@Override
public InputStream getBody () {
return new ByteArrayInputStream ( request . getData ());
}
@Override
public Map < String , List < String >> getHeaders ()
throws IOException {
return headers ;
}
public CacheControl getControl () {
return control ;
}
public boolean isExpired () {
Date now = new Date ();
if ( control . getMaxAge (). before ( now )) return true ;
else if ( expires != null && control . getMaxAge () != null ) {
Search WWH ::




Custom Search