Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check inside Java code if the server is running in localhost

Tags:

java

tomcat7

I have the need to check at runtime if the server is running in http://localhost Searching on the net I haven't found any good solution. Some advice?

Thank you

like image 886
salgaf Avatar asked Sep 30 '15 10:09

salgaf


2 Answers

We have a running setup where the following configuration is being done:

  1. In catalina.properties, define active_profile=prod for production, active_profile=stage for stage or active_profile=dev for developer machine
  2. Have different connection properties files matching to the profile key - jdbc_prod.properties, jdbc_stage.properties, jdbc_dev.properties
  3. Refer to the connection properties as jdbc_${active_profile}.properties in your configuration.
like image 195
James Jithin Avatar answered Sep 18 '22 12:09

James Jithin


You can try open a connection to localhost, if no exception was throw, then your server is running.

from doc: https://docs.oracle.com/javase/tutorial/networking/urls/connecting.html

try {
    URL myURL = new URL("http://localhost");
    // also you can put a port 
   //  URL myURL = new URL("http://localhost:8080");
    URLConnection myURLConnection = myURL.openConnection();
    myURLConnection.connect();
} 
catch (MalformedURLException e) { 
    // new URL() failed
    // ...
} 
catch (IOException e) {   
    // openConnection() failed
    // ...
}

Another way is to get all process name and check if one matches what you expect, the problem with this solution is that is not platform independent. In Java 9 it will be independent.

             try {                                      
                //linux 
                //Process process = Runtime.getRuntime().exec("ps -few");

                //windows
                Process process = Runtime.getRuntime().exec(System.getenv("windir") +"\\system32\\"+"tasklist.exe /fo csv /nh");                                

                BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));                             
                boolean isRunning = input.lines().anyMatch(p -> p.contains("your process name"));

                input.close();

            } catch (Exception err) {
                err.printStackTrace();
            }
like image 30
Johnny Willer Avatar answered Sep 18 '22 12:09

Johnny Willer