Is there any way to stop Apache Tomcat using Java and JMX?
I suppose that there is a a managed bean which can be used for this?
By its own the Tomcat does not come with the ability to shutdown operation run from the JMX, basically it is not secure !!! But if you really need it you need to create your own ShutdownMBean. It is very easy and straight forward process of creating the MBean and registering it at application deploy.
Lets first create the ShutdownMBean whch will have name and will expose a single doShutdown() operation.
public interface ShutdownMBean {
void doShutdown();
String getName();
}
The implementation is easy as well, just send SHUTDOWN signal to default shutdown port of Tomcat.
public class Shutdown implements ShutdownMBean{
@Override
public void doShutdown() {
try {
Socket clientSocket = new Socket("localhost", 8005);
clientSocket.getOutputStream().write("SHUTDOWN".getBytes());
clientSocket.getOutputStream().close();
clientSocket.close();
} catch (IOException e) {
}
}
@Override
public String getName() {
return "Shutdown JMX Hook";
}
}
And at the end just register the ShutdownMBean after context initialization (I assume you are using Tomcat 7+):
@WebListener
public class ShutdownListener implements javax.servlet.ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
try {
ShutdownMBean shutdownMBean = new Shutdown();
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=Shutdown");
server.registerMBean(shutdownMBean, name);
} catch (InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException | MalformedObjectNameException e) {
}
}
}
Thats it, just deploy your app, connect to your Tomcat using JConsole and you will find doShutdown operation under com.example group
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