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
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 are on linux, you could check if the process is running by
ps aux | grep tomcat
On Linux, you could also check status of tomcat service.
sudo service tomcat7 status
If you are on windows, check task manager. It should appear as a javaw.exe process.
If you want to perform some logic on Tomcat initialization, you can write code within a ServletContextListener.
https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html
Simply write a class that implements ServletContextListener and implement the contextInitialized method.
Next, add the listener entry to web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>
example.ServletContextExample
</listener-class>
</listener>
</web-app>