1
2
3
4
5
6
7
8
9
10
11
12
13
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.Iterator;
21 import java.util.LinkedHashSet;
22 import java.util.Objects;
23 import java.util.Set;
24
25 import org.htmlunit.util.Cookie;
26
27
28
29
30
31
32
33
34
35
36
37
38 public class CookieManager implements Serializable {
39
40
41 private boolean cookiesEnabled_;
42
43
44 private final Set<Cookie> cookies_ = new LinkedHashSet<>();
45
46
47
48
49 public CookieManager() {
50 cookiesEnabled_ = true;
51 }
52
53
54
55
56
57 public synchronized void setCookiesEnabled(final boolean enabled) {
58 cookiesEnabled_ = enabled;
59 }
60
61
62
63
64
65 public synchronized boolean isCookiesEnabled() {
66 return cookiesEnabled_;
67 }
68
69
70
71
72
73
74 public synchronized Set<Cookie> getCookies() {
75 if (!isCookiesEnabled()) {
76 return Collections.emptySet();
77 }
78
79 final Set<Cookie> copy = new LinkedHashSet<>(cookies_);
80 return Collections.unmodifiableSet(copy);
81 }
82
83
84
85
86
87
88
89 public synchronized boolean clearExpired(final Date date) {
90 if (!isCookiesEnabled()) {
91 return false;
92 }
93
94 if (date == null) {
95 return false;
96 }
97
98 boolean foundExpired = false;
99 for (final Iterator<Cookie> iter = cookies_.iterator(); iter.hasNext();) {
100 final Cookie cookie = iter.next();
101 if (cookie.getExpires() != null && date.after(cookie.getExpires())) {
102 iter.remove();
103 foundExpired = true;
104 }
105 }
106 return foundExpired;
107 }
108
109
110
111
112
113
114
115 public synchronized Cookie getCookie(final String name) {
116 if (!isCookiesEnabled()) {
117 return null;
118 }
119
120 for (final Cookie cookie : cookies_) {
121 if (Objects.equals(cookie.getName(), name)) {
122 return cookie;
123 }
124 }
125 return null;
126 }
127
128
129
130
131
132
133 public synchronized void addCookie(final Cookie cookie) {
134 if (!isCookiesEnabled()) {
135 return;
136 }
137
138 cookies_.remove(cookie);
139
140
141 if (cookie.getExpires() == null || cookie.getExpires().after(new Date())) {
142 cookies_.add(cookie);
143 }
144 }
145
146
147
148
149
150
151 public synchronized void removeCookie(final Cookie cookie) {
152 if (!isCookiesEnabled()) {
153 return;
154 }
155
156 cookies_.remove(cookie);
157 }
158
159
160
161
162
163 public synchronized void clearCookies() {
164 if (!isCookiesEnabled()) {
165 return;
166 }
167
168 cookies_.clear();
169 }
170 }