/*
 * JBoss, the OpenSource EJB server
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.util;

import java.io.*;
import java.net.*;
import java.util.*;

import javax.management.*;

import org.jboss.logging.Logger;

/**
 *   <description> 
 *      
 *   @see <related>
 *   @author Rickard Öberg (rickard.oberg@telkel.com)
 *   @version $Revision: 1.2.6.2 $
 */
public class Shutdown
   implements MBeanRegistration, ShutdownMBean
{
   // Constants -----------------------------------------------------
   public static final String OBJECT_NAME = ":type=Shutdown";
    
   // Attributes ----------------------------------------------------
   static Logger log = Logger.getLogger(Shutdown.class);

   List mbeans = new ArrayList();
   MBeanServer server;
   
   // Public  -------------------------------------------------------
   public void shutdown()
   {
      new Thread()
      {
         public void run()
         {
            log.info("Shutting down the JVM now!");
            System.exit(0); // This will execute the shutdown hook
         }
      }.start();
   }
   
   // MBeanRegistration implementation ------------------------------
   public ObjectName preRegister(final MBeanServer server, ObjectName name)
      throws java.lang.Exception
   {
      this.server = server;
      try
      {
         Runtime.getRuntime().addShutdownHook(new Thread()
         {
            public void run()
            {
               System.out.println("Shutting down");
               
               // Make sure all services are down properly
               shutdownServices();
               
               System.out.println("Shutdown complete");
            }
         });
         log.info("Shutdown hook added");
      } catch (Throwable e)
      {
         log.error("Could not add shutdown hook", e);
      }
      return name == null ? new ObjectName(OBJECT_NAME) : name;
   }

   public void postRegister(java.lang.Boolean registrationDone)
   {
   }
   
   public void preDeregister()
      throws java.lang.Exception
   {
   }
   
   public void postDeregister()
   {
   }
   
   protected void shutdownServices()
   {
      try
      {
         // Stop services
         server.invoke(new ObjectName(":service=ServiceControl"), "stop", new Object[0] , new String[0]);
      } catch (Exception e)
      {
         log.error("stop of ServiceControl failed", e);
      }

      try
      {
         // Destroy services
         server.invoke(new ObjectName(":service=ServiceControl"), "destroy", new Object[0] , new String[0]);
      } catch (Exception e)
      {
         log.error("destroy of ServiceControl failed", e);
      }
   }
}


