/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import javax.management.ObjectName;
import javax.management.MBeanServer;
import javax.management.MBeanException;
import javax.management.ReflectionException;

/**
 * InvocationHandler delegate the MBeanServer invoke the actually operation
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class MBeanInvocationHandler implements InvocationHandler {
  private MBeanServer server = null;
  private ObjectName objectName = null;

  public MBeanInvocationHandler(MBeanServer server, ObjectName objectName) {
    this.server = server;
    this.objectName = objectName;
  }

  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    if (args == null) args = new Object[0];
    Class[] types = method.getParameterTypes();
    String[] signature = new String[types.length];
    for (int i = 0; i < types.length; i++) {
       signature[i] = types[i].getName();
    }
    try{
       return server.invoke(objectName, method.getName(), args, signature);
    }
    catch (MBeanException e){
       throw e.getTargetException();
    }
    catch (ReflectionException e) {
       throw e.getTargetException();
    }
  }

}
