Skip to content

Commit

Permalink
Quit java process if port 8080 is already taken
Browse files Browse the repository at this point in the history
  • Loading branch information
davidcorbin committed Apr 13, 2018
1 parent 7ee8df0 commit 22d76fe
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/main/java/com/mygcc/api/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.glassfish.jersey.servlet.ServletContainer;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.ServerSocket;

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

// Check that port is open
if (!portAvailable(Integer.parseInt(webPort))) {
return;
}

final Server server = new Server(Integer.parseInt(webPort));

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

/**
* Checks to see if a specific port is available.
*
* @param port the port to check for availability
* @return whether the port is available
*/
private static boolean portAvailable(final int port) {
ServerSocket ss = null;
DatagramSocket ds = null;
try {
ss = new ServerSocket(port);
ss.setReuseAddress(true);
ds = new DatagramSocket(port);
ds.setReuseAddress(true);
return true;
} catch (IOException e) {
} finally {
if (ds != null) {
ds.close();
}

if (ss != null) {
try {
ss.close();
} catch (IOException e) {
/* should not be thrown */
}
}
}

return false;
}

/**
* Fixes Checkstyle error: utility classes should not have a public or
* default constructor.
Expand Down

0 comments on commit 22d76fe

Please sign in to comment.