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
We have a running setup where the following configuration is being done:
catalina.properties
, define active_profile=prod
for production, active_profile=stage
for stage or active_profile=dev
for developer machinejdbc_prod.properties
, jdbc_stage.properties
, jdbc_dev.properties
jdbc_${active_profile}.properties
in your configuration.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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With