Fixes Cookies.getCookie() to prefer the most specific cookie instead of the
least specific cookie.
The cookies that come from the browser are sorted by path order so that cookies
with the most specific path appear first. If multiple cookies with the same
name are present we should return the most specific cookie. As it stands, we
end up returning the last cookie which is the least specific one. This changes
it so that we return the first cookie, which is the most specific.
Change-Id: Ie8c76c349780f8c59beb98c4df2a3497e78e7216
diff --git a/user/src/com/google/gwt/user/client/Cookies.java b/user/src/com/google/gwt/user/client/Cookies.java
index c30d50b..053b025 100644
--- a/user/src/com/google/gwt/user/client/Cookies.java
+++ b/user/src/com/google/gwt/user/client/Cookies.java
@@ -199,7 +199,7 @@
var docCookie = $doc.cookie;
if (docCookie && docCookie != '') {
var crumbs = docCookie.split('; ');
- for (var i = 0; i < crumbs.length; ++i) {
+ for (var i = crumbs.length - 1; i >= 0; --i) {
var name, value;
var eqIdx = crumbs[i].indexOf('=');
if (eqIdx == -1) {
diff --git a/user/test/com/google/gwt/user/client/CookieTest.java b/user/test/com/google/gwt/user/client/CookieTest.java
index 5e80386..8f9073f 100644
--- a/user/test/com/google/gwt/user/client/CookieTest.java
+++ b/user/test/com/google/gwt/user/client/CookieTest.java
@@ -16,6 +16,8 @@
package com.google.gwt.user.client;
import com.google.gwt.core.client.GWT;
+import com.google.gwt.junit.DoNotRunWith;
+import com.google.gwt.junit.Platform;
import com.google.gwt.junit.client.GWTTestCase;
import java.util.Collection;
@@ -62,10 +64,25 @@
assertEquals(Cookies.getCookie("novalue"), "");
assertEquals(Cookies.getCookie("notpresent"), null);
}
-
+
+ // HTMLUnit doesn't match browsers in terms of the order of cookies.
+ @DoNotRunWith(Platform.HtmlUnitUnknown)
+ public void testCookiesWithTheSameName() {
+ // Make the cookie expire in one minute, so that they don't hang around
+ // past the end of this test.
+ Date expires = new Date(getClientTime() + (60 * 1000));
+
+ // Given multiple cookies with the same name, we should pick the cookie with the longest
+ // path.
+ Cookies.setCookie("token", "root", expires, null, "/", false);
+ Cookies.setCookie("token", "longest", expires, null, "/com.google.gwt.user.User.JUnit/junit.html", false);
+ Cookies.setCookie("token", "middle", expires, null, "/com.google.gwt.user.User.JUnit/", false);
+ assertEquals("longest", Cookies.getCookie("token"));
+ }
+
/*
* Test that the cookie will expire correctly after a set amount of time,
- * but does not expire before that time.
+ * but does not expire before that time.
*/
public void testExpires() {
// Generate a random ID for the cookies. Since cookies are shared across