001/* 002 * ==================================================================== 003 * Licensed to the Apache Software Foundation (ASF) under one 004 * or more contributor license agreements. See the NOTICE file 005 * distributed with this work for additional information 006 * regarding copyright ownership. The ASF licenses this file 007 * to you under the Apache License, Version 2.0 (the 008 * "License"); you may not use this file except in compliance 009 * with the License. You may obtain a copy of the License at 010 * 011 * http://www.apache.org/licenses/LICENSE-2.0 012 * 013 * Unless required by applicable law or agreed to in writing, 014 * software distributed under the License is distributed on an 015 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 016 * KIND, either express or implied. See the License for the 017 * specific language governing permissions and limitations 018 * under the License. 019 * ==================================================================== 020 * 021 * This software consists of voluntary contributions made by many 022 * individuals on behalf of the Apache Software Foundation. For more 023 * information on the Apache Software Foundation, please see 024 * <http://www.apache.org/>. 025 * 026 */ 027 028package org.apache.http.cookie; 029 030import java.io.Serializable; 031import java.util.Comparator; 032 033import org.apache.http.annotation.Contract; 034import org.apache.http.annotation.ThreadingBehavior; 035 036/** 037 * This cookie comparator can be used to compare identity of cookies. 038 * <p> 039 * Cookies are considered identical if their names are equal and 040 * their domain attributes match ignoring case. 041 * 042 * @since 4.0 043 */ 044@Contract(threading = ThreadingBehavior.IMMUTABLE) 045public class CookieIdentityComparator implements Serializable, Comparator<Cookie> { 046 047 private static final long serialVersionUID = 4466565437490631532L; 048 049 @Override 050 public int compare(final Cookie c1, final Cookie c2) { 051 int res = c1.getName().compareTo(c2.getName()); 052 if (res == 0) { 053 // do not differentiate empty and null domains 054 String d1 = c1.getDomain(); 055 if (d1 == null) { 056 d1 = ""; 057 } else if (d1.indexOf('.') == -1) { 058 d1 = d1 + ".local"; 059 } 060 String d2 = c2.getDomain(); 061 if (d2 == null) { 062 d2 = ""; 063 } else if (d2.indexOf('.') == -1) { 064 d2 = d2 + ".local"; 065 } 066 res = d1.compareToIgnoreCase(d2); 067 } 068 if (res == 0) { 069 String p1 = c1.getPath(); 070 if (p1 == null) { 071 p1 = "/"; 072 } 073 String p2 = c2.getPath(); 074 if (p2 == null) { 075 p2 = "/"; 076 } 077 res = p1.compareTo(p2); 078 } 079 return res; 080 } 081 082}