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

import org.jboss.remoting.transport.socket.SocketClientInvoker;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.invocation.NameBasedInvocation;

import javax.management.ObjectName;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * Simple Remoting-based proxy that can be downloaded (via JNDI) into the client's address space. Uses
 * java.lang.reflect.Proxy to handle all method calls, and uses remoteURI (identifies the server) and
 * targetObject (identifies the target MBean on the server side) to dispatch requests using Remoting
 * @author Bela Ban
 * @version $Id: TreeCacheProxy.java,v 1.1.2.2 2005/04/06 21:07:11 starksm Exp $
 */
public class TreeCacheProxy implements Serializable, InvocationHandler
{
   static final long serialVersionUID = -4485997268761451933L;

   String remoteURI=null;
   SocketClientInvoker invoker;
   ObjectName targetObject=null;

   public TreeCacheProxy(String remoteURI, ObjectName targetObject) {
      this.remoteURI=remoteURI;
      this.targetObject=targetObject;
   }


   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
      InvokerLocator invokerLocator=new InvokerLocator(remoteURI);
      if(invoker == null) {
         invoker=new SocketClientInvoker(invokerLocator);
      }

      // ObjectName name, String operationName, Object[] params, String[] signature)
      NameBasedInvocation arg;
      arg=new NameBasedInvocation("invoke",
                                  new Object[]{targetObject, method.getName(), args, generateSignatureFromMethod(method)},
                                  new String[]{ObjectName.class.getName(), String.class.getName(),
                                  Object[].class.getName(), String[].class.getName()});
      InvocationRequest req=new InvocationRequest("bla", "JBossCache", arg, null, null, invokerLocator);
      return invoker.invoke(req);
   }


   private String[] generateSignatureFromMethod(final Method method) {
      Class[] parameterTypes=method.getParameterTypes();
      String[] signature=new String[parameterTypes.length];
      for(int i=0; i < parameterTypes.length; i++) {
         Class parameterType=parameterTypes[i];
         signature[i]=parameterType.getName();
      }
      return signature;
   }
}