View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
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   * Customized BasicMaxAgeHandler for HtmlUnit.
27   *
28   * @author Ronald Brill
29   * @author Lai Quang Duong
30   */
31  final class HtmlUnitMaxAgeHandler extends BasicMaxAgeHandler {
32  
33      // Max-Age should be 400 days at most
34      // https://httpwg.org/http-extensions/draft-ietf-httpbis-rfc6265bis.html#section-5.5
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  }