Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
  * JBoss, Home of Professional Open Source
  * Copyright 2005, JBoss Inc., and individual contributors as indicated
  * by the @authors tag. See the copyright.txt in the distribution for a
  * full listing of individual contributors.
  *
  * This is free software; you can redistribute it and/or modify it
  * under the terms of the GNU Lesser General Public License as
  * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */
 
 package org.jboss.remoting.transporter;
 
 import  org.jboss.logging.Logger;
 
 
Class to be used as a factory via static method calls to get remote proxy to POJO that exists within a external process. Note, if using clustered, will use the multicast detector by default.

Author(s):
Tom Elrod
 
 public class TransporterClient implements InvocationHandlerSerializable
 {
    private Client remotingClient = null;
    private boolean isClustered = false;
    private String subSystem = null;
 
    private LoadBalancer loadBalancer = new DefaultLoadBalancer();
 
    private final Logger log = Logger.getLogger(TransporterClient.class);
    private static final long serialVersionUID = 7418567482011657189L;

   
Creates the remoting client to server POJO. Is not clustered.

Parameters:
locator
Throws:
Exception
 
    private TransporterClient(InvokerLocator locatorthrows Exception
    {
        = new Client(locator);
       .connect();
    }

   
Creates the remoting client to server POJO. Is clustered

Parameters:
locator
targetSubsystem
Throws:
Exception
 
    private TransporterClient(InvokerLocator locatorString targetSubsystemthrows Exception
    {
        = new Client(locatortargetSubsystem);
       .connect();
       this. = true;
       this. = targetSubsystem;
    }

   
Creates the remoting client to server POJO. Is clustered

Parameters:
locator
targetSubsystem
loadbalancer policy
Throws:
Exception
   private TransporterClient(InvokerLocator locatorString targetSubsystemLoadBalancer loadbalancerthrows Exception
   {
      this. = loadbalancer;
       = new Client(locatortargetSubsystem);
      .connect();
      this. = true;
      this. = targetSubsystem;
   }

   
Disconnects the remoting client
   private void disconnect()
   {
      if ( != null)
      {
         .disconnect();
      }
   }

   
Will set up network registry and detector for clustering (to identify other remoting servers running on network).

Throws:
Exception
   private static void setupDetector() throws Exception
   {
      InternalTransporterServices services = InternalTransporterServices.getInstance();
      // if no one has setup our internal services yet, let's do it now
      if (!services.isSetup())
      {
         // we need an MBeanServer to store our network registry and multicast detector services
         MBeanServer server = createMBeanServer();
         // multicast detector will detect new network registries that come online
         MulticastDetector detector = new MulticastDetector();
         NetworkRegistry registry = NetworkRegistry.getInstance();
         services.setup(serverdetectornullregistrynulltruetrue);
         detector.start();
      }
      else
      {
         // the internal services singleton is already setup, but make sure it has the services we need
         if (services.getDetector() == null)
         {
            MulticastDetector detector = new MulticastDetector();
            services.assignDetector(detectornulltrue);
            detector.start();
         }
         if (services.getNetworkRegistry() == null)
         {
            NetworkRegistry registry = NetworkRegistry.getInstance();
            services.assignNetworkRegistry(registrynulltrue);
         }
      }
      return;
   }

   
Create a remote proxy to a POJO on a remote server.

Parameters:
locatorURI - the remoting locator uri to the target server where the target POJO exists.
targetClass - the interface class of the POJO will be calling upon.
clustered - true will cause the transporter to look for other remoting serves that have the POJO running and include it in the client's target list. If a call on first target fails, will seamlessly fail over to one of the other discovered targets.
Returns:
dynamic remote proxy typed to the interface specified by the targetClass param.
Throws:
Exception
   public static Object createTransporterClient(String locatorURIClass targetClassboolean clusteredthrows Exception
   {
      if (!clustered)
      {
         return createTransporterClient(locatorURItargetClass);
      }
      else
      {
         if (InternalTransporterServices.getInstance().getNetworkRegistry() == null)
         {
            setupDetector();
         }
         InvokerLocator locator = new InvokerLocator(locatorURI);
         TransporterClient client = new TransporterClient(locatortargetClass.getName());
         ClassLoader tcl = (ClassLoader) AccessController.doPrivilegednew PrivilegedAction()
         {
            public Object run()
            {
               return Thread.currentThread().getContextClassLoader();
            }
         });
         return Proxy.newProxyInstance(tclnew Class[]{targetClass}, client);
      }
   }

   
Create a remote proxy to a POJO on a remote server.

Parameters:
locatorURI - the remoting locator uri to the target server where the target POJO exists.
targetClass - the interface class of the POJO will be calling upon.
loadBalancer - policy for selecting which target server to use from list of available servers.
Returns:
dynamic remote proxy typed to the interface specified by the targetClass param.
Throws:
Exception
   public static Object createTransporterClient(String locatorURIClass targetClassLoadBalancer loadBalancerthrows Exception
   {
         if (InternalTransporterServices.getInstance().getNetworkRegistry() == null)
         {
            setupDetector();
         }
         InvokerLocator locator = new InvokerLocator(locatorURI);
         TransporterClient client = new TransporterClient(locatortargetClass.getName(), loadBalancer);
         ClassLoader tcl = (ClassLoader) AccessController.doPrivilegednew PrivilegedAction()
         {
            public Object run()
            {
               return Thread.currentThread().getContextClassLoader();
            }
         });
         return Proxy.newProxyInstance(tclnew Class[]{targetClass}, client);
   }

   
Create a remote proxy to a POJO on a remote server.

Parameters:
locatorURI - the remoting locator uri to the target server where the target POJO exists.
targetClass - the interface class of the POJO will be calling upon.
Returns:
dynamic remote proxy typed to the interface specified by the targetClass param.
Throws:
Exception
   public static Object createTransporterClient(String locatorURIClass targetClassthrows Exception
   {
      InvokerLocator locator = new InvokerLocator(locatorURI);
      return createTransporterClient(locatortargetClass);
   }

   
Create a remote proxy to a POJO on a remote server.

Parameters:
locator - the remoting locator to the target server where the target POJO exists.
targetClass - the interface class of the POJO will be calling upon.
Returns:
dynamic remote proxy typed to the interface specified by the targetClass param.
Throws:
Exception
   public static Object createTransporterClient(InvokerLocator locatorClass targetClassthrows Exception
   {
      TransporterClient client = new TransporterClient(locatortargetClass.getName());
      ClassLoader tcl = (ClassLoader) AccessController.doPrivilegednew PrivilegedAction()
      {
         public Object run()
         {
            return Thread.currentThread().getContextClassLoader();
         }
      });
      return Proxy.newProxyInstance(tclnew Class[]{targetClass}, client);
   }

   
Needs to be called by user when no longer need to make calls on remote POJO. Otherwise will maintain remote connection until this is called.

Parameters:
transporterClient
   public static void destroyTransporterClient(Object transporterClient)
   {
      if (transporterClient instanceof Proxy)
      {
         InvocationHandler handler = Proxy.getInvocationHandler(transporterClient);
         if (handler instanceof TransporterClient)
         {
            TransporterClient client = (TransporterClienthandler;
            client.disconnect();
         }
         else
         {
            throw new IllegalArgumentException("Object is not a transporter client.");
         }
      }
      else
      {
         throw new IllegalArgumentException("Object is not a transporter client.");
      }
   }

   
The method called when anyone calls on the dynamic proxy returned by getProcessor(). This method will simply convert the proxy call info into a remoting invocation on the target remoting server (using a NameBaseInvocation).

Parameters:
proxy
method
args
Returns:
Throws:
Throwable
   public Object invoke(Object proxyMethod methodObject[] argsthrows Throwable
   {
      String methodName = method.getName();
      String[] paramSig = createParamSignature(method.getParameterTypes());
      NameBasedInvocation request = new NameBasedInvocation(methodName,
                                                            args,
                                                            paramSig);
      Object response = null;
      boolean failOver = false;
      do
      {
         try
         {
            failOver = false;
            response = .invoke(request);
         }
         catch (CannotConnectException cnc)
         {
            failOver = findAlternativeTarget();
            if (!failOver)
            {
               throw cnc;
            }
         }
         catch (InvocationTargetException itex)
         {
            Throwable rootEx = itex.getCause();
            throw rootEx;
         }
      }
      while (failOver);
      return response;
   }

   
Will check to see if the network registry has found any other remoting servers. Then will check to see if any of them contain the subsystem we are interested in (which will corespond to the proxy type we are using). If one is found, will try to create a remoting client and connect to it. If can't find one, will return fasle.

Returns:
   private boolean findAlternativeTarget()
   {
      boolean failover = false;
      ArrayList availableList = new ArrayList();
      NetworkRegistry registry = InternalTransporterServices.getInstance().getNetworkRegistry();
      if (registry != null)
      {
         NetworkInstance[] instances = registry.getServers();
         if (instances != null)
         {
            for (int x = 0; x < instances.lengthx++)
            {
               NetworkInstance netInstance = instances[x];
               ServerInvokerMetadata[] metadata = netInstance.getServerInvokers();
               for (int i = 0; i < metadata.lengthi++)
               {
                  ServerInvokerMetadata data = metadata[i];
                  String[] subsystems = data.getSubSystems();
                  for (int z = 0; z < subsystems.lengthz++)
                  {
                     if (.equalsIgnoreCase(subsystems[z]))
                     {
                        availableList.add(data);
                     }
                  }
               }
            }
            //If alternative servers are found
            if (availableList.size() > 0)
            {
               int index = .selectServer(availableList);
               if (.isDebugEnabled())
               {
                  .debug("Total of " + availableList.size() + " available servers found.");
                  .debug("Using server number " + index);
               }
               //reconnect to the new server
               ServerInvokerMetadata data = (ServerInvokerMetadataavailableList.get(index);
               InvokerLocator newLocator = data.getInvokerLocator();
               if (!.getInvoker().getLocator().equals(newLocator))
               {
                  try
                  {
                      = new Client(newLocator);
                     .connect();
                     return true;
                  }
                  catch (Exception e)
                  {
                     .warn("Problem connecting to newly found alternate target."e);
                  }
               }
            }
         }
      }
      return failover;
   }

   
Converts the Class array supplied via the dynamic proxy to a String array of the respective class names, which is need by the NameBasedInvocation object.

Parameters:
args
Returns:
   private String[] createParamSignature(Class[] args)
   {
      if (args == null || args.length == 0)
      {
         return new String[]{};
      }
      String[] paramSig = new String[args.length];
      for (int x = 0; x < args.lengthx++)
      {
         paramSig[x] = args[x].getName();
      }
      return paramSig;
   }
   static private MBeanServer createMBeanServer() throws Exception
   {
      if (SecurityUtility.skipAccessControl())
      {
         return MBeanServerFactory.createMBeanServer();
      }
      
      try
      {
         return (MBeanServer) AccessController.doPrivilegednew PrivilegedExceptionAction()
         {
            public Object run() throws Exception
            {
               return MBeanServerFactory.createMBeanServer();
            }
         });
      }
      catch (PrivilegedActionException e)
      {
         throw (Exceptione.getCause();
      }   
   }
New to GrepCode? Check out our FAQ X