1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package io.netty.util;
18
19 import io.netty.util.internal.StringUtil;
20
21 import java.net.IDN;
22 import java.util.Collections;
23 import java.util.LinkedHashMap;
24 import java.util.Locale;
25 import java.util.Map;
26
27 import static io.netty.util.internal.ObjectUtil.checkNotNull;
28 import static io.netty.util.internal.StringUtil.commonSuffixOfLength;
29
30
31
32
33
34
35
36
37 public class DomainNameMapping<V> implements Mapping<String, V> {
38
39 final V defaultValue;
40 private final Map<String, V> map;
41 private final Map<String, V> unmodifiableMap;
42
43
44
45
46
47
48
49
50 @Deprecated
51 public DomainNameMapping(V defaultValue) {
52 this(4, defaultValue);
53 }
54
55
56
57
58
59
60
61
62
63 @Deprecated
64 public DomainNameMapping(int initialCapacity, V defaultValue) {
65 this(new LinkedHashMap<String, V>(initialCapacity), defaultValue);
66 }
67
68 DomainNameMapping(Map<String, V> map, V defaultValue) {
69 this.defaultValue = checkNotNull(defaultValue, "defaultValue");
70 this.map = map;
71 unmodifiableMap = map != null ? Collections.unmodifiableMap(map)
72 : null;
73 }
74
75
76
77
78
79
80
81
82
83
84
85
86
87 @Deprecated
88 public DomainNameMapping<V> add(String hostname, V output) {
89 map.put(normalizeHostname(checkNotNull(hostname, "hostname")), checkNotNull(output, "output"));
90 return this;
91 }
92
93
94
95
96 static boolean matches(String template, String hostName) {
97 if (template.startsWith("*.")) {
98 return template.regionMatches(2, hostName, 0, hostName.length())
99 || commonSuffixOfLength(hostName, template, template.length() - 1);
100 }
101 return template.equals(hostName);
102 }
103
104
105
106
107 static String normalizeHostname(String hostname) {
108 if (needsNormalization(hostname)) {
109 hostname = IDN.toASCII(hostname, IDN.ALLOW_UNASSIGNED);
110 }
111 return hostname.toLowerCase(Locale.US);
112 }
113
114 private static boolean needsNormalization(String hostname) {
115 final int length = hostname.length();
116 for (int i = 0; i < length; i++) {
117 int c = hostname.charAt(i);
118 if (c > 0x7F) {
119 return true;
120 }
121 }
122 return false;
123 }
124
125 @Override
126 public V map(String hostname) {
127 if (hostname != null) {
128 hostname = normalizeHostname(hostname);
129
130 for (Map.Entry<String, V> entry : map.entrySet()) {
131 if (matches(entry.getKey(), hostname)) {
132 return entry.getValue();
133 }
134 }
135 }
136 return defaultValue;
137 }
138
139
140
141
142 public Map<String, V> asMap() {
143 return unmodifiableMap;
144 }
145
146 @Override
147 public String toString() {
148 return StringUtil.simpleClassName(this) + "(default: " + defaultValue + ", map: " + map + ')';
149 }
150 }