Java Code Examples for org.apache.http.impl.cookie.DateUtils#parseDate()

The following examples show how to use org.apache.http.impl.cookie.DateUtils#parseDate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CacheHeaderTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@SuppressForbidden(reason = "Needs currentTimeMillis to check against expiry headers from Solr")
protected void checkVetoHeaders(HttpResponse response, boolean checkExpires) throws Exception {
  Header head = response.getFirstHeader("Cache-Control");
  assertNotNull("We got no Cache-Control header", head);
  assertTrue("We got no no-cache in the Cache-Control header ["+head+"]", head.getValue().contains("no-cache"));
  assertTrue("We got no no-store in the Cache-Control header ["+head+"]", head.getValue().contains("no-store"));

  head = response.getFirstHeader("Pragma");
  assertNotNull("We got no Pragma header", head);
  assertEquals("no-cache", head.getValue());

  if (checkExpires) {
    head = response.getFirstHeader("Expires");
    assertNotNull("We got no Expires header:" + Arrays.asList(response.getAllHeaders()), head);
    Date d = DateUtils.parseDate(head.getValue());
    assertTrue("We got no Expires header far in the past", System
        .currentTimeMillis()
        - d.getTime() > 100000);
  }
}
 
Example 2
Source File: CacheEntryUpdater.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
private boolean entryDateHeaderNewerThenResponse(HttpCacheEntry entry,
		HttpResponse response) {
	try {
		Date entryDate = DateUtils.parseDate(entry.getFirstHeader(
				HTTP.DATE_HEADER).getValue());
		Date responseDate = DateUtils.parseDate(response.getFirstHeader(
				HTTP.DATE_HEADER).getValue());

		if (!entryDate.after(responseDate)) {
			return false;
		}
	} catch (DateParseException e) {
		return false;
	}

	return true;
}
 
Example 3
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 6 votes vote down vote up
private boolean alreadyHaveNewerCacheEntry(HttpHost target,
		HttpRequest request, HttpResponse backendResponse)
		throws IOException {
	HttpCacheEntry existing = null;
	try {
		existing = responseCache.getCacheEntry(target, request);
	} catch (IOException ioe) {
		// nop
	}
	if (existing == null)
		return false;
	Header entryDateHeader = existing.getFirstHeader("Date");
	if (entryDateHeader == null)
		return false;
	Header responseDateHeader = backendResponse.getFirstHeader("Date");
	if (responseDateHeader == null)
		return false;
	try {
		Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
		Date responseDate = DateUtils.parseDate(responseDateHeader
				.getValue());
		return responseDate.before(entryDate);
	} catch (DateParseException e) {
	}
	return false;
}
 
Example 4
Source File: CacheValidityPolicy.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
protected Date getDateValue(final HttpCacheEntry entry) {
	Header dateHdr = entry.getFirstHeader(HTTP.DATE_HEADER);
	if (dateHdr == null)
		return null;
	try {
		return DateUtils.parseDate(dateHdr.getValue());
	} catch (DateParseException dpe) {
		// ignore malformed date
	}
	return null;
}
 
Example 5
Source File: CacheValidityPolicy.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
protected Date getLastModifiedValue(final HttpCacheEntry entry) {
	Header dateHdr = entry.getFirstHeader(HeaderConstants.LAST_MODIFIED);
	if (dateHdr == null)
		return null;
	try {
		return DateUtils.parseDate(dateHdr.getValue());
	} catch (DateParseException dpe) {
		// ignore malformed date
	}
	return null;
}
 
Example 6
Source File: CacheValidityPolicy.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
protected Date getExpirationDate(final HttpCacheEntry entry) {
	Header expiresHeader = entry.getFirstHeader(HeaderConstants.EXPIRES);
	if (expiresHeader == null)
		return null;
	try {
		return DateUtils.parseDate(expiresHeader.getValue());
	} catch (DateParseException dpe) {
		// malformed expires header
	}
	return null;
}
 
Example 7
Source File: CachedResponseSuitabilityChecker.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
private boolean hasValidDateField(HttpRequest request, String headerName) {
	for (Header h : request.getHeaders(headerName)) {
		try {
			DateUtils.parseDate(h.getValue());
			return true;
		} catch (DateParseException dpe) {
			// ignore malformed dates
		}
	}
	return false;
}
 
Example 8
Source File: WarningValue.java    From apigee-android-sdk with Apache License 2.0 5 votes vote down vote up
protected void consumeWarnDate() {
	int curr = offs;
	Matcher m = WARN_DATE_PATTERN.matcher(src.substring(offs));
	if (!m.lookingAt())
		parseError();
	offs += m.end();
	try {
		warnDate = DateUtils.parseDate(src.substring(curr + 1, offs - 1));
	} catch (DateParseException e) {
		throw new IllegalStateException("couldn't parse a parseable date");
	}
}
 
Example 9
Source File: CacheHeaderTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
protected void doLastModified(String method) throws Exception {
  // We do a first request to get the last modified
  // This must result in a 200 OK response
  HttpRequestBase get = getSelectMethod(method);
  HttpResponse response = getClient().execute(get);
  checkResponseBody(method, response);

  assertEquals("Got no response code 200 in initial request", 200, response.
      getStatusLine().getStatusCode());

  Header head = response.getFirstHeader("Last-Modified");
  assertNotNull("We got no Last-Modified header", head);

  Date lastModified = DateUtils.parseDate(head.getValue());

  // If-Modified-Since tests
  get = getSelectMethod(method);
  get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date()));

  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("Expected 304 NotModified response with current date", 304,
      response.getStatusLine().getStatusCode());

  get = getSelectMethod(method);
  get.addHeader("If-Modified-Since", DateUtils.formatDate(new Date(
      lastModified.getTime() - 10000)));
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals("Expected 200 OK response with If-Modified-Since in the past",
      200, response.getStatusLine().getStatusCode());

  // If-Unmodified-Since tests
  get = getSelectMethod(method);
  get.addHeader("If-Unmodified-Since", DateUtils.formatDate(new Date(
      lastModified.getTime() - 10000)));

  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "Expected 412 Precondition failed with If-Unmodified-Since in the past",
      412, response.getStatusLine().getStatusCode());

  get = getSelectMethod(method);
  get.addHeader("If-Unmodified-Since", DateUtils
          .formatDate(new Date()));
  response = getClient().execute(get);
  checkResponseBody(method, response);
  assertEquals(
      "Expected 200 OK response with If-Unmodified-Since and current date",
      200, response.getStatusLine().getStatusCode());
}
 
