/**
 * Copyright (c) 2014,2017 Contributors to the Eclipse Foundation
 *
 * See the NOTICE file(s) distributed with this work for additional
 * information regarding copyright ownership.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0
 *
 * SPDX-License-Identifier: EPL-2.0
 */
package org.eclipse.smarthome.binding.fsinternetradio.test;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * Look up a free TCP/IP port on localhost for test execution. This ensures collision free parallel test execution using
 * embedded jetty on dynamic ports.
 *
 * @author Henning Treu - initial contribution
 *
 */
public class TestPortUtil {

    /**
     * Returns a free port number on localhost.
     *
     * Heavily inspired from org.eclipse.jdt.launching.SocketUtil (to avoid a dependency to JDT just because of this).
     * Slightly improved with close() missing in JDT. And throws exception instead of returning -1.
     *
     * @return a free port number on localhost
     * @throws IllegalStateException if unable to find a free port
     */
    public static int findFreePort() {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0);
            socket.setReuseAddress(true);
            int port = socket.getLocalPort();
            try {
                socket.close();
            } catch (IOException e) {
                // Ignore IOException on close()
            }
            return port;
        } catch (IOException e) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                }
            }
        }
        throw new IllegalStateException("Could not find a free TCP/IP port to start embedded Jetty HTTP Server on");
    }
}

@@ -1232,16 +1232,27 @@
         
+try (final 
 ServerSo
@@ -1268,49 +1268,8 @@
 et =
- null;%0A        try %7B%0A            socket =
  new
@@ -1284,17 +1284,19 @@
 ocket(0)
-;
+) %7B
 %0A       
@@ -1346,18 +1346,14 @@
     
-int port =
+return
  soc
@@ -1384,338 +1384,8 @@
     
-    try %7B%0A                socket.close();%0A            %7D catch (IOException e) %7B%0A                // Ignore IOException on close()%0A            %7D%0A            return port;%0A        %7D catch (IOException e) %7B%0A        %7D finally %7B%0A            if (socket != null) %7B%0A                try %7B%0A                    socket.close();%0A                
 %7D ca
@@ -1389,16 +1389,22 @@
  catch (
+final 
 IOExcept
@@ -1408,24 +1408,25 @@
 eption e
+x
 ) %7B%0A    
         
@@ -1421,46 +1421,8 @@
     
-            %7D%0A            %7D%0A        %7D%0A
     
@@ -1531,18 +1531,52 @@
 rver on%22
-);
+,%0A                    ex);%0A        %7D
 %0A    %7D%0A%7D

improve test port util method (#4720)