/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.mx.modelmbean;

import java.lang.reflect.Constructor;

import javax.management.modelmbean.ModelMBean;
import javax.management.modelmbean.ModelMBeanInfo;

import org.jboss.mx.server.ServerConstants;
import org.jboss.mx.util.PropertyAccess;

/**
 * ModelMBean instantiator. The ModelMBean implementation
 * can be configured by setting a <tt>jbossmx.required.modelmbean.class</tt>
 * system property.
 *
 * @see javax.management.modelmbean.ModelMBean
 *
 * @author  <a href="mailto:juha@jboss.org">Juha Lindfors</a>.
 * @author  <a href="mailto:Adrian@jboss.org">Adrian Brock</a>.
 * @version $Revision: 1.4 $
 */
public class RequiredModelMBeanInstantiator
{
   public static ModelMBean instantiate()
   {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      String className = getClassName();
      try
      {
         Class modelMBean = cl.loadClass(className);
         return (ModelMBean) modelMBean.newInstance();  
      }
      catch (ClassNotFoundException e)
      {
         throw new Error("Cannot instantiate model mbean class. Class " + className + " not found.");
      }
      catch (ClassCastException e) 
      {
         throw new Error("Cannot instantiate model mbean class. The target class is not an instance of ModelMBean interface.");
      }
      catch (Exception e) 
      {
         throw new Error("Cannot instantiate model mbean class " + className + " with default constructor: " + e.getMessage());      
      }
   }

   public static ModelMBean instantiate(ModelMBeanInfo info)
   {
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      String className = getClassName();
      try 
      {
         Class modelMBean = cl.loadClass(className);
         Constructor constructor = modelMBean.getConstructor(new Class[] { ModelMBeanInfo.class });
         return (ModelMBean) constructor.newInstance(new Object[] { info });  
      }
      catch (ClassNotFoundException e)
      {
         throw new Error("Cannot instantiate model mbean class. Class " + className + " not found.");
      }
      catch (ClassCastException e) 
      {
         throw new Error("Cannot instantiate model mbean class. The target class is not an instance of ModelMBean interface.");
      }
      catch (Exception e) 
      {
         throw new Error("Cannot instantiate model mbean class " + className + ": " + e.toString());      
      }
   }

   public static String getClassName()
   {
      return PropertyAccess.getProperty
      (
            ServerConstants.REQUIRED_MODELMBEAN_CLASS_PROPERTY,
            ServerConstants.DEFAULT_REQUIRED_MODELMBEAN_CLASS
      );
   }
}