Java Code Examples for io.netty.handler.codec.DateFormatter#parseHttpDate()

The following examples show how to use io.netty.handler.codec.DateFormatter#parseHttpDate() . 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: ServerCookieEncoderTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 2
Source File: StringMultimap.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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;
    }
}
 
Example 3
Source File: StringValueConverter.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example 4
Source File: ServerCookieEncoderTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 5
Source File: ClientCookieDecoder.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 6
Source File: HttpHeaders.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
/**
 * @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;
}
 
Example 7
Source File: ClientCookieDecoder.java    From styx with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: ClientCookieDecoder.java    From armeria with Apache License 2.0 5 votes vote down vote up
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));
        }
    }
}
 
Example 9
Source File: FileServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example 10
Source File: HttpHeaders.java    From netty-4.1.22 with Apache License 2.0 3 votes vote down vote up
/**
 * @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;
}