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;
16  
17  import java.io.Serializable;
18  import java.util.Collections;
19  import java.util.Date;
20  import java.util.LinkedHashSet;
21  import java.util.Objects;
22  import java.util.Set;
23  import java.util.concurrent.locks.ReentrantReadWriteLock;
24  
25  import org.htmlunit.http.Cookie;
26  
27  /**
28   * Manages cookies for a {@link WebClient}.
29   *
30   * <p>This class is thread-safe: all mutator and accessor operations are
31   * protected via a {@link ReentrantReadWriteLock}.
32   * </p>
33   *
34   * <p>Cookie support can be turned off via {@link #setCookiesEnabled(boolean)}.
35   * While disabled, this manager ignores all cookie operations: additions and
36   * removals become no-ops, and accessors behave as if the cookie store were
37   * empty. Subclasses that override these methods must preserve this contract.
38   * </p>
39   *
40   * @author Daniel Gredler
41   * @author Ahmed Ashour
42   * @author Nicolas Belisle
43   * @author Ronald Brill
44   * @author Vidya m
45   */
46  public class CookieManager implements Serializable {
47  
48      private final ReentrantReadWriteLock lock_ = new ReentrantReadWriteLock();
49  
50      /** Whether or not cookies are enabled. */
51      private boolean cookiesEnabled_;
52  
53      /** The cookies added to this cookie manager. */
54      private final Set<Cookie> cookies_ = new LinkedHashSet<>();
55  
56      /**
57       * Creates a new instance.
58       */
59      public CookieManager() {
60          cookiesEnabled_ = true;
61      }
62  
63      /**
64       * Enables or disables cookie support. Cookies are enabled by default.
65       * Disabling does not clear existing cookies; it only suppresses all
66       * cookie operations until re-enabled.
67       *
68       * @param enabled {@code true} to enable cookie support, {@code false} to disable it
69       */
70      public void setCookiesEnabled(final boolean enabled) {
71          lock_.writeLock().lock();
72          try {
73              cookiesEnabled_ = enabled;
74          }
75          finally {
76              lock_.writeLock().unlock();
77          }
78      }
79  
80      /**
81       * Returns {@code true} if cookies are enabled. Cookies are enabled by default.
82       *
83       * @return {@code true} if cookies are enabled, {@code false} otherwise
84       */
85      public boolean isCookiesEnabled() {
86          lock_.readLock().lock();
87          try {
88              return cookiesEnabled_;
89          }
90          finally {
91              lock_.readLock().unlock();
92          }
93      }
94  
95      /**
96       * Returns a snapshot of the currently configured cookies as an
97       * unmodifiable set. The returned set is a copy and will not reflect
98       * later changes to this manager's cookie store.
99       *
100      * @return the currently configured cookies, in an unmodifiable set;
101      *         empty if cookie support is disabled
102      */
103     public Set<Cookie> getCookies() {
104         lock_.readLock().lock();
105         try {
106             if (!cookiesEnabled_) {
107                 return Collections.emptySet();
108             }
109 
110             final Set<Cookie> copy = new LinkedHashSet<>(cookies_);
111             return Collections.unmodifiableSet(copy);
112         }
113         finally {
114             lock_.readLock().unlock();
115         }
116     }
117 
118     /**
119      * Removes all cookies whose expiration date is strictly before the
120      * given date. A cookie expiring at exactly {@code date} is not
121      * considered expired by this comparison (consistent with RFC 6265's
122      * treatment of cookie expiry).
123      *
124      * @param date the date to compare against; if {@code null}, this method
125      *             does nothing and returns {@code false}
126      * @return {@code true} if one or more cookies were found expired and removed;
127      *         {@code false} otherwise, or if cookie support is disabled
128      */
129     public boolean clearExpired(final Date date) {
130         lock_.writeLock().lock();
131         try {
132             if (!cookiesEnabled_ || date == null) {
133                 return false;
134             }
135 
136             return cookies_.removeIf(cookie ->
137                 cookie.getExpires() != null && date.after(cookie.getExpires()));
138         }
139         finally {
140             lock_.writeLock().unlock();
141         }
142     }
143 
144     /**
145      * Returns the currently configured cookie with the specified name, or
146      * {@code null} if none exists. If multiple stored cookies happen to
147      * share a name (e.g., differing by domain or path), the first match
148      * encountered in iteration order is returned.
149      *
150      * @param name the cookie name to look up; may be {@code null}
151      * @return the matching cookie, or {@code null} if none exists or cookie
152      *         support is disabled
153      */
154     public Cookie getCookie(final String name) {
155         lock_.readLock().lock();
156         try {
157             if (!cookiesEnabled_) {
158                 return null;
159             }
160 
161             for (final Cookie cookie : cookies_) {
162                 if (Objects.equals(cookie.getName(), name)) {
163                     return cookie;
164                 }
165             }
166             return null;
167         }
168         finally {
169             lock_.readLock().unlock();
170         }
171     }
172 
173     /**
174      * Adds the specified cookie, replacing any existing cookie considered
175      * equal to it. If the cookie is already expired relative to the current
176      * time, it replaces the old entry (if any) but is not itself re-added —
177      * this is the mechanism by which a cookie can be deleted by supplying a
178      * past expiration date, per RFC 6265.
179      *
180      * @param cookie the cookie to add
181      */
182     public void addCookie(final Cookie cookie) {
183         lock_.writeLock().lock();
184         try {
185             if (!cookiesEnabled_) {
186                 return;
187             }
188 
189             cookies_.remove(cookie);
190 
191             // don't add expired cookie
192             if (cookie.getExpires() == null || cookie.getExpires().after(new Date())) {
193                 cookies_.add(cookie);
194             }
195         }
196         finally {
197             lock_.writeLock().unlock();
198         }
199     }
200 
201     /**
202      * Removes the specified cookie, if present. Does nothing if cookie support
203      * is disabled.
204      *
205      * @param cookie the cookie to remove; may be {@code null}, in which case
206      *               this method does nothing
207      */
208     public void removeCookie(final Cookie cookie) {
209         lock_.writeLock().lock();
210         try {
211             if (!cookiesEnabled_) {
212                 return;
213             }
214 
215             cookies_.remove(cookie);
216         }
217         finally {
218             lock_.writeLock().unlock();
219         }
220     }
221 
222     /**
223      * Removes all cookies from this manager. Does nothing if cookie support
224      * is disabled.
225      */
226     public void clearCookies() {
227         lock_.writeLock().lock();
228         try {
229             if (!cookiesEnabled_) {
230                 return;
231             }
232 
233             cookies_.clear();
234         }
235         finally {
236             lock_.writeLock().unlock();
237         }
238     }
239 }