View Javadoc
1   /*
2    * Copyright 2015 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    *   http://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.netty.resolver;
17  
18  import io.netty.util.internal.UnstableApi;
19  
20  import java.net.Inet4Address;
21  import java.net.Inet6Address;
22  import java.net.InetAddress;
23  import java.util.Locale;
24  import java.util.Map;
25  
26  /**
27   * Default {@link HostsFileEntriesResolver} that resolves hosts file entries only once.
28   */
29  @UnstableApi
30  public final class DefaultHostsFileEntriesResolver implements HostsFileEntriesResolver {
31  
32      private final Map<String, Inet4Address> inet4Entries;
33      private final Map<String, Inet6Address> inet6Entries;
34  
35      public DefaultHostsFileEntriesResolver() {
36          this(HostsFileParser.parseSilently());
37      }
38  
39      // for testing purpose only
40      DefaultHostsFileEntriesResolver(HostsFileEntries entries) {
41          inet4Entries = entries.inet4Entries();
42          inet6Entries = entries.inet6Entries();
43      }
44  
45      @Override
46      public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) {
47          String normalized = normalize(inetHost);
48          switch (resolvedAddressTypes) {
49              case IPV4_ONLY:
50                  return inet4Entries.get(normalized);
51              case IPV6_ONLY:
52                  return inet6Entries.get(normalized);
53              case IPV4_PREFERRED:
54                  Inet4Address inet4Address = inet4Entries.get(normalized);
55                  return inet4Address != null? inet4Address : inet6Entries.get(normalized);
56              case IPV6_PREFERRED:
57                  Inet6Address inet6Address = inet6Entries.get(normalized);
58                  return inet6Address != null? inet6Address : inet4Entries.get(normalized);
59              default:
60                  throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
61          }
62      }
63  
64      // package-private for testing purposes
65      String normalize(String inetHost) {
66          return inetHost.toLowerCase(Locale.ENGLISH);
67      }
68  }