/*
 * JBoss, Home of Professional Open Source
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.invocation.pooled.interfaces;

import java.io.Serializable;
import javax.net.SocketFactory;

/**
 * This class encapsulates all the required information for a client to 
 * establish a connection with the server.
 * 
 * It also attempts to provide a fast hash() function since this object
 * is used as a key in a hashmap mainted by the ConnectionManager. 
 *
 * @author Bill Burke
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.4.6.1 $
 */
public class ServerAddress implements Serializable
{
   /** The serialVersionUID @since 1.1.4.1 */
   private static final long serialVersionUID = -7206359745950445445L;

   /**
    * Address of host to connect to
    * @serial
    */
   public String address;

   /**
    * Port the service is listening on
    * @serial
    */
   public int port;

   /**
    * If the TcpNoDelay option should be used on the socket.
    * @serial
    */
   public boolean enableTcpNoDelay = false;

   /**
    * Timeout of setSoTimeout
    * @serial
    */
   public int timeout = 60000;
   /** An option socket factory for connecting to the server
    * @serial
    */
   public SocketFactory clientSocketFactory;

   /**
    * This object is used as a key in a hashmap,
    * so we precompute the hascode for faster lookups.
    */
   private transient int hashCode;

   /**
    * The server address/port representation.
    * 
    * @param address - hostname/ip of the server
    * @param port - the invoker port
    * @param enableTcpNoDelay - the Socket.setTcpNoDelay flag
    * @param timeout - the Socket.setSoTimeout value
    * @param clientSocketFactory - optional SocketFactory
    */ 
   public ServerAddress(String address, int port, boolean enableTcpNoDelay,
      int timeout, SocketFactory clientSocketFactory)
   {
      this.address = address;
      this.port = port;
      this.enableTcpNoDelay = enableTcpNoDelay;
      this.hashCode = address.hashCode() + port;
      this.timeout = timeout;
      this.clientSocketFactory = clientSocketFactory;
   }

   public String toString()
   {
      return "[address:" + address + ",port:" + port + ",enableTcpNoDelay:" + enableTcpNoDelay + "]";
   }

   public boolean equals(Object obj)
   {
      try
      {
         ServerAddress o = (ServerAddress) obj;
         if (o.hashCode != hashCode)
            return false;
         if (port != port)
            return false;
         if (!o.address.equals(address))
            return false;
         if (o.enableTcpNoDelay != enableTcpNoDelay)
            return false;
         return true;
      }
      catch (Throwable e)
      {
         return false;
      }
   }

   public int hashCode()
   {
      return hashCode;
   }

}
