Thursday, July 8, 2010

Using JMX to restart Glassfish

I needed to restart my Glassfish Application Server from an application. I wanted to keep everything pure Java for simplicity, so I decided to use JMX. The code below successfully calls the Glassfish server instance restart.
I ended up not using this because "restart" is not supported on Windows. But I decided to post this to provide an example of managing Glassfish internally using JMX.

import java.lang.management.ManagementFactory;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.ObjectName;

...

    public void restart() {
      final String domain = "com.sun.appserv";
      final String serversName = domain + ":type=servers,category=config";
      MBeanServer mbeanSvr = ManagementFactory.getPlatformMBeanServer();
      try {
        ObjectName serversObjName = new ObjectName( serversName );

        String[] serverNames = (String[]) mbeanSvr.invoke( serversObjName, "getServerNamesList",
                                                           null, null );
        if( serverNames.length != 1 ) {
          logger.error( "Expected 1 Glassfish server name, found: " +
                        String.valueOf( serverNames.length ));
          if( serverNames.length < 1 ) return;
        }
        final String svrInstName = domain + ":type=server-instance,name=" + serverNames[0];
        ObjectName svrInstObjName = new ObjectName( svrInstName );
        mbeanSvr.invoke( svrInstObjName, "restart", null, null );
      }
      catch( JMException oe ) {
        logger.error( "Cannot restart server", oe );
      }
    }

No comments:

Post a Comment