1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.httpclient;
16
17 import java.util.Date;
18 import java.util.regex.Pattern;
19
20 import org.apache.http.cookie.MalformedCookieException;
21 import org.apache.http.cookie.SetCookie;
22 import org.apache.http.impl.cookie.BasicMaxAgeHandler;
23 import org.apache.http.util.Args;
24
25
26
27
28
29
30
31 final class HtmlUnitMaxAgeHandler extends BasicMaxAgeHandler {
32
33
34
35 private static final int MAX_MAX_AGE = 400 * 24 * 60 * 60;
36
37 private static final Pattern MAX_AGE_PATTERN = Pattern.compile("-?[0-9]+");
38
39 @Override
40 public void parse(final SetCookie cookie, final String value)
41 throws MalformedCookieException {
42 Args.notNull(cookie, "Cookie");
43 if (value == null || value.isEmpty()) {
44 throw new MalformedCookieException("Missing value for 'max-age' attribute");
45 }
46 if (!MAX_AGE_PATTERN.matcher(value).matches()) {
47 throw new MalformedCookieException("Invalid 'max-age' attribute: " + value);
48 }
49 if (value.startsWith("-")) {
50 cookie.setExpiryDate(new Date(0L));
51 return;
52 }
53 int age;
54 try {
55 age = Math.min(Integer.parseInt(value), MAX_MAX_AGE);
56 }
57 catch (final NumberFormatException e) {
58 age = MAX_MAX_AGE;
59 }
60 cookie.setExpiryDate(new Date(System.currentTimeMillis() + age * 1000L));
61 }
62
63 }