下面列出了 io.netty.handler.codec.DateFormatter # parseHttpDate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testEncodingSingleCookieV0() throws ParseException {
int maxAge = 50;
String result =
"myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere; Domain=.adomainsomewhere; Secure";
Cookie cookie = new DefaultCookie("myCookie", "myValue");
cookie.setDomain(".adomainsomewhere");
cookie.setMaxAge(maxAge);
cookie.setPath("/apathsomewhere");
cookie.setSecure(true);
String encodedCookie = ServerCookieEncoder.STRICT.encode(cookie);
Matcher matcher = Pattern.compile(result).matcher(encodedCookie);
assertTrue(matcher.find());
Date expiresDate = DateFormatter.parseHttpDate(matcher.group(1));
long diff = (expiresDate.getTime() - System.currentTimeMillis()) / 1000;
// 2 secs should be fine
assertTrue(Math.abs(diff - maxAge) <= 2);
}
@Nullable
private static Long toTimeMillis(@Nullable String v) {
if (v == null) {
return null;
}
try {
@SuppressWarnings("UseOfObsoleteDateTimeApi")
final Date date = DateFormatter.parseHttpDate(v);
return date != null ? date.getTime() : null;
} catch (Exception ignore) {
// `parseHttpDate()` can raise an exception rather than returning `null`
// when the given value has more than 64 characters.
return null;
}
}
@Override
public long convertToTimeMillis(String value) {
@SuppressWarnings("UseOfObsoleteDateTimeApi")
Date date = null;
try {
date = DateFormatter.parseHttpDate(value);
} catch (Exception ignored) {
// `parseHttpDate()` can raise an exception rather than returning `null`
// when the given value has more than 64 characters.
}
if (date == null) {
throw new IllegalArgumentException("not a date: " + value);
}
return date.getTime();
}
@Test
public void testEncodingSingleCookieV0() throws ParseException {
final int maxAge = 50;
final String result = "myCookie=myValue; Max-Age=50; Expires=(.+?); Path=/apathsomewhere; " +
"Domain=.adomainsomewhere; Secure; SameSite=Strict";
final Cookie cookie = Cookie.builder("myCookie", "myValue")
.domain(".adomainsomewhere")
.maxAge(maxAge)
.path("/apathsomewhere")
.secure(true)
.sameSite("Strict")
.build();
final String encodedCookie = cookie.toSetCookieHeader();
final Matcher matcher = Pattern.compile(result).matcher(encodedCookie);
assertThat(matcher.find()).isTrue();
final Date expiresDate = DateFormatter.parseHttpDate(matcher.group(1));
final long diff = (expiresDate.getTime() - System.currentTimeMillis()) / 1000;
// 2 secs should be fine
assertThat(Math.abs(diff - maxAge)).isLessThanOrEqualTo(2);
}
private long mergeMaxAgeAndExpires() {
// max age has precedence over expires
if (maxAge != Long.MIN_VALUE) {
return maxAge;
} else if (isValueDefined(expiresStart, expiresEnd)) {
Date expiresDate = DateFormatter.parseHttpDate(header, expiresStart, expiresEnd);
if (expiresDate != null) {
long maxAgeMillis = expiresDate.getTime() - System.currentTimeMillis();
return maxAgeMillis / 1000 + (maxAgeMillis % 1000 != 0 ? 1 : 0);
}
}
return Long.MIN_VALUE;
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence)} instead.
*
* Returns the date header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value
* @throws ParseException
* if there is no such header or the header value is not a formatted date
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name) throws ParseException {
String value = message.headers().get(name);
if (value == null) {
throw new ParseException("header not found: " + name, 0);
}
Date date = DateFormatter.parseHttpDate(value);
if (date == null) {
throw new ParseException("header can't be parsed into a Date: " + value, 0);
}
return date;
}
private long mergeMaxAgeAndExpires() {
// max age has precedence over expires
if (maxAge != Long.MIN_VALUE) {
return maxAge;
} else if (isValueDefined(expiresStart, expiresEnd)) {
Date expiresDate = DateFormatter.parseHttpDate(header, expiresStart, expiresEnd);
if (expiresDate != null) {
long maxAgeMillis = expiresDate.getTime() - System.currentTimeMillis();
return maxAgeMillis / 1000 + (maxAgeMillis % 1000 != 0 ? 1 : 0);
}
}
return Long.MIN_VALUE;
}
private static void mergeMaxAgeAndExpires(CookieBuilder builder, String header) {
// max age has precedence over expires
if (builder.maxAge != Cookie.UNDEFINED_MAX_AGE) {
return;
}
if (isValueDefined(builder.expiresStart, builder.expiresEnd)) {
final Date expiresDate =
DateFormatter.parseHttpDate(header, builder.expiresStart, builder.expiresEnd);
if (expiresDate != null) {
final long maxAgeMillis = expiresDate.getTime() - System.currentTimeMillis();
builder.maxAge(maxAgeMillis / 1000 + (maxAgeMillis % 1000 != 0 ? 1 : 0));
}
}
}
private static void assert200Ok(CloseableHttpResponse res,
@Nullable String expectedContentType,
Consumer<String> contentAssertions) throws Exception {
assertStatusLine(res, "HTTP/1.1 200 OK");
// Ensure that the 'Date' header exists and is well-formed.
final String date = headerOrNull(res, HttpHeaders.DATE);
assertThat(date).isNotNull();
DateFormatter.parseHttpDate(date);
// Ensure that the 'Last-Modified' header exists and is well-formed.
final String lastModified = headerOrNull(res, HttpHeaders.LAST_MODIFIED);
assertThat(lastModified).isNotNull();
DateFormatter.parseHttpDate(lastModified);
// Ensure that the 'ETag' header exists and is well-formed.
final String entityTag = headerOrNull(res, HttpHeaders.ETAG);
assertThat(entityTag).matches(ETAG_PATTERN);
// Ensure the content type is correct.
if (expectedContentType != null) {
assertThat(headerOrNull(res, HttpHeaders.CONTENT_TYPE)).startsWith(expectedContentType);
} else {
assertThat(res.containsHeader(HttpHeaders.CONTENT_TYPE)).isFalse();
}
// Ensure the content satisfies the condition.
contentAssertions.accept(EntityUtils.toString(res.getEntity()).trim());
}
/**
* @deprecated Use {@link #getTimeMillis(CharSequence, long)} instead.
*
* Returns the date header value with the specified header name. If
* there are more than one header value for the specified header name, the
* first value is returned.
*
* @return the header value or the {@code defaultValue} if there is no such
* header or the header value is not a formatted date
*/
@Deprecated
public static Date getDateHeader(HttpMessage message, CharSequence name, Date defaultValue) {
final String value = getHeader(message, name);
Date date = DateFormatter.parseHttpDate(value);
return date != null ? date : defaultValue;
}