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

import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * MBeanTyper is a helper class that creates a typed-object from an MBean ObjectName and a main
 * interface class that the MBean implements.  You can then use the returned object (casted to the appropriate
 * main interface class) with the correct typed signatures instead of <tt>mbeanserver.invoke(objectname,<sig>,etc.)</tt>.
 * <P>
 * Example usage: <BR>
 * <code><tt>
 *      MyInterfaceMBean mbean=(MyInterfaceMBean)MBeanTyper.typeMBean(server,new ObjectName(":type=MyBean"),MyInterfaceMBean.class);
 *      mbean.foobar();
 * </tt></code> <P>
 *
 * To turn debug on for this package, set the System property <tt>vocalos.jmx.mbeantyper.debug</tt> to true.
 *
 * @author <a href="mailto:jhaynie@vocalocity.net">Jeff Haynie</a>
 */
public class MBeanTyper
{
    static final boolean DEBUG = Boolean.getBoolean("jboss.jmx.debug");

    /**
     * create a typed object from an mbean
     */
    public static final Object typeMBean(MBeanServer server, ObjectName mbean, Class mainInterface)
            throws Exception
    {
        List interfaces = new ArrayList();
        if (mainInterface.isInterface())
        {
            interfaces.add(mainInterface);
        }
        addInterfaces(mainInterface.getInterfaces(), interfaces);
        Class cl[] = (Class[]) interfaces.toArray(new Class[interfaces.size()]);
        if (DEBUG)
        {
            System.err.println("typeMean->server=" + server + ",mbean=" + mbean + ",mainInterface=" + mainInterface);
            for (int c = 0; c < cl.length; c++)
            {
                System.err.println("     :" + cl[c]);
            }
        }

        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), cl, new MBeanTyperInvoker(server, mbean));
    }

    private static final void addInterfaces(Class cl[], List list)
    {
        if (cl == null) return;
        for (int c = 0; c < cl.length; c++)
        {
            list.add(cl[c]);
            addInterfaces(cl[c].getInterfaces(), list);
        }
    }
}