Java 类org.apache.http.client.utils.DateUtils 实例源码

项目:microservice-atom    文件:InvoicePoller.java   
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");
    }
}
项目:microservice-atom    文件:AtomClientTest.java   
@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());
}
项目:microservice-atom    文件:ShippingPoller.java   
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");
    }
}
项目:metrics-aggregator-daemon    文件:UriTrigger.java   
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;
}
项目:purecloud-iot    文件:CachingExec.java   
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;
}
项目:purecloud-iot    文件:CachingExec.java   
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);
}
项目:purecloud-iot    文件:ResponseCachingPolicy.java   
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);
}
项目:purecloud-iot    文件:TestBasicHttpCache.java   
@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));
}
项目:purecloud-iot    文件:TestProtocolRecommendations.java   
@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());
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@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);
}
项目:purecloud-iot    文件:TestBasicHttpCache.java   
@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));
}
项目:purecloud-iot    文件:TestCacheInvalidator.java   
@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);
}
项目:purecloud-iot    文件:TestProtocolRecommendations.java   
@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));
}
项目:purecloud-iot    文件:TestProtocolRecommendations.java   
@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));
}
项目:purecloud-iot    文件:TestBasicHttpCache.java   
@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));
}
项目:purecloud-iot    文件:TestProtocolRequirements.java   
@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"));
    }
}
项目:purecloud-iot    文件:TestCachingExecChain.java   
@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());

}
项目:purecloud-iot    文件:TestCacheEntryUpdater.java   
@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");
}
项目:purecloud-iot    文件:TestProtocolRequirements.java   
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();
    }
项目:purecloud-iot    文件:TestCacheEntryUpdater.java   
@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\"");
}
项目:Reer    文件:HttpResponseResource.java   
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;
    }
}
项目:jspider    文件:NoopCookieSpecProvider.java   
@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
        }
    };
}
项目:event-driven-spring-boot    文件:CreditDecisionPoller.java   
@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);
            }

        }
    }
}
项目:nexus3-rundeck-plugin    文件:RundeckMavenResource.java   
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();
}
项目:versiondebt-plugin    文件:VersiondebtMojo.java   
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;
}
项目:remote-files-sync    文件:BasicExpiresHandlerHC4.java   
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);
}
项目:communote-server    文件:HttpExternalImageProvider.java   
/**
 * 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;
}
项目:purecloud-iot    文件:TestCachedResponseSuitabilityChecker.java   
@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));
}
项目:purecloud-iot    文件:TestCachedResponseSuitabilityChecker.java   
@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));
}
项目:nexus-repository-apt    文件:AptHostedFacet.java   
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();
}
项目:purecloud-iot    文件:HttpCacheEntry.java   
/**
 * 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());
}
项目:purecloud-iot    文件:TestResponseCachingPolicy.java   
@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));
}
项目:purecloud-iot    文件:CacheValidityPolicy.java   
protected Date getExpirationDate(final HttpCacheEntry entry) {
    final Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
    if (expiresHeader == null) {
        return null;
    }
    return DateUtils.parseDate(expiresHeader.getValue());
}
项目:purecloud-iot    文件:TestResponseCachingPolicy.java   
@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));
}
项目:purecloud-iot    文件:CachedResponseSuitabilityChecker.java   
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;
}
项目:purecloud-iot    文件:TestResponseCachingPolicy.java   
@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));
}
项目:purecloud-iot    文件:CacheEntryUpdater.java   
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;
}
项目:purecloud-iot    文件:CacheInvalidator.java   
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);
}
项目:purecloud-iot    文件:WarningValue.java   
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));
}
项目:purecloud-iot    文件:TestProtocolRequirements.java   
@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));
}