1 /*
2 * $Header$
3 * $Revision:400312 $
4 * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5 *
6 * ====================================================================
7 *
8 * Licensed to the Apache Software Foundation (ASF) under one or more
9 * contributor license agreements. See the NOTICE file distributed with
10 * this work for additional information regarding copyright ownership.
11 * The ASF licenses this file to You under the Apache License, Version 2.0
12 * (the "License"); you may not use this file except in compliance with
13 * the License. You may obtain a copy of the License at
14 *
15 * http://www.apache.org/licenses/LICENSE-2.0
16 *
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
22 * ====================================================================
23 *
24 * This software consists of voluntary contributions made by many
25 * individuals on behalf of the Apache Software Foundation. For more
26 * information on the Apache Software Foundation, please see
27 * <http://www.apache.org/>.
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 // Does not really matter
79 return 0;
80 }
81 }
82
83 }