/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.kafka.clients;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.kafka.common.config.ConfigException;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class ClientUtilsTest {

    private HostResolver hostResolver = new DefaultHostResolver();

    @Test
    public void testParseAndValidateAddresses() {
        checkWithoutLookup("127.0.0.1:8000");
        checkWithoutLookup("localhost:8080");
        checkWithoutLookup("[::1]:8000");
        checkWithoutLookup("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:1234", "localhost:10000");
        List<InetSocketAddress> validatedAddresses = checkWithoutLookup("localhost:10000");
        assertEquals(1, validatedAddresses.size());
        InetSocketAddress onlyAddress = validatedAddresses.get(0);
        assertEquals("localhost", onlyAddress.getHostName());
        assertEquals(10000, onlyAddress.getPort());
    }

    @Test
    public void testParseAndValidateAddressesWithReverseLookup() {
        checkWithoutLookup("127.0.0.1:8000");
        checkWithoutLookup("localhost:8080");
        checkWithoutLookup("[::1]:8000");
        checkWithoutLookup("[2001:db8:85a3:8d3:1319:8a2e:370:7348]:1234", "localhost:10000");

        // With lookup of example.com, either one or two addresses are expected depending on
        // whether ipv4 and ipv6 are enabled
        List<InetSocketAddress> validatedAddresses = checkWithLookup(Arrays.asList("example.com:10000"));
        assertTrue(validatedAddresses.size() >= 1, "Unexpected addresses " + validatedAddresses);
        List<String> validatedHostNames = validatedAddresses.stream().map(InetSocketAddress::getHostName)
                .collect(Collectors.toList());
        List<String> expectedHostNames = Arrays.asList("93.184.216.34", "2606:2800:220:1:248:1893:25c8:1946");
        assertTrue(expectedHostNames.containsAll(validatedHostNames), "Unexpected addresses " + validatedHostNames);
        validatedAddresses.forEach(address -> assertEquals(10000, address.getPort()));
    }

    @Test
    public void testInvalidConfig() {
        assertThrows(IllegalArgumentException.class,
            () -> ClientUtils.parseAndValidateAddresses(Collections.singletonList("localhost:10000"), "random.value"));
    }

    @Test
    public void testNoPort() {
        assertThrows(ConfigException.class, () -> checkWithoutLookup("127.0.0.1"));
    }

    @Test
    public void testOnlyBadHostname() {
        assertThrows(ConfigException.class, () -> checkWithoutLookup("some.invalid.hostname.foo.bar.local:9999"));
    }

    @Test
    public void testFilterPreferredAddresses() throws UnknownHostException {
        InetAddress ipv4 = InetAddress.getByName("192.0.0.1");
        InetAddress ipv6 = InetAddress.getByName("::1");

        InetAddress[] ipv4First = new InetAddress[]{ipv4, ipv6, ipv4};
        List<InetAddress> result = ClientUtils.filterPreferredAddresses(ipv4First);
        assertTrue(result.contains(ipv4));
        assertFalse(result.contains(ipv6));
        assertEquals(2, result.size());

        InetAddress[] ipv6First = new InetAddress[]{ipv6, ipv4, ipv4};
        result = ClientUtils.filterPreferredAddresses(ipv6First);
        assertTrue(result.contains(ipv6));
        assertFalse(result.contains(ipv4));
        assertEquals(1, result.size());
    }

    @Test
    public void testResolveUnknownHostException() {
        assertThrows(UnknownHostException.class,
            () -> ClientUtils.resolve("some.invalid.hostname.foo.bar.local", hostResolver));
    }

    @Test
    public void testResolveDnsLookup() throws UnknownHostException {
        // Note that kafka.apache.org resolves to at least 2 IP addresses
        assertTrue(ClientUtils.resolve("kafka.apache.org", hostResolver).size() > 1);
    }

    private List<InetSocketAddress> checkWithoutLookup(String... url) {
        return ClientUtils.parseAndValidateAddresses(Arrays.asList(url), ClientDnsLookup.USE_ALL_DNS_IPS);
    }

    private List<InetSocketAddress> checkWithLookup(List<String> url) {
        return ClientUtils.parseAndValidateAddresses(url, ClientDnsLookup.RESOLVE_CANONICAL_BOOTSTRAP_SERVERS_ONLY);
    }

}

@@ -933,33 +933,8 @@
 on;%0A
-import java.util.Arrays;%0A
 impo
@@ -959,16 +959,16 @@
 ctions;%0A
+
 import j
@@ -1109,16 +1109,55 @@
 .Test;%0A%0A
+import static java.util.Arrays.asList;%0A
 import s
@@ -1434,16 +1434,22 @@
 private 
+final 
 HostReso
@@ -2629,23 +2629,16 @@
 hLookup(
-Arrays.
 asList(%22
@@ -2951,23 +2951,16 @@
 Names = 
-Arrays.
 asList(%22
@@ -4821,63 +4821,230 @@
     
-// Note that kafka.apache.org resolves to at least 2 IP
+InetAddress%5B%5D addresses = new InetAddress%5B%5D %7B%0A            InetAddress.getByName(%22198.51.100.0%22), InetAddress.getByName(%22198.51.100.5%22)%0A        %7D;%0A        HostResolver hostResolver = new AddressChangeHostResolver(addresses,
  add
@@ -5049,16 +5049,18 @@
 ddresses
+);
 %0A       
@@ -5066,21 +5066,42 @@
   assert
-True(
+Equals(asList(addresses), 
 ClientUt
@@ -5149,19 +5149,8 @@
 ver)
-.size() %3E 1
 );%0A 
@@ -5219,32 +5219,32 @@
 tring... url) %7B%0A
+
         return C
@@ -5280,23 +5280,16 @@
 dresses(
-Arrays.
 asList(u

Fix `testResolveDnsLookup` by using a mocked dns resolver (#11091)