Skip to content

Commit 22d76fe

Browse files
committed
Quit java process if port 8080 is already taken
1 parent 7ee8df0 commit 22d76fe

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/main/java/com/mygcc/api/Main.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
import org.eclipse.jetty.servlet.ServletContextHandler;
55
import org.eclipse.jetty.servlet.ServletHolder;
66
import org.glassfish.jersey.servlet.ServletContainer;
7+
import java.io.IOException;
8+
import java.net.DatagramSocket;
9+
import java.net.ServerSocket;
710

811
/**
912
* This class launches the web application in an embedded Jetty container. This
@@ -25,6 +28,11 @@ public static void main(final String[] args) throws Exception {
2528
webPort = "8080";
2629
}
2730

31+
// Check that port is open
32+
if (!portAvailable(Integer.parseInt(webPort))) {
33+
return;
34+
}
35+
2836
final Server server = new Server(Integer.parseInt(webPort));
2937

3038
ServletContextHandler ctx =
@@ -41,6 +49,39 @@ public static void main(final String[] args) throws Exception {
4149
server.join();
4250
}
4351

52+
/**
53+
* Checks to see if a specific port is available.
54+
*
55+
* @param port the port to check for availability
56+
* @return whether the port is available
57+
*/
58+
private static boolean portAvailable(final int port) {
59+
ServerSocket ss = null;
60+
DatagramSocket ds = null;
61+
try {
62+
ss = new ServerSocket(port);
63+
ss.setReuseAddress(true);
64+
ds = new DatagramSocket(port);
65+
ds.setReuseAddress(true);
66+
return true;
67+
} catch (IOException e) {
68+
} finally {
69+
if (ds != null) {
70+
ds.close();
71+
}
72+
73+
if (ss != null) {
74+
try {
75+
ss.close();
76+
} catch (IOException e) {
77+
/* should not be thrown */
78+
}
79+
}
80+
}
81+
82+
return false;
83+
}
84+
4485
/**
4586
* Fixes Checkstyle error: utility classes should not have a public or
4687
* default constructor.

0 commit comments

Comments
 (0)