1 /*
2 * Copyright 2018 The Netty Project
3 *
4 * The Netty Project licenses this file to you under the Apache License,
5 * version 2.0 (the "License"); you may not use this file except in compliance
6 * with the License. You may obtain a copy of the License at:
7 *
8 * https://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16 package io.netty5.resolver.dns;
17
18 import java.io.Serializable;
19 import java.net.InetAddress;
20 import java.net.InetSocketAddress;
21 import java.util.Comparator;
22 import java.util.List;
23
24 import static java.util.Objects.requireNonNull;
25
26 /**
27 * Special {@link Comparator} implementation to sort the nameservers to use when follow redirects.
28 *
29 * This implementation follows all the semantics listed in the
30 * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html">Comparator apidocs</a>
31 * with the limitation that {@link InetSocketAddress#equals(Object)} will not result in the same return value as
32 * {@link #compare(InetSocketAddress, InetSocketAddress)}. This is completely fine as this should only be used
33 * to sort {@link List}s.
34 */
35 public final class NameServerComparator implements Comparator<InetSocketAddress>, Serializable {
36
37 private static final long serialVersionUID = 8372151874317596185L;
38
39 private final Class<? extends InetAddress> preferredAddressType;
40
41 public NameServerComparator(Class<? extends InetAddress> preferredAddressType) {
42 this.preferredAddressType = requireNonNull(preferredAddressType, "preferredAddressType");
43 }
44
45 @Override
46 public int compare(InetSocketAddress addr1, InetSocketAddress addr2) {
47 if (addr1.equals(addr2)) {
48 return 0;
49 }
50 if (!addr1.isUnresolved() && !addr2.isUnresolved()) {
51 if (addr1.getAddress().getClass() == addr2.getAddress().getClass()) {
52 return 0;
53 }
54 return preferredAddressType.isAssignableFrom(addr1.getAddress().getClass()) ? -1 : 1;
55 }
56 if (addr1.isUnresolved() && addr2.isUnresolved()) {
57 return 0;
58 }
59 return addr1.isUnresolved() ? 1 : -1;
60 }
61 }