public class HttpHeaderUtil {
public static CacheEntry<CachedResponse> buildCacheEntry(SenderRequest request, SenderResponse response) {
Multival headers = response.getHeaders();
long softTtl = 0; //seconds
long maxAge = 0; //seconds
boolean hasCacheControl = false;
String headerValue = headers.getFirst("Cache-Control");
if (headerValue != null) {
hasCacheControl = true;
String[] tokens = headerValue.split(",");
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i].trim();
if (token.equals("no-store") || token.equals("no-cache")) {
//always check server for new version (with If-None-Match (ETag) or If-Modified-Since(Last-Modified/Date))
//if ETag or Last-Modified is not present, we will not cache this reponse at all
maxAge = 0;
break;
} else if (token.equals("must-revalidate") || token.equals("proxy-revalidate")) {
//cache response until expire (max-age, Expires)
//then check server for new version (with If-None-Match (ETag) or If-Modified-Since(Last-Modified/Date))
//when max-age=0 or Expires=-1 then this is same as no-store/no-cache
maxAge = 0;
} else if (token.startsWith("max-age=")) {
try {
maxAge = Long.parseLong(token.substring(8));//seconds
break;
} catch (Exception e) {
//ignore
}
}
}
}
long serverDate = 0;
headerValue = headers.getFirst("Date");
if (headerValue != null) {
serverDate = parseDateAsEpoch(headerValue);
}
long serverExpires = 0;
headerValue = headers.getFirst("Expires");
if (headerValue != null) {
serverExpires = parseDateAsEpoch(headerValue);
}
long lastModified = 0;
headerValue = headers.getFirst("Last-Modified");
if (headerValue != null) {
lastModified = parseDateAsEpoch(headerValue);
}
Date modified = lastModified > 0 ? new Date(lastModified) : null;
String etag = headers.getFirst("ETag");
// Cache-Control takes precedence over an Expires header,
// even if both exist and Expires is more restrictive.
if (hasCacheControl) {
softTtl = maxAge;