Java Reference
In-Depth Information
}
}
I'll show you later how to register these client-side filters, but our request filter must be re-
gistered as a singleton and constructed with an instance of a Cache . I'm not going to go into
the details of this Cache class, but hopefully you can make an educated guess of how its im-
plemented.
Our ClientCacheRequestFilter.filter() method performs a variety of actions based on
the state of the underlying cache. First, it checks the ClientRequestContext to see if we're
doing an HTTP GET. If not, it just returns and does nothing. Next, we look up the request's
URI in the cache. If there is no entry, again, just return. If there is an entry, we must check to
see if it's expired or not. If it isn't, we create a Response object that returns a 200, “OK,”
status. We populate the Response object with the content and Content-Header stored in the
cache entry and abort the invocation by calling ClientRequestContext.abortWith() .
Depending on how the application initiated the client invocation, the aborted Response ob-
ject will either be returned directly to the client application, or unmarshalled into the appro-
priate Java type. If the cache entry has expired, we perform a conditional GET by setting the
If-None-Match and/or If-Modified-Since request headers with values stored in the cache
entry.
Now that we've seen the request filter, let's finish this example by implementing the re-
sponse filter:
public
public class
class CacheResponseFilter
CacheResponseFilter implements
implements ClientResponseFilter {
private
private Cache cache ;
public
public CacheResponseFilter ( Cache cache ) {
this
this . cache = cache ;
}
public
public void
void filter ( ClientRequestContext request ,
ClientResponseContext response )
throws IOException {
iif (! request . getMethod (). equalsIgnoreCase ( "GET" )) return
throws
return ;
iif ( response . getStatus () == 200 ) {
cache . cacheResponse ( response , request . getUri ());
} else
else iif ( response . getStatus () == 304 ) {
CacheEntry entry = cache . getEntry ( request . getUri ());
entry . updateCacheHeaders ( response );
response . getHeaders (). clear ();
Search WWH ::




Custom Search