public void pollInternal() { HttpHeaders requestHeaders = new HttpHeaders(); if (lastModified != null) { requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified)); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { log.trace("data has been modified"); Feed feed = response.getBody(); for (Entry entry : feed.getEntries()) { if ((lastModified == null) || (entry.getUpdated().after(lastModified))) { Invoice invoice = restTemplate .getForEntity(entry.getContents().get(0).getSrc(), Invoice.class).getBody(); log.trace("saving invoice {}", invoice.getId()); invoiceService.generateInvoice(invoice); } } if (response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED) != null) { lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED)); log.trace("Last-Modified header {}", lastModified); } } else { log.trace("no new data"); } }
@Test public void requestWithLastModifiedReturns304() { Order order = new Order(); order.setCustomer(customerRepository.findAll().iterator().next()); orderRepository.save(order); ResponseEntity<Feed> response = restTemplate.exchange(feedUrl(), HttpMethod.GET, new HttpEntity(null), Feed.class); Date lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified")); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified)); HttpEntity requestEntity = new HttpEntity(requestHeaders); response = restTemplate.exchange(feedUrl(), HttpMethod.GET, requestEntity, Feed.class); assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode()); }
public void pollInternal() { HttpHeaders requestHeaders = new HttpHeaders(); if (lastModified != null) { requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified)); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { log.trace("data has been modified"); Feed feed = response.getBody(); for (Entry entry : feed.getEntries()) { if ((lastModified == null) || (entry.getUpdated().after(lastModified))) { Shipment shipping = restTemplate .getForEntity(entry.getContents().get(0).getSrc(), Shipment.class).getBody(); log.trace("saving shipping {}", shipping.getId()); shipmentService.ship(shipping); } } if (response.getHeaders().getFirst("Last-Modified") != null) { lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED)); log.trace("Last-Modified header {}", lastModified); } } else { log.trace("no new data"); } }
private boolean isLastModifiedChanged(final HttpResponse response) { final Header newLastModifiedHeader = response.getFirstHeader(HttpHeaders.LAST_MODIFIED); if (newLastModifiedHeader != null) { final Date newLastModified = DateUtils.parseDate(newLastModifiedHeader.getValue()); if (newLastModified == null) { throw new IllegalArgumentException("Invalid last modified date"); } if (!_previousLastModified.isPresent() || newLastModified.after(_previousLastModified.get())) { LOGGER.debug() .setMessage("Uri last modified changed") .addData("uri", _uri) .addData("newLastModified", newLastModified) .addData("previousLastModified", _previousLastModified) .log(); _previousLastModified = Optional.of(newLastModified); return true; } } return false; }
private boolean revalidationResponseIsTooOld(final HttpResponse backendResponse, final HttpCacheEntry cacheEntry) { final Header entryDateHeader = cacheEntry.getFirstHeader(HTTP.DATE_HEADER); final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); if (entryDateHeader != null && responseDateHeader != null) { final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); final Date respDate = DateUtils.parseDate(responseDateHeader.getValue()); if (entryDate == null || respDate == null) { // either backend response or cached entry did not have a valid // Date header, so we can't tell if they are out of order // according to the origin clock; thus we can skip the // unconditional retry recommended in 13.2.6 of RFC 2616. return false; } if (respDate.before(entryDate)) { return true; } } return false; }
private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final HttpRequestWrapper request, final HttpResponse backendResponse) { HttpCacheEntry existing = null; try { existing = responseCache.getCacheEntry(target, request); } catch (final IOException ioe) { // nop } if (existing == null) { return false; } final Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER); if (entryDateHeader == null) { return false; } final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER); if (responseDateHeader == null) { return false; } final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); if (entryDate == null || responseDate == null) { return false; } return responseDate.before(entryDate); }
private boolean expiresHeaderLessOrEqualToDateHeaderAndNoCacheControl( final HttpResponse response) { if (response.getFirstHeader(HeaderConstants.CACHE_CONTROL) != null) { return false; } final Header expiresHdr = response.getFirstHeader(HeaderConstants.EXPIRES); final Header dateHdr = response.getFirstHeader(HTTP.DATE_HEADER); if (expiresHdr == null || dateHdr == null) { return false; } final Date expires = DateUtils.parseDate(expiresHdr.getValue()); final Date date = DateUtils.parseDate(dateHdr.getValue()); if (expires == null || date == null) { return false; } return expires.equals(date) || expires.before(date); }
@Test public void testSmallEnoughResponsesAreCached() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest request = new HttpGet("http://foo.example.com/bar"); final Date now = new Date(); final Date requestSent = new Date(now.getTime() - 3 * 1000L); final Date responseGenerated = new Date(now.getTime() - 2 * 1000L); final Date responseReceived = new Date(now.getTime() - 1 * 1000L); final HttpResponse originResponse = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); originResponse.setEntity(HttpTestUtils.makeBody(CacheConfig.DEFAULT_MAX_OBJECT_SIZE_BYTES - 1)); originResponse.setHeader("Cache-Control","public, max-age=3600"); originResponse.setHeader("Date", DateUtils.formatDate(responseGenerated)); originResponse.setHeader("ETag", "\"etag\""); final HttpResponse result = impl.cacheAndReturnResponse(host, request, originResponse, requestSent, responseReceived); assertEquals(1, backing.map.size()); assertTrue(backing.map.containsKey((new CacheKeyGenerator()).getURI(host, request))); assertTrue(HttpTestUtils.semanticallyTransparent(originResponse, result)); }
@Test public void testForwardsExistingWarningHeadersOnResponseThatArrivesStale() throws Exception { originResponse.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); originResponse.setHeader("Cache-Control","public, max-age=5"); originResponse.setHeader("ETag","\"etag\""); originResponse.addHeader("Age","10"); final String warning = "110 fred \"Response is stale\""; originResponse.addHeader("Warning",warning); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); final HttpResponse result = impl.execute(route, request, context, null); verifyMocks(); assertEquals(warning, result.getFirstHeader("Warning").getValue()); }
@Test public void flushesEntryIfFresherAndSpecifiedByRelativeContentLocation() throws Exception { response.setHeader("ETag","\"new-etag\""); response.setHeader("Date", DateUtils.formatDate(now)); final String cacheKey = "http://foo.example.com:80/bar"; response.setHeader("Content-Location", "/bar"); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("ETag", "\"old-etag\"") }); when(mockStorage.getEntry(cacheKey)).thenReturn(entry); impl.flushInvalidatedCacheEntries(host, request, response); verify(mockStorage).getEntry(cacheKey); verify(mockStorage).removeEntry(cacheKey); }
@Test public void testDoNotFlushContentLocationEntryIfSafeRequest() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpGet("/foo"); final HttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), new BasicHeader("ETag", "\"old-etag\"") }); backing.map.put(key, entry); impl.flushInvalidatedCacheEntriesFor(host, req, resp); assertEquals(entry, backing.map.get(key)); }
@Test public void doesNotFlushEntrySpecifiedByContentLocationIfResponseHasNoEtag() throws Exception { response.removeHeaders("ETag"); response.setHeader("Date", DateUtils.formatDate(now)); final String theURI = "http://foo.example.com:80/bar"; response.setHeader("Content-Location", theURI); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("ETag", "\"old-etag\"") }); when(mockStorage.getEntry(theURI)).thenReturn(entry); impl.flushInvalidatedCacheEntries(host, request, response); verify(mockStorage).getEntry(theURI); verifyNoMoreInteractions(mockStorage); }
@Test public void expiresEqualToDateWithNoCacheControlIsNotCacheable() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest()); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(now)); resp1.setHeader("Expires", DateUtils.formatDate(now)); resp1.removeHeaders("Cache-Control"); backendExpectsAnyRequestAndReturn(resp1); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest()); req2.setHeader("Cache-Control", "max-stale=1000"); final HttpResponse resp2 = HttpTestUtils.make200Response(); resp2.setHeader("ETag", "\"etag2\""); backendExpectsAnyRequestAndReturn(resp2); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp2, result)); }
@Test public void returnsStaleCacheEntryWithOnlyIfCachedAndMaxStale() throws Exception { final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest()); final HttpResponse resp1 = HttpTestUtils.make200Response(); resp1.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); resp1.setHeader("Cache-Control","max-age=5"); backendExpectsAnyRequestAndReturn(resp1); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(HttpTestUtils.makeDefaultRequest()); req2.setHeader("Cache-Control", "max-stale=20, only-if-cached"); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); assertTrue(HttpTestUtils.semanticallyTransparent(resp1, result)); }
@Test public void testFlushContentLocationEntryIfUnSafeRequest() throws Exception { final HttpHost host = new HttpHost("foo.example.com"); final HttpRequest req = new HttpPost("/foo"); final HttpResponse resp = HttpTestUtils.make200Response(); resp.setHeader("Content-Location", "/bar"); resp.setHeader(HeaderConstants.ETAG, "\"etag\""); final String key = (new CacheKeyGenerator()).getURI(host, new HttpGet("/bar")); final HttpCacheEntry entry = HttpTestUtils.makeCacheEntry(new Header[] { new BasicHeader("Date", DateUtils.formatDate(new Date())), new BasicHeader("ETag", "\"old-etag\"") }); backing.map.put(key, entry); impl.flushInvalidatedCacheEntriesFor(host, req, resp); assertNull(backing.map.get(key)); }
@Test public void testStripsBadlyDatedWarningsFromForwardedResponses() throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); originResponse.setHeader("Date", DateUtils.formatDate(now)); originResponse.addHeader("Warning", "110 fred \"stale\", 110 wilma \"stale\" \"" + DateUtils.formatDate(tenSecondsAgo) + "\""); originResponse.setHeader("Cache-Control","no-cache,no-store"); backendExpectsAnyRequest().andReturn(originResponse); replayMocks(); final HttpResponse result = impl.execute(route, request, context, null); verifyMocks(); for(final Header h : result.getHeaders("Warning")) { Assert.assertFalse(h.getValue().contains("wilma")); } }
@Test public void testReturns304ForIfNoneMatchHeaderIfRequestServedFromCache() throws Exception { impl = createCachingExecChain(mockBackend, new BasicHttpCache(), CacheConfig.DEFAULT); final HttpRequestWrapper req1 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); final HttpRequestWrapper req2 = HttpRequestWrapper.wrap(new HttpGet( "http://foo.example.com/")); req2.addHeader("If-None-Match", "*"); final HttpResponse resp1 = new BasicHttpResponse(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"); resp1.setEntity(HttpTestUtils.makeBody(128)); resp1.setHeader("Content-Length", "128"); resp1.setHeader("ETag", "\"etag\""); resp1.setHeader("Date", DateUtils.formatDate(new Date())); resp1.setHeader("Cache-Control", "public, max-age=3600"); backendExpectsAnyRequestAndReturn(resp1); replayMocks(); impl.execute(route, req1, context, null); final HttpResponse result = impl.execute(route, req2, context, null); verifyMocks(); Assert.assertEquals(HttpStatus.SC_NOT_MODIFIED, result.getStatusLine().getStatusCode()); }
@Test public void testNewerHeadersReplaceExistingHeaders() throws IOException { final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(requestDate)), new BasicHeader("Cache-Control", "private"), new BasicHeader("ETag", "\"etag\""), new BasicHeader("Last-Modified", DateUtils.formatDate(requestDate)), new BasicHeader("Cache-Control", "max-age=0"),}; entry = HttpTestUtils.makeCacheEntry(headers); response.setHeaders(new Header[] { new BasicHeader("Last-Modified", DateUtils.formatDate(responseDate)), new BasicHeader("Cache-Control", "public")}); final HttpCacheEntry updatedEntry = impl.updateCacheEntry(null, entry, new Date(), new Date(), response); final Header[] updatedHeaders = updatedEntry.getAllHeaders(); assertEquals(4, updatedHeaders.length); headersContain(updatedHeaders, "Date", DateUtils.formatDate(requestDate)); headersContain(updatedHeaders, "ETag", "\"etag\""); headersContain(updatedHeaders, "Last-Modified", DateUtils.formatDate(responseDate)); headersContain(updatedHeaders, "Cache-Control", "public"); }
private void testUnknownResponseStatusCodeIsNotCached(final int code) throws Exception { emptyMockCacheExpectsNoPuts(); originResponse = Proxies.enhanceResponse( new BasicHttpResponse(HttpVersion.HTTP_1_1, code, "Moo")); originResponse.setHeader("Date", DateUtils.formatDate(new Date())); originResponse.setHeader("Server", "MockOrigin/1.0"); originResponse.setHeader("Cache-Control", "max-age=3600"); originResponse.setEntity(body); EasyMock.expect( mockBackend.execute( EasyMock.isA(HttpRoute.class), EasyMock.isA(HttpRequestWrapper.class), EasyMock.isA(HttpClientContext.class), EasyMock.<HttpExecutionAware>isNull())).andReturn(originResponse); replayMocks(); impl.execute(route, request, context, null); // in particular, there were no storage calls on the cache verifyMocks(); }
@Test public void oldHeadersRetainedIfResponseOlderThanEntry() throws Exception { final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(oneSecondAgo)), new BasicHeader("ETag", "\"new-etag\"") }; entry = HttpTestUtils.makeCacheEntry(twoSecondsAgo, now, headers); response.setHeader("Date", DateUtils.formatDate(tenSecondsAgo)); response.setHeader("ETag", "\"old-etag\""); final HttpCacheEntry result = impl.updateCacheEntry("A", entry, new Date(), new Date(), response); assertEquals(2, result.getAllHeaders().length); headersContain(result.getAllHeaders(), "Date", DateUtils.formatDate(oneSecondAgo)); headersContain(result.getAllHeaders(), "ETag", "\"new-etag\""); }
public long getLastModified() { Header responseHeader = response.getFirstHeader("last-modified"); if (responseHeader == null) { return 0; } try { return DateUtils.parseDate(responseHeader.getValue()).getTime(); } catch (Exception e) { return 0; } }
@Override public CookieSpec create(HttpContext context) { String[] datePatterns = new String[] { DateUtils.PATTERN_RFC1123, DATE_PATTERN_NETSCAPE1,//default Netscape date pattern }; return new DefaultCookieSpec(datePatterns, false) { @Override public void validate(Cookie cookie, CookieOrigin origin) throws MalformedCookieException { //do nothing } }; }
@Scheduled(fixedDelay = 15000) public void poll() { HttpHeaders requestHeaders = new HttpHeaders(); if (lastModified != null) { requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified)); } HttpEntity<?> requestEntity = new HttpEntity(requestHeaders); ResponseEntity<Feed> response = restTemplate.exchange(creditDecisionFeed, HttpMethod.GET, requestEntity, Feed.class); if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) { Feed feed = response.getBody(); Date lastUpdateInFeed = null; for (Entry entry : feed.getEntries()) { String applicationNumber = entry.getSummary().getValue(); if ((lastModified == null) || (entry.getUpdated().after(lastModified))) { log.info(applicationNumber + " is new, updating the status"); CreditApplicationStatus applicationStatus = repository.findByApplicationNumber(applicationNumber); if (applicationStatus != null) { applicationStatus.setApproved(true); repository.save(applicationStatus); } if ((lastUpdateInFeed == null) || (entry.getUpdated().after(lastUpdateInFeed))) { lastUpdateInFeed = entry.getUpdated(); } } } if (response.getHeaders().getFirst("Last-Modified") != null) { lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified")); log.info("LastModified header {}", lastModified); } else { if (lastUpdateInFeed != null) { lastModified = lastUpdateInFeed; log.info("Last in feed {}", lastModified); } } } }
private RundeckXO his2RundeckXO(SearchHit hit) { String version = (String) hit.getSource().get("version"); List<Map<String, Object>> assets = (List<Map<String, Object>>) hit.getSource().get("assets"); Map<String, Object> attributes = (Map<String, Object>) assets.get(0).get("attributes"); Map<String, Object> content = (Map<String, Object>) attributes.get("content"); String lastModifiedTime = "null"; if (content != null && content.containsKey("last_modified")) { Long lastModified = (Long) content.get("last_modified"); lastModifiedTime = DateUtils.formatDate(new Date(lastModified), "yyyy-MM-dd HH:mm:ss"); } return RundeckXO.builder().name(version + " (" + lastModifiedTime + ")").value(version).build(); }
private Date extractLastModified(final Artifact artifact, final String version, final List<String> repositoryUrls) throws IOException { for (final String repositoryUrl : repositoryUrls) { final URL url = new URL(generateUrl(artifact, version, repositoryUrl)); final URLConnection connection = url.openConnection(); String lastModified = connection.getHeaderField("Last-Modified"); if (lastModified != null) { // Once found, return. return DateUtils.parseDate(lastModified); } } return null; }
public void parse(final SetCookie cookie, final String value) throws MalformedCookieException { Args.notNull(cookie, "Cookie"); if (value == null) { throw new MalformedCookieException("Missing value for expires attribute"); } final Date expiry = DateUtils.parseDate(value, this.datepatterns); if (expiry == null) { throw new MalformedCookieException("Unable to parse expires attribute: " + value); } cookie.setExpiryDate(expiry); }
/** * Get last modified header value as date, will fall back to current time if header is not set * * @param response * the response of the image request * @return the last modification date */ protected Date getLastModifiedHeaderValue(CloseableHttpResponse response) { Header lastModifiedHeader = response.getLastHeader(HttpHeaders.LAST_MODIFIED); Date lastModified = null; if (lastModifiedHeader != null && lastModifiedHeader.getValue() != null) { lastModified = DateUtils.parseDate(lastModifiedHeader.getValue()); } if (lastModified == null) { // take current time rounded to seconds because Last-Modified has only second precision long now = (System.currentTimeMillis() / 1000) * 1000; lastModified = new Date(now); } return lastModified; }
@Test public void testSuitableForGETIfHeadResponseCachingEnabledAndEntryDoesNotSpecifyARequestMethodButContains204Response() { impl = new CachedResponseSuitabilityChecker(CacheConfig.custom().build()); final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Cache-Control", "max-age=3600") }; entry = HttpTestUtils.make204CacheEntryWithNoRequestMethod(headers); Assert.assertTrue(impl.canCachedResponseBeUsed(host, request, entry, now)); }
@Test public void testNotSuitableIfRequestHasNoCache() { request.addHeader("Cache-Control", "no-cache"); final Header[] headers = { new BasicHeader("Date", DateUtils.formatDate(tenSecondsAgo)), new BasicHeader("Cache-Control", "max-age=3600"), new BasicHeader("Content-Length","128") }; entry = getEntry(headers); Assert.assertFalse(impl.canCachedResponseBeUsed(host, request, entry, now)); }
private String buildReleaseFile(String distribution, Collection<String> architectures, String md5, String sha256) { Paragraph p = new Paragraph(Arrays.asList( new ControlFile.ControlField("Suite", distribution), new ControlFile.ControlField("Codename", distribution), new ControlFile.ControlField("Components", "main"), new ControlFile.ControlField("Date", DateUtils.formatDate(new Date())), new ControlFile.ControlField("Architectures", architectures.stream().collect(Collectors.joining(" "))), new ControlFile.ControlField("SHA256", sha256), new ControlFile.ControlField("MD5Sum", md5))); return p.toString(); }
/** * Find the "Date" response header and parse it into a java.util.Date * @return the Date value of the header or null if the header is not present */ private Date parseDate() { final Header dateHdr = getFirstHeader(HTTP.DATE_HEADER); if (dateHdr == null) { return null; } return DateUtils.parseDate(dateHdr.getValue()); }
@Test public void test303WithExplicitCachingHeadersUnderDefaultBehavior() { // RFC 2616 says: 303 should not be cached response.setStatusCode(HttpStatus.SC_SEE_OTHER); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Cache-Control","max-age=300"); Assert.assertFalse(policy.isResponseCacheable(request, response)); }
protected Date getExpirationDate(final HttpCacheEntry entry) { final Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES); if (expiresHeader == null) { return null; } return DateUtils.parseDate(expiresHeader.getValue()); }
@Test public void headsWithQueryParametersFrom1_1OriginsVia1_0ProxiesAreCacheableWithExpires() { policy = new ResponseCachingPolicy(0, true, false, false); request = new BasicHttpRequest("HEAD", "/foo?s=bar"); response = new BasicHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_OK, "OK"); response.setHeader("Date", DateUtils.formatDate(now)); response.setHeader("Expires", DateUtils.formatDate(tenSecondsFromNow)); response.setHeader("Via", "1.1 someproxy"); Assert.assertTrue(policy.isResponseCacheable(request, response)); }
private boolean hasValidDateField(final HttpRequest request, final String headerName) { for(final Header h : request.getHeaders(headerName)) { final Date date = DateUtils.parseDate(h.getValue()); return date != null; } return false; }
@Test public void testResponsesWithMultipleExpiresHeadersAreNotCacheableUsingSharedPublicCache() { policy = new ResponseCachingPolicy(0, true, false, false); request.setHeader("Authorization", "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="); response.setHeader("Cache-Control", "public"); response.addHeader("Expires", DateUtils.formatDate(now)); response.addHeader("Expires", DateUtils.formatDate(sixSecondsAgo)); Assert.assertFalse(policy.isResponseCacheable(request, response)); }
private boolean entryDateHeaderNewerThenResponse(final HttpCacheEntry entry, final HttpResponse response) { final Date entryDate = DateUtils.parseDate(entry.getFirstHeader(HTTP.DATE_HEADER) .getValue()); final Date responseDate = DateUtils.parseDate(response.getFirstHeader(HTTP.DATE_HEADER) .getValue()); if (entryDate == null || responseDate == null) { return false; } if (!entryDate.after(responseDate)) { return false; } return true; }
private boolean responseDateOlderThanEntryDate(final HttpResponse response, final HttpCacheEntry entry) { final Header entryDateHeader = entry.getFirstHeader(HTTP.DATE_HEADER); final Header responseDateHeader = response.getFirstHeader(HTTP.DATE_HEADER); if (entryDateHeader == null || responseDateHeader == null) { /* be conservative; should probably flush */ return false; } final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue()); final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue()); if (entryDate == null || responseDate == null) { return false; } return responseDate.before(entryDate); }
protected void consumeWarnDate() { final int curr = offs; final Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs)); if (!m.lookingAt()) { parseError(); } offs += m.end(); warnDate = DateUtils.parseDate(src.substring(curr+1,offs-1)); }
@Test public void testHEADResponseWithUpdatedLastModifiedFieldMakeACacheEntryStale() throws Exception { final Date now = new Date(); final Date tenSecondsAgo = new Date(now.getTime() - 10 * 1000L); final Date sixSecondsAgo = new Date(now.getTime() - 6 * 1000L); testHEADResponseWithUpdatedEntityFieldsMakeACacheEntryStale("Last-Modified", DateUtils .formatDate(tenSecondsAgo), DateUtils.formatDate(sixSecondsAgo)); }