/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
package javax.management;

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.management.loading.ClassLoaderRepository;
import javax.management.loading.DefaultLoaderRepository;

import org.jboss.mx.server.ServerConstants;

/**
 * MBeanServerFactory is used to create instances of MBean servers.
 *
 * @see javax.management.MBeanServer
 * @see javax.management.MBeanServerBuilder
 *
 * @author  <a href="mailto:juha@jboss.org">Juha Lindfors</a>.
 * @author  <a href="mailto:Adrian.Brock@HappeningTimes.com">Adrian Brock</a>.
 * @version $Revision: 1.4.8.3 $
 *
 * <p><b>Revisions:</b>
 *
 * <p><b>20030806 Juha Lindfors:</b>
 * <ul>
 * <li>
 *   Attempts a reflected invoke to "releaseServer" method on the MBean server
 *   instance before letting go of the server reference. This allows the
 *   MBean server to do some clean up. Based on the patch submitted by
 *   Rod Burgett (Bug Tracker: #763378)
 * </ul>
 */
public class MBeanServerFactory
{

   // Constants -----------------------------------------------------

   private static final MBeanServerPermission CREATE =
      new MBeanServerPermission("createMBeanServer", null);
   private static final MBeanServerPermission FIND = 
      new MBeanServerPermission("findMBeanServer", null);
   private static final MBeanServerPermission NEW = 
      new MBeanServerPermission("newMBeanServer", null);
   private static final MBeanServerPermission RELEASE = 
      new MBeanServerPermission("releaseMBeanServer", null);


   // Attributes ----------------------------------------------------

   /**
    * Hold on to the server instances here (unless requested not to)
    */
   private static Map serverMap = new HashMap();


   // Public --------------------------------------------------------

   /**
    * Releases the reference to an MBean server. A security permission check
    * is made first if security manager has been installed.
    *
    * @param mbeanServer reference to the MBean server you want to release
    */
   public static void releaseMBeanServer(MBeanServer mbeanServer)
   {
      checkPermission(RELEASE);
      try
      {
         String agentID = (String)mbeanServer.getAttribute(
               new ObjectName(ServerConstants.MBEAN_SERVER_DELEGATE),
               "MBeanServerId"
         );

         Object server = serverMap.remove(agentID);

         try
         {
            Method m = server.getClass().getMethod("releaseServer", null);
            m.invoke(server, null);
         }
         catch (Exception ignored)
         {
            // if the release fails, then it fails
         }

         if (server == null)
            throw new IllegalArgumentException("MBean server reference not found.");
      }
      catch (MalformedObjectNameException e)
      {
         throw new Error(e.toString());
      }
      catch (JMException e)
      {
         throw new Error("Cannot retrieve AgentID: " + e.toString());
      }
   }

   public static MBeanServer createMBeanServer()
   {
      checkPermission(CREATE);
      return createMBeanServer(ServerConstants.DEFAULT_DOMAIN);
   }

   public static MBeanServer createMBeanServer(String domain)
   {
      checkPermission(CREATE);
      return createMBeanServer(domain, true);
   }

   public static MBeanServer newMBeanServer()
   {
      checkPermission(NEW);
      return newMBeanServer(ServerConstants.DEFAULT_DOMAIN);
   }

   public static MBeanServer newMBeanServer(String domain)
   {
      checkPermission(NEW);
      return createMBeanServer(domain, false);
   }

   public static ArrayList findMBeanServer(String agentId)
   {
      checkPermission(FIND);
      if (agentId != null)
      {
         ArrayList list = new ArrayList(1);
         Object server = serverMap.get(agentId);
         
         if (server != null)
            list.add(server);
            
         return list;
      }

      return new ArrayList(serverMap.values());
   }

   /**
    * Returns the classloader repository for an MBeanServer
    *
    * @todo implement this, currently it just returns a wrapper for the default
    *       loader repository
    *
    * @param server the mbean server, pass null for the default loader repository
    *        shared by all mbeanservers
    * @return the loader repository
    */
   public static ClassLoaderRepository getClassLoaderRepository(MBeanServer server)
   {
      return new DefaultLoaderRepositoryWrapper();
   }


   // Private -------------------------------------------------------

   private static MBeanServer createMBeanServer(String defaultDomain, boolean registerServer)
   {
      String builderClass = System.getProperty(
            ServerConstants.MBEAN_SERVER_BUILDER_CLASS_PROPERTY,
            ServerConstants.DEFAULT_MBEAN_SERVER_BUILDER_CLASS
      );

      try
      {
         ClassLoader cl = Thread.currentThread().getContextClassLoader();
         Class clazz = cl.loadClass(builderClass);
         Constructor constructor = clazz.getConstructor(new Class[0]);
         MBeanServerBuilder builder = (MBeanServerBuilder)constructor.newInstance(new Object[0]);

         MBeanServerDelegate delegate = builder.newMBeanServerDelegate();
         MBeanServer server = builder.newMBeanServer(defaultDomain, null, delegate);

         if (registerServer)
         {
            String agentID = delegate.getMBeanServerId();
            serverMap.put(agentID, server);
         }

         return server;
      }
      catch (ClassNotFoundException e)
      {
         throw new IllegalArgumentException("The MBean server builder implementation class " + builderClass + " was not found: " + e.toString());
      }
      catch (NoSuchMethodException e) 
      {
         throw new IllegalArgumentException("The MBean server builder implementation class " + builderClass + " must contain a default constructor.");
      }
      catch (InstantiationException e) 
      {
         throw new IllegalArgumentException("Cannot instantiate class " + builderClass + ": " + e.toString());
      }
      catch (IllegalAccessException e)
      {
         throw new IllegalArgumentException("Unable to create the MBean server builder instance. Illegal access to class " + builderClass + " constructor: " + e.toString());
      }
      catch (InvocationTargetException e)
      {
         throw new RuntimeException("Unable to create the MBean server builder instance. Class " + builderClass + " has raised an exception in constructor: " + e.getTargetException().toString());
      }
   }

   private static void checkPermission(MBeanServerPermission permission)
   {
      SecurityManager security = System.getSecurityManager();
      if (security == null)
         return;
      security.checkPermission(permission);
   }

   private static class DefaultLoaderRepositoryWrapper
      implements ClassLoaderRepository
   {
      public Class loadClass(String className)
         throws ClassNotFoundException
      {
         return DefaultLoaderRepository.loadClass(className);
      }

      public Class loadClassWithout(ClassLoader loader, String className)
         throws ClassNotFoundException
      {
         return DefaultLoaderRepository.loadClassWithout(loader, className);
      }
      
      public Class loadClassBefore(ClassLoader stop, String className)
         throws ClassNotFoundException
      {
         throw new Error("NYI");
      }
            
   }
}

