From 22d76fe384194421f72dcdb8e7815571ddf14244 Mon Sep 17 00:00:00 2001 From: David Corbin Date: Fri, 13 Apr 2018 15:23:43 -0400 Subject: [PATCH] Quit java process if port 8080 is already taken --- src/main/java/com/mygcc/api/Main.java | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/main/java/com/mygcc/api/Main.java b/src/main/java/com/mygcc/api/Main.java index 57fc8f2..e390ddb 100644 --- a/src/main/java/com/mygcc/api/Main.java +++ b/src/main/java/com/mygcc/api/Main.java @@ -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 @@ -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 = @@ -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.