Dear All,
The question of programatically restarting a Tomcat connector came up twice on the Tomcat mailing lists, in recent weeks. I guess that that is a feature that is really wanted.
I sat down and wrote a little JSP page that does precisely that. I hope you find the code useful. Please feel free to comment on it and correct me.
To make this work, open a file named (for example) reset-connector.jsp in one of your webapps and paste the code below into it.
Kees Jan
Code:
<!--
A small piece of code to programatically reset a Tomcat connector using JMX.
Written by Kees Jan Koster and published on Java-monitor.com/forum
-->
<jsp:directive.page import="java.util.*" />
<jsp:directive.page import="javax.management.*" />
<%
// Here, we specify the JMX object name of the connector you'd like to reset.
// Think of the object name not as a human name (Alice, Bob), but as a query.
// You can find this object name using jconsole. We used a bunch of wildcards,
// so that this code will work in any of Tomcat, JBoss and SpringSource dm
// Server or any of the may other projects that have Tomcat embedded.
// In prose, this object name is something like "any mbean that was registered
// to have type 'Connector' and port number 8080, but can have more attributes
// that we don't really care about at this point".
final ObjectName objectNameQuery = new ObjectName("*:type=Connector,port=8080,*");
// We now have to find the right MBean server. A running VM typically contains
// two or so MBean servers. We just root through all of them, to see which one
// has an MBean matching our query. We also get the precise object name for
// the connector MBean. We will need that precise name later.
MBeanServer mbeanServer = null;
ObjectName objectName = null;
for (final MBeanServer server : (List<MBeanServer>) MBeanServerFactory.findMBeanServer(null)) {
if (server.queryNames(objectNameQuery, null).size() > 0) {
mbeanServer = server;
objectName = (ObjectName) server.queryNames(objectNameQuery, null).toArray()[0];
// we found it, bail out
break;
}
}
// now we restart the connector that we just found. We sleep a little, but I am
// not actually sure 1) how long we should sleep for or 2) if sleeping is
// necessary at all.
mbeanServer.invoke(objectName, "stop", null, null);
Thread.sleep(20000);
mbeanServer.invoke(objectName, "start", null, null);
// while it is restarting, consider the security implications of this code... :-)
%>