DefaultHostsFileEntriesResolver implements HostsFileEntriesResolver { @Override public InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes) { String normalized = normalize(inetHost); switch (resolvedAddressTypes) { case IPV4_ONLY: return inet4Entries.get(normalized); case IPV6_ONLY: return inet6Entries.get(normalized); case IPV4_PREFERRED: Inet4Address inet4Address = inet4Entries.get(normalized); return inet4Address != null? inet4Address : inet6Entries.get(normalized); case IPV6_PREFERRED: Inet6Address inet6Address = inet6Entries.get(normalized); return inet6Address != null? inet6Address : inet4Entries.get(normalized); default: throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes); } } DefaultHostsFileEntriesResolver();   DefaultHostsFileEntriesResolver(HostsFileEntries entries); @Override InetAddress address(String inetHost, ResolvedAddressTypes resolvedAddressTypes);  }
@Test public void shouldntFindWhenAddressTypeDoesntMatch() { Map<String, Inet4Address> inet4Entries = new HashMap<String, Inet4Address>(); Map<String, Inet6Address> inet6Entries = new HashMap<String, Inet6Address>(); inet4Entries.put("localhost", NetUtil.LOCALHOST4); DefaultHostsFileEntriesResolver resolver = new DefaultHostsFileEntriesResolver(new HostsFileEntries(inet4Entries, inet6Entries)); InetAddress address = resolver.address("localhost", ResolvedAddressTypes.IPV6_ONLY); Assert.assertNull("Should pick an IPv6 address", address); }
@Test public void shouldPickIpv4WhenBothAreDefinedButIpv4IsPreferred() { Map<String, Inet4Address> inet4Entries = new HashMap<String, Inet4Address>(); Map<String, Inet6Address> inet6Entries = new HashMap<String, Inet6Address>(); inet4Entries.put("localhost", NetUtil.LOCALHOST4); inet6Entries.put("localhost", NetUtil.LOCALHOST6); DefaultHostsFileEntriesResolver resolver = new DefaultHostsFileEntriesResolver(new HostsFileEntries(inet4Entries, inet6Entries)); InetAddress address = resolver.address("localhost", ResolvedAddressTypes.IPV4_PREFERRED); Assert.assertTrue("Should pick an IPv4 address", address instanceof Inet4Address); }
@Test public void shouldPickIpv6WhenBothAreDefinedButIpv6IsPreferred() { Map<String, Inet4Address> inet4Entries = new HashMap<String, Inet4Address>(); Map<String, Inet6Address> inet6Entries = new HashMap<String, Inet6Address>(); inet4Entries.put("localhost", NetUtil.LOCALHOST4); inet6Entries.put("localhost", NetUtil.LOCALHOST6); DefaultHostsFileEntriesResolver resolver = new DefaultHostsFileEntriesResolver(new HostsFileEntries(inet4Entries, inet6Entries)); InetAddress address = resolver.address("localhost", ResolvedAddressTypes.IPV6_PREFERRED); Assert.assertTrue("Should pick an IPv6 address", address instanceof Inet6Address); }