Example 10
Source File: ResponseCachingPolicy.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
/**
 * Determines if an HttpResponse can be cached.
 * 
 * @param httpMethod
 *            What type of request was this, a GET, PUT, other?
 * @param response
 *            The origin response
 * @return <code>true</code> if response is cacheable
 */
public boolean isResponseCacheable(String httpMethod, HttpResponse response) {
	boolean cacheable = false;

	if (!HeaderConstants.GET_METHOD.equals(httpMethod)) {
		log.debug("Response was not cacheable.");
		return false;
	}

	switch (response.getStatusLine().getStatusCode()) {
	case HttpStatus.SC_OK:
	case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
	case HttpStatus.SC_MULTIPLE_CHOICES:
	case HttpStatus.SC_MOVED_PERMANENTLY:
	case HttpStatus.SC_GONE:
		// these response codes MAY be cached
		cacheable = true;
		log.debug("Response was cacheable");
		break;
	case HttpStatus.SC_PARTIAL_CONTENT:
		// we don't implement Range requests and hence are not
		// allowed to cache partial content
		log.debug("Response was not cacheable (Partial Content)");
		return cacheable;

	default:
		// If the status code is not one of the recognized
		// available codes in HttpStatus Don't Cache
		log.debug("Response was not cacheable (Unknown Status code)");
		return cacheable;
	}

	Header contentLength = response.getFirstHeader(HTTP.CONTENT_LEN);
	if (contentLength != null) {
		int contentLengthValue = Integer.parseInt(contentLength.getValue());
		if (contentLengthValue > this.maxObjectSizeBytes)
			return false;
	}

	Header[] ageHeaders = response.getHeaders(HeaderConstants.AGE);

	if (ageHeaders.length > 1)
		return false;

	Header[] expiresHeaders = response.getHeaders(HeaderConstants.EXPIRES);

	if (expiresHeaders.length > 1)
		return false;

	Header[] dateHeaders = response.getHeaders(HTTP.DATE_HEADER);

	if (dateHeaders.length != 1)
		return false;

	try {
		DateUtils.parseDate(dateHeaders[0].getValue());
	} catch (DateParseException dpe) {
		return false;
	}

	for (Header varyHdr : response.getHeaders(HeaderConstants.VARY)) {
		for (HeaderElement elem : varyHdr.getElements()) {
			if ("*".equals(elem.getName())) {
				return false;
			}
		}
	}

	if (isExplicitlyNonCacheable(response))
		return false;

	return (cacheable || isExplicitlyCacheable(response));
}
 
Example 11
Source File: CachingHttpClient.java    From apigee-android-sdk with Apache License 2.0 4 votes vote down vote up
HttpResponse revalidateCacheEntry(HttpHost target, HttpRequest request,
		HttpContext context, HttpCacheEntry cacheEntry) throws IOException,
		ProtocolException {
	HttpRequest conditionalRequest = conditionalRequestBuilder
			.buildConditionalRequest(request, cacheEntry);

	Date requestDate = getCurrentDate();
	HttpResponse backendResponse = backend.execute(target,
			conditionalRequest, context);
	Date responseDate = getCurrentDate();

	final Header entryDateHeader = cacheEntry.getFirstHeader("Date");
	final Header responseDateHeader = backendResponse
			.getFirstHeader("Date");
	if (entryDateHeader != null && responseDateHeader != null) {
		try {
			Date entryDate = DateUtils
					.parseDate(entryDateHeader.getValue());
			Date respDate = DateUtils.parseDate(responseDateHeader
					.getValue());
			if (respDate.before(entryDate)) {
				HttpRequest unconditional = conditionalRequestBuilder
						.buildUnconditionalRequest(request, cacheEntry);
				requestDate = getCurrentDate();
				backendResponse = backend.execute(target, unconditional,
						context);
				responseDate = getCurrentDate();
			}
		} catch (DateParseException e) {
			// 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.
		}
	}

	backendResponse.addHeader("Via", generateViaHeader(backendResponse));

	int statusCode = backendResponse.getStatusLine().getStatusCode();
	if (statusCode == HttpStatus.SC_NOT_MODIFIED
			|| statusCode == HttpStatus.SC_OK) {
		cacheUpdates.getAndIncrement();
		setResponseStatus(context, CacheResponseStatus.VALIDATED);
	}

	if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
		HttpCacheEntry updatedEntry = responseCache.updateCacheEntry(
				target, request, cacheEntry, backendResponse, requestDate,
				responseDate);
		if (suitabilityChecker.isConditional(request)
				&& suitabilityChecker.allConditionalsMatch(request,
						updatedEntry, new Date())) {
			return responseGenerator
					.generateNotModifiedResponse(updatedEntry);
		}
		return responseGenerator.generateResponse(updatedEntry);
	}

	return handleBackendResponse(target, conditionalRequest, requestDate,
			responseDate, backendResponse);
}