1 /*
2 * ====================================================================
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 * ====================================================================
20 *
21 * This software consists of voluntary contributions made by many
22 * individuals on behalf of the Apache Software Foundation. For more
23 * information on the Apache Software Foundation, please see
24 * <http://www.apache.org/>.
25 *
26 */
27
28 package org.apache.hc.client5.http.cookie;
29
30 import java.io.Serializable;
31 import java.util.Comparator;
32
33 import org.apache.hc.core5.annotation.Contract;
34 import org.apache.hc.core5.annotation.ThreadingBehavior;
35
36 /**
37 * This cookie comparator ensures that multiple cookies satisfying
38 * a common criteria are ordered in the {@link Cookie} 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 common request-URI. Otherwise, the result of the
45 * comparison is undefined.
46 * </p>
47 *
48 *
49 * @since 4.0
50 */
51 @Contract(threading = ThreadingBehavior.STATELESS)
52 public class CookiePathComparator implements Serializable, Comparator<Cookie> {
53
54 /**
55 * Default instance of {@link CookiePathComparator}.
56 */
57 public static final CookiePathComparator INSTANCE = new CookiePathComparator();
58
59 private static final long serialVersionUID = 7523645369616405818L;
60
61 private String normalizePath(final Cookie cookie) {
62 String path = cookie.getPath();
63 if (path == null) {
64 path = "/";
65 }
66 if (!path.endsWith("/")) {
67 path = path + '/';
68 }
69 return path;
70 }
71
72 @Override
73 public int compare(final Cookie c1, final Cookie c2) {
74 final String path1 = normalizePath(c1);
75 final String path2 = normalizePath(c2);
76 if (path1.equals(path2)) {
77 return 0;
78 } else if (path1.startsWith(path2)) {
79 return -1;
80 } else if (path2.startsWith(path1)) {
81 return 1;
82 } else {
83 // Does not really matter
84 return 0;
85 }
86 }
87
88 }