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
28
29
30
31 package org.apache.commons.httpclient.cookie;
32
33 import java.util.Comparator;
34
35 import org.apache.commons.httpclient.Cookie;
36
37 /***
38 * This cookie comparator ensures that multiple cookies satisfying
39 * a common criteria are ordered in the <tt>Cookie</tt> header such
40 * that those with more specific Path attributes precede those with
41 * less specific.
42 *
43 * <p>
44 * This comparator assumes that Path attributes of two cookies
45 * path-match a commmon request-URI. Otherwise, the result of the
46 * comparison is undefined.
47 * </p>
48 *
49 * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
50 *
51 * @since 3.1
52 */
53 public class CookiePathComparator implements Comparator {
54
55 private String normalizePath(final Cookie cookie) {
56 String path = cookie.getPath();
57 if (path == null) {
58 path = "/";
59 }
60 if (!path.endsWith("/")) {
61 path = path + "/";
62 }
63 return path;
64 }
65
66 public int compare(final Object o1, final Object o2) {
67 Cookie c1 = (Cookie) o1;
68 Cookie c2 = (Cookie) o2;
69 String path1 = normalizePath(c1);
70 String path2 = normalizePath(c2);
71 if (path1.equals(path2)) {
72 return 0;
73 } else if (path1.startsWith(path2)) {
74 return -1;
75 } else if (path2.startsWith(path1)) {
76 return 1;
77 } else {
78
79 return 0;
80 }
81 }
82
83 }