Reputation: 330
How do I set a "configuration check" on a web application startup (Tomcat or other) and if the condition is not met the application should not start.
Let's say the application require a the file /tmp/dummy to exist on the fs in order to start. So I have something like
public class TestConfig {
public static void TestServerConfiguration() {
if (! new File("/tmp/dummy").exists()) {
// don't start this web application ...
}
}
}
Where should I include this test?
Thanks!
Upvotes: 0
Views: 254
Reputation: 17435
I would go with a ServletContextListner. As with the servlet answer, it will not stop Tomcat but it will prevent the web application from loading. One advantage over the servlet answer is from the Javadoc:
All ServletContextListeners are notified of context initialization before any filters or servlets in the web application are initialized.
As an example:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class FileVerifierContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
// verify that the file exists. if not, throw a RuntimeException
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
Above assumes that your web.xml
specifies a Servlet 3.0 or above environment (or that you don't have a web.xml
at all):
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
</web-app>
If you're using a lower servlet spec then you'll want to remove the @WebListener
annotation and declare the listener in web.xml
:
<web-app ...>
<listener>
<listener-class>
com.example.package.name.FileVerifierContextListener
</listener-class>
</listener>
</web-app>
Upvotes: 2
Reputation: 3174
One idea (but there can be others) is to implement a servlet that will do this check and exit when the condition is false. You need to run it at the beginning of the context deployment with the adequate load-on-startup tag. The web.xml
will then look like :
<servlet>
<display-name>startup condition servlet</display-name>
<servlet-name>startup condition</servlet-name>
<servlet-class>com.xxx.yyy.ConditionChecker</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>FILE_TO_CHECK</param-name>
<param-value>/tmp/dummy</param-value>
</init-param>
</servlet>
This servlet could execute System.exit(1)
when the condition is not met (/tmp/dummy doesn't exist).
Please not this will kill the Tomcat. Not exactly stop the deployment process. If anyone want to fine tune this, you can edit my post.
Upvotes: 0