com.github.httpmock.exec.PortUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mock-http-server-exec Show documentation
Show all versions of mock-http-server-exec Show documentation
Mock HTTP Server - Executable
The newest version!
package com.github.httpmock.exec;
import com.github.httpmock.ServerException;
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.List;
import static com.github.httpmock.util.CollectionUtil.emptyList;
public abstract class PortUtil {
public static List getRandomPorts(int numberOfPorts) {
List serverSockets = createServerSockets(numberOfPorts);
List ports = emptyList(numberOfPorts);
for (ServerSocket serverSocket : serverSockets) {
ports.add(serverSocket.getLocalPort());
IOUtils.closeQuietly(serverSocket);
}
return ports;
}
private static List createServerSockets(int numberOfSockets) {
List serverSockets = emptyList(numberOfSockets);
for (int i = 1; i <= numberOfSockets; i++) {
try {
serverSockets.add(createServerSocket());
} catch (IOException e) {
closeAllSockets(serverSockets);
throw new ServerException(e);
}
}
return serverSockets;
}
private static void closeAllSockets(List serverSockets) {
for (ServerSocket serverSocket : serverSockets) {
IOUtils.closeQuietly(serverSocket);
}
}
private static ServerSocket createServerSocket() throws IOException {
return new ServerSocket(0);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy