/*
 * JBoss, the OpenSource J2EE webOS
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package test.compliance.server.support;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import javax.management.MBeanServer;

/**
 * A wrapper for an MBeanServer
 *
 * @author  <a href="mailto:Adrian.Brock@HappeningTimes.com">Adrian Brock</a>.
 * @version $Revision: 1.3.2.1 $
 */
public class MBeanServerWrapper
   implements InvocationHandler
{
   public MBeanServer server;

   public boolean invoked = false;

   private static Method EQUALS;

   static
   {
      try
      {
         EQUALS = Object.class.getClass().getMethod("equals", new Class[] { Object.class });
      }
      catch (Exception e)
      {
         throw new RuntimeException(e.toString());
      }
   }

   public static MBeanServer getWrapper()
   {
      return (MBeanServer) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), 
                                                  new Class[] { MBeanServer.class },
                                                  new MBeanServerWrapper());
   }

   public static MBeanServerWrapper getHandler(MBeanServer proxy)
   {
      return (MBeanServerWrapper) Proxy.getInvocationHandler(proxy);
   }

   public Object invoke(Object proxy, Method method, Object[] args)
      throws Throwable
   {
      invoked = true;
      if (method.equals(EQUALS))
         return new Boolean(proxy == args[0]);
      if (method.getName().equals("queryMBeans"))
         throw new MBeanServerReplaced();
      return method.invoke(server, args);
   }
}
