diff --git a/server/src/main/java/server/PortChecker.java b/server/src/main/java/server/PortChecker.java index c097237..c0c564a 100644 --- a/server/src/main/java/server/PortChecker.java +++ b/server/src/main/java/server/PortChecker.java @@ -30,10 +30,9 @@ public class PortChecker { public boolean isPortAvailable(int port){ try(ServerSocket socket = new ServerSocket(port)){ return true; - }catch(IOException i) { + } + catch(IOException i) { return false; } } -} - - +} \ No newline at end of file diff --git a/server/src/main/java/server/ServerPortCustomizer.java b/server/src/main/java/server/ServerPortCustomizer.java index 0994a8e..9524cbf 100644 --- a/server/src/main/java/server/ServerPortCustomizer.java +++ b/server/src/main/java/server/ServerPortCustomizer.java @@ -1,4 +1,3 @@ - package server; import org.springframework.boot.web.server.ConfigurableWebServerFactory; @@ -6,7 +5,8 @@ import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.stereotype.Component; @Component -public class ServerPortCustomizer implements WebServerFactoryCustomizer{ +public class ServerPortCustomizer + implements WebServerFactoryCustomizer{ /** * Changes the port that will be used to launch the program. * made with the help of: https://www.baeldung.com/spring-boot-change-port @@ -19,11 +19,9 @@ public class ServerPortCustomizer implements WebServerFactoryCustomizer { + checker.isPortAvailable(-1); + } + ); + assertThrows(IllegalArgumentException.class, ()-> { + checker.isPortAvailable(65536); + } + ); + } + @Test + void findFreePort() throws IOException { + PortChecker checker = new PortChecker(); + + int port = checker.findFreePort(); + int defaultPort = 8080; + int lastPort = 8090; + + boolean greaterOrEqual = port >= defaultPort; + boolean lessOrEqual = port <= lastPort; + boolean inRange = greaterOrEqual && lessOrEqual; + boolean isItFree = checker.isPortAvailable(port); + + assertTrue(inRange); + } + @Test + void noFreePort() { + List notFreePorts = new ArrayList<>(); + int defaultPort = 8080; + int lastPort = 8090; + + try { + for (int i = defaultPort; i <= lastPort; i++) { + try { + notFreePorts.add(new ServerSocket(i)); + } + catch (IOException e) { + } + } + + PortChecker checker = new PortChecker(); + assertThrows(IOException.class, () -> { + checker.findFreePort(); + } + ); + } + catch (Exception e) { + throw new RuntimeException(e); + } + + for (ServerSocket s : notFreePorts) { + try { + s.close(); + } + catch (IOException e) { + } + } + } +} \ No newline at end of file