1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27 package org.apache.http.impl.client;
28
29 import java.io.IOException;
30 import java.io.ObjectInputStream;
31 import java.io.Serializable;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.Iterator;
35 import java.util.List;
36 import java.util.TreeSet;
37 import java.util.concurrent.locks.ReadWriteLock;
38 import java.util.concurrent.locks.ReentrantReadWriteLock;
39
40 import org.apache.http.annotation.Contract;
41 import org.apache.http.annotation.ThreadingBehavior;
42 import org.apache.http.client.CookieStore;
43 import org.apache.http.cookie.Cookie;
44 import org.apache.http.cookie.CookieIdentityComparator;
45
46
47
48
49
50
51
52 @Contract(threading = ThreadingBehavior.SAFE)
53 public class BasicCookieStore implements CookieStore, Serializable {
54
55 private static final long serialVersionUID = -7581093305228232025L;
56
57 private final TreeSet<Cookie> cookies;
58 private transient ReadWriteLock lock;
59
60 public BasicCookieStore() {
61 super();
62 this.cookies = new TreeSet<Cookie>(new CookieIdentityComparator());
63 this.lock = new ReentrantReadWriteLock();
64 }
65
66 private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
67 stream.defaultReadObject();
68
69
70 this.lock = new ReentrantReadWriteLock();
71 }
72
73
74
75
76
77
78
79
80
81
82
83 @Override
84 public void addCookie(final Cookie cookie) {
85 if (cookie != null) {
86 lock.writeLock().lock();
87 try {
88
89 cookies.remove(cookie);
90 if (!cookie.isExpired(new Date())) {
91 cookies.add(cookie);
92 }
93 } finally {
94 lock.writeLock().unlock();
95 }
96 }
97 }
98
99
100
101
102
103
104
105
106
107
108
109 public void addCookies(final Cookie[] cookies) {
110 if (cookies != null) {
111 for (final Cookie cookie : cookies) {
112 this.addCookie(cookie);
113 }
114 }
115 }
116
117
118
119
120
121
122
123 @Override
124 public List<Cookie> getCookies() {
125 lock.readLock().lock();
126 try {
127
128 return new ArrayList<Cookie>(cookies);
129 } finally {
130 lock.readLock().unlock();
131 }
132 }
133
134
135
136
137
138
139
140
141
142 @Override
143 public boolean clearExpired(final Date date) {
144 if (date == null) {
145 return false;
146 }
147 lock.writeLock().lock();
148 try {
149 boolean removed = false;
150 for (final Iterator<Cookie> it = cookies.iterator(); it.hasNext(); ) {
151 if (it.next().isExpired(date)) {
152 it.remove();
153 removed = true;
154 }
155 }
156 return removed;
157 } finally {
158 lock.writeLock().unlock();
159 }
160 }
161
162
163
164
165 @Override
166 public void clear() {
167 lock.writeLock().lock();
168 try {
169 cookies.clear();
170 } finally {
171 lock.writeLock().unlock();
172 }
173 }
174
175 @Override
176 public String toString() {
177 lock.readLock().lock();
178 try {
179 return cookies.toString();
180 } finally {
181 lock.readLock().unlock();
182 }
183 }
184
185 }