Make sure to synchronize in addCookie now that domain count limits are imposed and modify unit test to also take into account domain limits

This commit is contained in:
Hunter Stern
2015-10-16 17:12:42 -07:00
parent d9684e913b
commit 44ac1030f2
2 changed files with 40 additions and 24 deletions
@@ -136,28 +136,30 @@ public class BdbCookieStore extends AbstractCookieStore implements
}
public void addCookie(Cookie cookie) {
if (isCookieCountMaxedForDomain(cookie.getDomain())) {
logger.log(
Level.FINEST,
"Maximum number of cookies reached for domain "
+ cookie.getDomain() + ". Will not add new cookie "
+ cookie.getName() + " with value "
+ cookie.getValue());
return;
}
byte[] key;
try {
key = sortableKey(cookie).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // impossible
}
synchronized (cookies) {
if (isCookieCountMaxedForDomain(cookie.getDomain())) {
logger.log(
Level.FINEST,
"Maximum number of cookies reached for domain "
+ cookie.getDomain()
+ ". Will not add new cookie "
+ cookie.getName() + " with value "
+ cookie.getValue());
return;
}
if (!cookie.isExpired(new Date())) {
cookies.put(key, cookie);
} else {
cookies.remove(key);
byte[] key;
try {
key = sortableKey(cookie).getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // impossible
}
if (!cookie.isExpired(new Date())) {
cookies.put(key, cookie);
} else {
cookies.remove(key);
}
}
}
@@ -24,8 +24,10 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.logging.Logger;
@@ -332,9 +334,21 @@ public class CookieStoreTest extends TmpDirTestCase {
threads[i].join();
}
List<Cookie> bdbCookieList = bdbCookieStore().getCookies();
assertTrue(bdbCookieList.size() > 3000);
assertCookieListsEquivalent(bdbCookieList, basicCookieStore().getCookies());
ArrayList<Cookie> bdbCookieArrayList = new ArrayList<Cookie>(bdbCookieStore().getCookies());
Map<String, Integer> domainCounts = new HashMap<String, Integer>();
for (Cookie cookie : bdbCookieArrayList) {
if (domainCounts.get(cookie.getDomain()) == null) {
domainCounts.put(cookie.getDomain(), 1);
}
else {
domainCounts.put(cookie.getDomain(), domainCounts.get(cookie.getDomain()) + 1);
}
}
for (String domain: domainCounts.keySet()) {
assertTrue(domainCounts.get(domain) <= BdbCookieStore.MAX_COOKIES_FOR_DOMAIN);
}
}
protected void assertCookieStoreCountEquals(BdbCookieStore bdb, int count) {