1
0
mirror of https://github.com/square/okhttp.git synced 2026-01-17 08:42:25 +03:00

Override the equals() and hashCode() methods of Cookie

Now it is possible to use Cookies in Collections that depend
on the hash function. (Useful when implementing an in-memory CookieJar)
This commit is contained in:
Francisco Montiel
2016-01-27 01:22:07 +01:00
committed by jwilson
parent eb179eb419
commit 7082ca91bc
2 changed files with 56 additions and 0 deletions

View File

@@ -17,8 +17,10 @@ package okhttp3;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import okhttp3.internal.Util;
import okhttp3.internal.http.HttpDate;
import org.junit.Test;
@@ -459,6 +461,32 @@ public final class CookieTest {
assertEquals(true, cookie.httpOnly());
}
@Test public void equalsAndHashCode() throws Exception {
List<String> cookieStrings = Arrays.asList(
"a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly",
"a= ; Path=/c; Domain=example.com; Max-Age=5; Secure; HttpOnly",
"a=b; Domain=example.com; Max-Age=5; Secure; HttpOnly",
"a=b; Path=/c; Max-Age=5; Secure; HttpOnly",
"a=b; Path=/c; Domain=example.com; Secure; HttpOnly",
"a=b; Path=/c; Domain=example.com; Max-Age=5; HttpOnly",
"a=b; Path=/c; Domain=example.com; Max-Age=5; Secure; "
);
for (String stringA : cookieStrings) {
Cookie cookieA = Cookie.parse(0, url, stringA);
for (String stringB : cookieStrings) {
Cookie cookieB = Cookie.parse(0, url, stringB);
if (Objects.equals(stringA, stringB)) {
assertEquals(cookieA.hashCode(), cookieB.hashCode());
assertEquals(cookieA, cookieB);
} else {
assertFalse(cookieA.hashCode() == cookieB.hashCode());
assertFalse(cookieA.equals(cookieB));
}
}
assertFalse(cookieA.equals(null));
}
}
private Date date(String s) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(Util.UTC);

View File

@@ -559,4 +559,32 @@ public final class Cookie {
return result.toString();
}
@Override public boolean equals(Object other) {
if (!(other instanceof Cookie)) return false;
Cookie that = (Cookie) other;
return that.name.equals(name)
&& that.value.equals(value)
&& that.domain.equals(domain)
&& that.path.equals(path)
&& that.expiresAt == expiresAt
&& that.secure == secure
&& that.httpOnly == httpOnly
&& that.persistent == persistent
&& that.hostOnly == hostOnly;
}
@Override public int hashCode() {
int hash = 17;
hash = 31 * hash + name.hashCode();
hash = 31 * hash + value.hashCode();
hash = 31 * hash + domain.hashCode();
hash = 31 * hash + path.hashCode();
hash = 31 * hash + (int) (expiresAt ^ (expiresAt >>> 32));
hash = 31 * hash + (secure ? 0 : 1);
hash = 31 * hash + (httpOnly ? 0 : 1);
hash = 31 * hash + (persistent ? 0 : 1);
hash = 31 * hash + (hostOnly ? 0 : 1);
return hash;
}
}