|
26 | 26 | import org.eclipse.jetty.servlet.FilterMapping; |
27 | 27 | import org.eclipse.jetty.servlet.ServletContextHandler; |
28 | 28 |
|
| 29 | +import java.io.IOException; |
| 30 | +import java.net.ServerSocket; |
| 31 | + |
29 | 32 | /** |
30 | 33 | * Created by yonisha on 2/3/2015. |
31 | 34 | */ |
32 | 35 | public class JettyTestServer { |
33 | 36 | private Server server; |
34 | | - private int Min = 1050; |
35 | | - private int Max = 15000; |
36 | | - private int portNumber = Min + (int)(Math.random() * ((Max - Min) + 1)); |
| 37 | + private final int Min = 1050; |
| 38 | + private final int Max = 15000; |
| 39 | + private final int portNumber; |
| 40 | + |
| 41 | + public JettyTestServer() { |
| 42 | + // try 256 times for ports |
| 43 | + int initialPortNumber = Min + (int)(Math.random() * ((Max - Min) + 1)); |
| 44 | + for (int i = 0; i < 256; i++) { |
| 45 | + ServerSocket ss = null; |
| 46 | + try { |
| 47 | + ss = new ServerSocket(initialPortNumber); |
| 48 | + break; // if it doesn't throw, the port is open |
| 49 | + } catch (IOException e) { |
| 50 | + System.out.printf("port '%d' in use. Trying next one.%n", initialPortNumber); |
| 51 | + initialPortNumber++; |
| 52 | + } finally { |
| 53 | + if (ss != null) { |
| 54 | + try { |
| 55 | + ss.close(); |
| 56 | + } catch (IOException e) { |
| 57 | + System.err.printf("Error closing port testing socket:%n%s%n", e.toString()); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + portNumber = initialPortNumber; |
| 63 | + } |
37 | 64 |
|
38 | 65 | public void start() throws Exception { |
39 | 66 | server = new Server(portNumber); |
|
0 commit comments