View Javadoc

1   /*
2    * $Header$
3    * $Revision:400312 $
4    * $Date:2006-05-06 14:49:41 +0200 (Sat, 06 May 2006) $
5    *
6    * ====================================================================
7    *
8    *  Copyright 1999-2004 The Apache Software Foundation
9    *
10   *  Licensed under the Apache License, Version 2.0 (the "License");
11   *  you may not use this file except in compliance with the License.
12   *  You may obtain a copy of the License at
13   *
14   *      http://www.apache.org/licenses/LICENSE-2.0
15   *
16   *  Unless required by applicable law or agreed to in writing, software
17   *  distributed under the License is distributed on an "AS IS" BASIS,
18   *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19   *  See the License for the specific language governing permissions and
20   *  limitations under the License.
21   * ====================================================================
22   *
23   * This software consists of voluntary contributions made by many
24   * individuals on behalf of the Apache Software Foundation.  For more
25   * information on the Apache Software Foundation, please see
26   * <http://www.apache.org/>.
27   *
28   */
29  
30  package org.apache.commons.httpclient.cookie;
31  
32  import java.util.Comparator;
33  
34  import org.apache.commons.httpclient.Cookie;
35  
36  /***
37   * This cookie comparator ensures that multiple cookies satisfying 
38   * a common criteria are ordered in the <tt>Cookie</tt> header such
39   * that those with more specific Path attributes precede those with
40   * less specific.
41   *  
42   * <p>
43   * This comparator assumes that Path attributes of two cookies 
44   * path-match a commmon request-URI. Otherwise, the result of the
45   * comparison is undefined.
46   * </p>
47   * 
48   * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
49   * 
50   * @since 3.1
51   */
52  public class CookiePathComparator implements Comparator {
53  
54      private String normalizePath(final Cookie cookie) {
55          String path = cookie.getPath();
56          if (path == null) {
57              path = "/";
58          }
59          if (!path.endsWith("/")) {
60              path = path + "/";
61          }
62          return path;
63      }
64      
65      public int compare(final Object o1, final Object o2) {
66          Cookie c1 = (Cookie) o1;
67          Cookie c2 = (Cookie) o2;
68          String path1 = normalizePath(c1);
69          String path2 = normalizePath(c2);
70          if (path1.equals(path2)) {
71              return 0;
72          } else if (path1.startsWith(path2)) {
73              return -1;
74          } else if (path2.startsWith(path1)) {
75              return 1;
76          } else {
77              // Does not really matter
78              return 0;
79          }
80      }
81  
82  }