/***************************************
 *                                     *
 *  JBoss: The OpenSource J2EE WebOS   *
 *                                     *
 *  Distributable under LGPL license.  *
 *  See terms of license at gnu.org.   *
 *                                     *
 ***************************************/
package org.jboss.remoting.transport.async;

import java.io.IOException;

import org.jboss.logging.Logger;
import org.jboss.remoting.ConnectionFailedException;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.RemoteClientInvoker;

/**
 * AsyncClientInvoker uses sockets to remotely connect to the 
 * a remote AsyncServerInvoker.  Requests are sent asynchronously 
 * to allow more concurrent requests to be sent to the server
 * while using fewer sockets.  This is also known as the 'async'
 * protocol.
 * 
 * TODO:
 * If you are running on Java 1.4, this transport
 * transport will take advantage of the NIO 
 * classes to further reduce the resources used on the server.
 *
 * @author <a href="mailto:hiram@coredevelopers.net">Hiram Chirino</a>
 */
public class AsyncClientInvoker extends RemoteClientInvoker  {

	static final Logger log = Logger.getLogger(AsyncClientInvoker.class);
	private ChannelPool pool;
	InvokerLocator uri;

	/**
	 * @param cl
	 * @param locator
	 */
	public AsyncClientInvoker(InvokerLocator locator) {
		super(locator);
		uri = locator;
	}

	/* (non-Javadoc)
	 * @see org.jboss.remoting.ClientInvoker#handleConnect()
	 */
	protected void handleConnect() throws ConnectionFailedException {
		try {
			log.trace("Connecting to: " + uri.getLocatorURI());
			this.pool = Registry.getChannelPool(uri);
			this.pool.connect();
		} catch (IOException e) {
			this.connected = false;
			throw new ConnectionFailedException(
				"Failed to connect to: " + uri.getLocatorURI()+" : "+e);
		}
	}

	/* (non-Javadoc)
	 * @see org.jboss.remoting.ClientInvoker#handleDisconnect()
	 */
	protected void handleDisconnect() {
		if (this.pool != null) {
			this.pool.disconnect();
			this.pool = null;
		}
	}

	protected void finalize() throws Throwable {
		disconnect();
		super.finalize();
	}

	/* (non-Javadoc)
	 * @see org.jboss.remoting.ClientInvoker#transport(java.lang.String, byte[])
	 */
	protected byte[] transport(String sessionId, byte[] buffer)
		throws IOException, ConnectionFailedException {
		if (connected == false) 
			connect();
			
		return pool.sendRequest(buffer);
	}

}
