[jboss-cvs] JBoss Messaging SVN: r5441 - in trunk: examples/messaging/src/org/jboss/messaging/example and 28 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Fri Nov 28 13:59:54 EST 2008


Author: timfox
Date: 2008-11-28 13:59:53 -0500 (Fri, 28 Nov 2008)
New Revision: 5441

Added:
   trunk/src/main/org/jboss/messaging/core/client/ConnectionLoadBalancingPolicy.java
   trunk/src/main/org/jboss/messaging/core/client/ConnectionManager.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ConnectionManagerImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/FirstElementConnectionLoadBalancingPolicy.java
   trunk/src/main/org/jboss/messaging/core/client/impl/RandomConnectionLoadBalancingPolicy.java
   trunk/src/main/org/jboss/messaging/core/client/impl/RoundRobinConnectionLoadBalancingPolicy.java
   trunk/src/main/org/jboss/messaging/util/Random.java
Removed:
   trunk/pom.xml
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
   trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java
Modified:
   trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java
   trunk/src/config/jbm-configuration.xml
   trunk/src/config/jbm-jms.xml
   trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
   trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
   trunk/src/main/org/jboss/messaging/core/config/Configuration.java
   trunk/src/main/org/jboss/messaging/core/config/cluster/BroadcastGroupConfiguration.java
   trunk/src/main/org/jboss/messaging/core/config/cluster/MessageFlowConfiguration.java
   trunk/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java
   trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
   trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/BroadcastGroup.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/DiscoveryGroup.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/impl/BroadcastGroupImpl.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ClusterManagerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/impl/DiscoveryGroupImpl.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ForwarderImpl.java
   trunk/src/main/org/jboss/messaging/core/server/cluster/impl/MessageFlowImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
   trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
   trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
   trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
   trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
   trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
   trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
   trunk/src/main/org/jboss/messaging/util/Pair.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
   trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
   trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/BasicMessageFlowTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/DiscoveryFlowTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchSizeTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchTimeTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowTransformerTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWildcardTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWithFilterTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/StaticFlowTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ActivationTimeoutTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverManagementTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverPreAcknowledgeTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/MultiThreadRandomFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/RandomFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ReplicateConnectionFailureTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleAutomaticFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleManualFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/jms/cluster/JMSFailoverTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/jms/consumer/ConsumerTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSQueueControlTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSUtil.java
   trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java
   trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java
Log:
Mainly client discovery


Modified: trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java
===================================================================
--- trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/examples/messaging/src/org/jboss/messaging/example/SSLClient.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -45,9 +45,9 @@
       ClientSession clientSession = null;
       try
       {         
-         ClientSessionFactory sessionFactory =
-            new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"));
-         sessionFactory.getTransportParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+         TransportConfiguration tc = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
+         tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, true);
+         ClientSessionFactory sessionFactory = new ClientSessionFactoryImpl(tc);         
          clientSession = sessionFactory.createSession(false, true, true);
          SimpleString queue = new SimpleString("queuejms.testQueue");
          ClientProducer clientProducer = clientSession.createProducer(queue);

Deleted: trunk/pom.xml
===================================================================
--- trunk/pom.xml	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/pom.xml	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1,416 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-  <modelVersion>4.0.0</modelVersion>
-  <groupId>jboss.messaging</groupId>
-  <artifactId>jboss-messaging</artifactId>
-  <packaging>jar</packaging>
-  <version>1.0</version>
-  <name>JBoss Messaging</name>
-  <url>http://www.jboss.com/products/messaging</url>
-  <description>JBoss Messaging provides an open source and standards-based messaging platform that brings enterprise-class messaging to the mass market.</description>
-  <licenses>
-   <license>
-      <name>lgpl</name>
-      <url>http://repository.jboss.com/licenses/lgpl.txt</url>
-   </license>
-  </licenses>
-  <organization>
-    <name>JBoss Inc.</name>
-    <url>http://www.jboss.org</url>
-  </organization>
- 
-  <repositories>
-    <repository>
-      <id>jboss</id>
-      <name>JBoss Inc. Repository</name>
-      <layout>default</layout>
-      <url>http://repository.jboss.com/maven2/</url>
-      <snapshots>
-        <enabled>true</enabled>
-      </snapshots>
-    </repository>
-  </repositories>
-
-  <pluginRepositories>
-     <pluginRepository>
-        <id>jbosspluginrepo</id>
-        <name>jboss plugin repository</name>
-        <url>http://repository.jboss.com/maven2</url>
-        <layout>default</layout>
-        <snapshots>
-           <enabled>false</enabled>
-           <updatePolicy>never</updatePolicy>
-        </snapshots>
-     </pluginRepository>
-     <pluginRepository>
-         <id>Maven Snapshots</id>
-         <url>http://snapshots.maven.codehaus.org/maven2/</url>
-         <snapshots>
-           <enabled>true</enabled>
-         </snapshots>
-         <releases>
-           <enabled>false</enabled>
-         </releases>
-       </pluginRepository>
-  </pluginRepositories>
-
-  
-  <build>
-     <sourceDirectory>src/main</sourceDirectory>
-     <!--define our resource files, these will be included in the jar -->
-     <resources>
-        <resource>
-           <directory>src/etc</directory>
-           <includes>
-              <include>aop-messaging-server.xml</include>
-              <include>aop-messaging-client.xml</include>
-           </includes>
-        </resource>
-        <resource>
-           <directory>src/etc/remoting</directory>
-           <includes>
-              <include>remoting-bisocket-service.xml</include>
-           </includes>
-        </resource>
-        <resource>
-           <directory>src/etc/server/default/deploy</directory>
-           <includes>
-              <include>messaging-service.xml</include>
-              <include>connection-factories-service.xml</include>
-              <include>destinations-service.xml</include>
-              <include>hsqldb-persistence-service.xml</include>
-              <include>jms-ds.xml</include>
-           </includes>
-        </resource> 
-        <resource>
-           <directory>src/etc/server/default/config</directory>
-           <includes>
-              <include>messaging-users.properties</include>
-              <include>messaging-roles.properties</include>
-           </includes>
-        </resource>                 
-        <resource>
-           <targetPath>xmdesc</targetPath>
-           <directory>src/etc/xmdesc</directory>
-           <includes>
-              <include>*.xml</include>
-           </includes>
-        </resource>   
-     </resources>
-     
-  <plugins>
-      
-           
-      <!-- define how we want compilation to take place
-           here, we accept most of the defaults but say that we want the
-           optimization flag set, and define the source and target to be 1.4,
-           these setting will be inherited by child projects -->
-      <plugin>
-        <artifactId>maven-compiler-plugin</artifactId>
-        <version>2.0</version>
-          <configuration>
-              <optimize>true</optimize>
-              <source>1.4</source>
-              <target>1.4</target>
-          </configuration>
-      </plugin>  
-
-      <!-- define that we wish to create src jars -->
-      <plugin>
-        <artifactId>maven-source-plugin</artifactId>
-        <inherited>true</inherited>
-       <executions>
-        <execution>
-          <goals>
-            <goal>jar</goal>
-          </goals>
-        </execution>
-      </executions>
-      </plugin>     
-      
-   <!-- generate java files from grammar -->
-   <plugin>
-    <groupId>org.codehaus.mojo</groupId>
-    <artifactId>javacc-maven-plugin</artifactId>
-    <version>2.1</version>
-    <configuration>
-      <packageName>org/jboss/jms/selector</packageName>
-      <sourceDirectory>src/main</sourceDirectory>
-      <isStatic>false</isStatic>
-    </configuration>
-    <executions>
-     <execution>
-      <goals>
-       <goal>javacc</goal>
-      </goals>
-      <id>javacc</id>
-     </execution>
-    </executions>
-   </plugin>       
-  
-            
-   <!-- declare the aop compilation task and run it during the process
-        classes phase -->
-   <plugin>
-      <artifactId>maven-antrun-plugin</artifactId>
-      <version>1.1</version>
-      <inherited>true</inherited>
-        <executions>
-        <execution>
-           <id>aopc</id>         
-           <phase>process-classes</phase>
-           <configuration>
-              <tasks>
-                 <taskdef name="aopc" classname="org.jboss.aop.ant.AopC"/>
-                        
-                 <aopc compilerclasspathref="maven.compile.classpath"  classpathref="maven.compile.classpath"
-                    verbose="false">
-                    <classpath refid="maven.compile.classpath"/>
-                    <src path="target/classes"/>
-                    <aoppath path="src/etc/prepare-aop.xml"/>
-                 </aopc>
-	                      
-             </tasks>
-          </configuration>
-          <goals>
-             <goal>run</goal>
-          </goals>
-       </execution>   
-        <execution>
-           <id>create-distinct-jars</id>         
-           <phase>package</phase>
-           <configuration>
-              <tasks>
-                 <!-- need to build some specific jars for inclusion in sar -->
-     
-            
-      <jar jarfile="${project.build.directory}/jboss-common-softvaluehashmap.jar">
-         <fileset dir="${project.build.directory}/dependencies" includes="org/jboss/util/collection/SoftValueHashMap*.class"/>
-      </jar>
-
-      
-      <jar jarfile="${project.build.directory}/jboss-common-stream.jar">
-         <fileset dir="${project.build.directory}/dependencies" includes="org/jboss/util/stream/**"/>
-      </jar>
-      
-
-      <!-- I need InvocationMarshaller both on server and client side, and versions prior to
-           JBoss 4.0.3 don't have them, so I need to include them as well. I only need to extract
-           org.jboss.invocation.unified.marshall from jboss.jar, because otherwise I scope classes
-           like javaURLContextFactory, which will mess up JNDI and other things.
-      -->
-
-
-      <jar jarfile="${project.build.directory}/jboss-unified-invocation.jar">
-         <fileset dir="${project.build.directory}/dependencies" includes="org/jboss/invocation/unified/**"/>
-      </jar>
-
-
-
-	                      
-             </tasks>
-          </configuration>
-          <goals>
-             <goal>run</goal>
-          </goals>
-       </execution>          
-       </executions>
-       <dependencies>
-          <dependency>
-             <groupId>jboss.jboss-aop</groupId>
-             <artifactId>jboss-aop</artifactId>
-             <version>1.5.0.GA</version>
-          </dependency>
-          <dependency>
-             <groupId>javassist</groupId>
-             <artifactId>javassist</artifactId>
-             <version>3.1</version>
-          </dependency>
-       </dependencies>         
-    </plugin>      
-  
-  
-    <!-- handle the retrieval and unpacking of dependencies
-         required for the sar -->
-   <plugin>
-        <groupId>org.codehaus.mojo</groupId>
-        <artifactId>dependency-maven-plugin</artifactId>
-        <executions>
-          <execution>
-            <id>unpack-common-core</id>
-            <phase>process-classes</phase>
-            <goals>
-              <goal>unpack</goal>
-            </goals>
-            <configuration>
-                <artifactItems>
-                  <artifactItem>
-                     <groupId>jboss.common.core</groupId>
-                     <artifactId>jboss-common-core</artifactId>
-                     <version>1.0</version>
-                     <type>jar</type>
-                     <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
-                   </artifactItem>
-                 </artifactItems>
-               <outputDirectory>${project.build.directory}</outputDirectory>
-               <overWriteReleases>false</overWriteReleases>
-               <overWriteSnapshots>true</overWriteSnapshots>
-            </configuration>
-          </execution>
-         <execution>
-            <id>unpack-jboss</id>
-            <phase>process-classes</phase>
-            <goals>
-              <goal>unpack</goal>
-            </goals>
-            <configuration>
-                <artifactItems>
-                  <artifactItem>
-                     <groupId>jboss</groupId>
-                     <artifactId>jboss</artifactId>
-                     <version>5.0-SNAPSHOT</version>
-                     <type>jar</type>
-                     <outputDirectory>${project.build.directory}/dependencies</outputDirectory>
-                   </artifactItem>
-                 </artifactItems>
-               <outputDirectory>${project.build.directory}</outputDirectory>
-               <overWriteReleases>false</overWriteReleases>
-               <overWriteSnapshots>true</overWriteSnapshots>
-            </configuration>
-          </execution>        
-        </executions>
-      </plugin>         
-  
-  
-  
-  
-    <!-- create a sar -->
-    <plugin>
-       <groupId>org.codehaus.mojo</groupId>
-       <artifactId>jboss-packaging-maven-plugin</artifactId>
-       <version>2.0-SNAPSHOT</version>
-       <extensions>true</extensions>
-               <executions>
-               <execution>
-                  <id>scopedsar</id>         
-           <phase>package</phase>
-       <configuration>
-          <deploymentDescriptorFile>${basedir}/src/etc/server/default/deploy/jboss-service.xml</deploymentDescriptorFile>
-          <packagingDirectory>${project.build.directory}/scoped-sar</packagingDirectory>
-          <libDirectory>${project.build.directory}/scoped-sar</libDirectory>
-          <excludes>
-             <exclude>jboss:jboss-j2ee</exclude>
-             <exclude>jboss:jboss-j2se</exclude>           
-             <exclude>jboss:jboss-jmx</exclude>
-             <exclude>jboss:jboss-transaction</exclude>              
-             <exclude>jboss.logging:jboss-logging-spi</exclude>              
-             <exclude>jboss:jboss-system</exclude>                           
-             <exclude>jboss:jbosssx</exclude>                                        
-             <exclude>jgroups:jgroups</exclude>                                                     
-             <exclude>apache-log4j:log4j</exclude>    
-             <exclude>apache-httpclient:commons-httpclient</exclude>
-             <exclude>oswego-concurrent:concurrent</exclude>  
-             <exclude>dom4j:dom4j</exclude>  
-             <exclude>jaxen:jaxen</exclude> 
-             <exclude>jboss.common.core:jboss-common-core</exclude>  
-             <exclude>apache-slide:webdavlib</exclude> 
-             <exclude>apache-xerces:xml-apis</exclude>               
-          </excludes>   
-       </configuration>
-       
-       <goals>
-                    <goal>sar</goal>
-                 </goals>
-              </execution>   
-       </executions>
-    </plugin>
-          
-    
-    </plugins>
-  </build>
-  <dependencies>
-      <dependency>
-        <groupId>jboss</groupId>
-        <artifactId>jboss-j2ee</artifactId>
-        <version>SNAPSHOT</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss.jboss-aop</groupId>
-      <artifactId>jboss-aop</artifactId>
-      <version>1.5.0.GA</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss.logging</groupId>
-      <artifactId>jboss-logging-spi</artifactId>
-      <version>1.0</version>
-    </dependency>
-    <dependency>
-      <groupId>oswego-concurrent</groupId>
-      <artifactId>concurrent</artifactId>
-      <version>1.3.4</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss</groupId>
-      <artifactId>jboss-remoting</artifactId>
-      <version>2.0.0.CR1</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss.common.core</groupId>
-      <artifactId>jboss-common-core</artifactId>
-      <version>1.0</version>
-    </dependency>  
-    <dependency>
-      <groupId>jboss</groupId>
-      <artifactId>jboss-serialization</artifactId>
-      <version>1.0.1.GA</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss</groupId>
-      <artifactId>jboss-j2se</artifactId>
-      <version>5.0-SNAPSHOT</version>
-    </dependency>
-    <dependency>
-      <groupId>jboss</groupId>
-      <artifactId>jboss-system</artifactId>
-      <version>5.0-SNAPSHOT</version>
-    </dependency>
-    <dependency>
-      <groupId>jgroups</groupId>
-      <artifactId>jgroups</artifactId>
-      <version>2.3</version>
-    </dependency>
-    <dependency>
-       <groupId>jboss</groupId>
-       <artifactId>jbosssx</artifactId>
-       <version>5.0-SNAPSHOT</version>
-    </dependency> 
-    <dependency>
-       <groupId>jboss</groupId>
-       <artifactId>jboss-jmx</artifactId>
-       <version>5.0-SNAPSHOT</version>
-    </dependency>
-    <dependency>
-       <groupId>jboss</groupId>
-       <artifactId>jboss-transaction</artifactId>
-       <version>5.0-SNAPSHOT</version>
-    </dependency> 
-    <dependency>
-       <groupId>jboss</groupId>
-       <artifactId>jboss</artifactId>
-       <version>5.0-SNAPSHOT</version>
-    </dependency>     
-    <dependency>
-      <groupId>javassist</groupId>
-      <artifactId>javassist</artifactId>
-      <version>3.1</version>
-    </dependency>    
-    <dependency>
-      <groupId>trove</groupId>
-      <artifactId>trove</artifactId>
-      <version>2.1.1</version>
-    </dependency>        
-
-  </dependencies>  
-
-</project>
-

Modified: trunk/src/config/jbm-configuration.xml
===================================================================
--- trunk/src/config/jbm-configuration.xml	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/config/jbm-configuration.xml	2008-11-28 18:59:53 UTC (rev 5441)
@@ -11,7 +11,7 @@
       	<group-address>231.7.7.7</group-address>
       	<group-port>9876</group-port>
       	<broadcast-period>5000</broadcast-period>
-      	<connector-ref connector-name="netty"/>
+      	<connector-ref connector-name="netty" backup-connector-name="netty-backup"/>
       </broadcast-group>
       
       <discovery-group name="dg-group1">
@@ -22,18 +22,18 @@
       
       <message-flow name="jms-distributed-queues">
          <address>jmsqueues.#</address>
-         <discovery-group-name>dg-group1</discovery-group-name>       
+         <discovery-group-ref discovery-group-name="dg-group1"/>       
       </message-flow>
       
       <message-flow name="jms-distributed-topics">
          <address>jmstopics.#</address>
-         <discovery-group-name>dg-group1</discovery-group-name> 
+         <discovery-group-ref discovery-group-name="dg-group1"/>
          <fanout>true</fanout>      
       </message-flow>
       
       <message-flow name="example-static-connectors">
          <address>jmstopics.#</address>
-         <connector-ref connector-name="connector1"/>
+         <connector-ref connector-name="connector1" backup-connector-name="backup-connector1"/>
          <connector-ref connector-name="connector2"/>
          <connector-ref connector-name="connector3"/>
          <fanout>true</fanout>      

Modified: trunk/src/config/jbm-jms.xml
===================================================================
--- trunk/src/config/jbm-jms.xml	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/config/jbm-jms.xml	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,13 +25,20 @@
    </connection-factory>
 
    <connection-factory name="ClusteredConnectionFactory">
-      <connector-ref connector-name="netty"/>
-      <backup-connector connector-name="netty-backup"/>
+      <connector-ref connector-name="netty" backup-connector-name="netty-backup"/>
       <entry name="/ClusteredConnectionFactory"/>
       <entry name="/ClusteredXAConnectionFactory"/>
       <entry name="java:/ClusteredConnectionFactory"/>
       <entry name="java:/ClusteredXAConnectionFactory"/>
    </connection-factory>
+   
+   <connection-factory name="ClusteredConnectionFactoryWithDiscovery">
+      <discovery-group-ref discovery-group-name="dg-group1"/> 
+      <entry name="/ClusteredConnectionFactory"/>
+      <entry name="/ClusteredXAConnectionFactory"/>
+      <entry name="java:/ClusteredConnectionFactory"/>
+      <entry name="java:/ClusteredXAConnectionFactory"/>
+   </connection-factory>
 
    <connection-factory name="MyExampleConnectionFactory">
       <connector-ref connector-name="netty"/>

Modified: trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/client/ClientSessionFactory.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -22,10 +22,7 @@
 
 package org.jboss.messaging.core.client;
 
-import java.util.Map;
-
 import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 
 /**
  * A ClientSessionFactory
@@ -66,7 +63,7 @@
    int getProducerMaxRate();
 
    int getMinLargeMessageSize();
-   
+
    void setMinLargeMessageSize(final int minLargeMessageSize);
 
    boolean isBlockOnPersistentSend();
@@ -92,18 +89,16 @@
    boolean isPreAcknowledge();
 
    void setPreAcknowledge(boolean preAcknowledge);
-   
-   ConnectorFactory getConnectorFactory();
 
-   Map<String, Object> getTransportParams();
-
-   ConnectorFactory getBackupConnectorFactory();
-
-   Map<String, Object> getBackupTransportParams();
-
    long getPingPeriod();
 
    long getCallTimeout();
 
    int getMaxConnections();
+   
+//   TransportConfiguration getTransportConfiguration();
+//   
+//   TransportConfiguration getBackupTransportConfiguration();
+   
+   void close();
 }

Added: trunk/src/main/org/jboss/messaging/core/client/ConnectionLoadBalancingPolicy.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ConnectionLoadBalancingPolicy.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/ConnectionLoadBalancingPolicy.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,38 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client;
+
+/**
+ * A ConnectionLoadBalancingPolicy
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 28 Nov 2008 10:19:56
+ *
+ *
+ */
+public interface ConnectionLoadBalancingPolicy
+{
+   int select(int max);
+}

Added: trunk/src/main/org/jboss/messaging/core/client/ConnectionManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/ConnectionManager.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/ConnectionManager.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,61 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client;
+
+import org.jboss.messaging.core.client.impl.ClientSessionInternal;
+import org.jboss.messaging.core.exception.MessagingException;
+
+/**
+ * A ConnectionManager
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 27 Nov 2008 18:45:46
+ *
+ *
+ */
+public interface ConnectionManager
+{
+   ClientSession createSession(final String username,
+                               final String password,
+                               final boolean xa,
+                               final boolean autoCommitSends,
+                               final boolean autoCommitAcks,
+                               final boolean preAcknowledge,
+                               final int ackBatchSize,
+                               final int minLargeMessageSize,
+                               final boolean blockOnAcknowledge,
+                               final boolean autoGroup,
+                               final int sendWindowSize,
+                               final int consumerWindowSize,
+                               final int consumerMaxRate,
+                               final int producerMaxRate,
+                               final boolean blockOnNonPersistentSend,
+                               final boolean blockOnPersistentSend) throws MessagingException;
+
+   void removeSession(final ClientSessionInternal session);
+
+   int numConnections();
+
+   int numSessions();
+}

Deleted: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1,790 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors 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.messaging.core.client.impl;
-
-import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EARLY_RESPONSE;
-
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.locks.Lock;
-
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.Channel;
-import org.jboss.messaging.core.remoting.ChannelHandler;
-import org.jboss.messaging.core.remoting.ConnectionManager;
-import org.jboss.messaging.core.remoting.FailureListener;
-import org.jboss.messaging.core.remoting.Packet;
-import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
-import org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory;
-import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionMessage;
-import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-import org.jboss.messaging.core.version.Version;
-import org.jboss.messaging.util.UUIDGenerator;
-import org.jboss.messaging.util.VersionLoader;
-
-/**
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * @author <a href="mailto:clebert.suconic at jboss.org">Clebert Suconic</a>
- * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
- * @author <a href="mailto:ataylor at redhat.com">Andy Taylor</a>
- * @version <tt>$Revision: 3602 $</tt>
- * 
- * Note! There should never be more than one clientsessionfactory with the same connection params
- * Otherwise failover won't work properly since channel ids won't match on live and backup
- */
-public class ClientSessionFactoryImpl implements ClientSessionFactoryInternal, FailureListener
-{
-   // Constants
-   // ------------------------------------------------------------------------------------
-
-   private static final long serialVersionUID = 2512460695662741413L;
-
-   private static final Logger log = Logger.getLogger(ClientSessionFactoryImpl.class);
-
-   public static final long DEFAULT_PING_PERIOD = 5000;
-
-   // Any message beyond this size is considered a big message (to be chunked)
-   public static final int DEFAULT_BIG_MESSAGE_SIZE = 100 * 1024;
-
-   public static final int DEFAULT_CONSUMER_WINDOW_SIZE = 1024 * 1024;
-
-   public static final int DEFAULT_CONSUMER_MAX_RATE = -1;
-
-   public static final int DEFAULT_SEND_WINDOW_SIZE = 1024 * 1024;
-
-   public static final int DEFAULT_PRODUCER_MAX_RATE = -1;
-
-   public static final boolean DEFAULT_BLOCK_ON_ACKNOWLEDGE = false;
-
-   public static final boolean DEFAULT_BLOCK_ON_PERSISTENT_SEND = false;
-
-   public static final boolean DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND = false;
-
-   public static final boolean DEFAULT_AUTO_GROUP = false;
-   
-   public static final long DEFAULT_CALL_TIMEOUT = 30000;
-      
-   public static final int DEFAULT_MAX_CONNECTIONS = 8;
-   
-   public static final int DEFAULT_ACK_BATCH_SIZE = 1024 * 1024;
-
-   public static final boolean DEFAULT_PRE_ACKNOWLEDGE = false;
-
-   // Attributes
-   // -----------------------------------------------------------------------------------
-
-   // These attributes are mutable and can be updated by different threads so
-   // must be volatile
-
-   private final ConnectorFactory connectorFactory;
-
-   private final Map<String, Object> transportParams;
-
-   private final ConnectorFactory backupConnectorFactory;
-
-   private final Map<String, Object> backupTransportParams;
-
-   private final long pingPeriod;
-
-   private final long callTimeout;
-
-   private final int maxConnections;
-
-   private volatile ConnectionManager connectionManager;
-
-   private volatile ConnectionManager backupConnectionManager;
-   
-   private volatile int minLargeMessageSize;
-
-   private volatile int consumerWindowSize;
-
-   private volatile int consumerMaxRate;
-
-   private volatile int sendWindowSize;
-
-   private volatile int producerMaxRate;
-
-   private volatile boolean blockOnAcknowledge;
-
-   private volatile boolean blockOnPersistentSend;
-
-   private volatile boolean blockOnNonPersistentSend;
-
-   private volatile boolean autoGroup;
-
-   private boolean preAcknowledge;
-   
-   private volatile int ackBatchSize;
-
-   private final Set<ClientSessionInternal> sessions = new HashSet<ClientSessionInternal>();
-   
-   private final Object exitLock = new Object();
-   
-   private final Object createSessionLock = new Object();
-   
-   private boolean inCreateSession;
-   
-   private final Object failoverLock = new Object();
-   
-
-   // Static
-   // ---------------------------------------------------------------------------------------
-
-   // Constructors
-   // ---------------------------------------------------------------------------------
-
-   /**
-    * Create a ClientSessionFactoryImpl specifying all attributes
-    */
-   public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig,
-                                   final TransportConfiguration backupConfig,
-                                   final long pingPeriod,                                 
-                                   final long callTimeout,
-                                   final int consumerWindowSize,
-                                   final int consumerMaxRate,
-                                   final int sendWindowSize,
-                                   final int producerMaxRate,
-                                   final int minLargeMessageSize,
-                                   final boolean blockOnAcknowledge,
-                                   final boolean blockOnNonPersistentSend,
-                                   final boolean blockOnPersistentSend,
-                                   final boolean autoGroup,
-                                   final int maxConnections,
-                                   final boolean preAcknowledge,
-                                   final int ackBatchSize)
-   {
-      connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
-
-      transportParams = connectorConfig.getParams();
-
-      connectionManager = new ConnectionManagerImpl(connectorFactory,
-                                                    transportParams,
-                                                    pingPeriod,
-                                                    callTimeout,
-                                                    maxConnections);
-      if (backupConfig != null)
-      {
-         backupConnectorFactory = instantiateConnectorFactory(backupConfig.getFactoryClassName());
-
-         backupTransportParams = backupConfig.getParams();
-
-         backupConnectionManager = new ConnectionManagerImpl(backupConnectorFactory,
-                                                             backupTransportParams,
-                                                             pingPeriod,
-                                                             callTimeout,
-                                                             maxConnections);
-      }
-      else
-      {
-         backupConnectorFactory = null;
-
-         backupTransportParams = null;
-
-         backupConnectionManager = null;
-      }
-      this.pingPeriod = pingPeriod;
-      this.callTimeout = callTimeout;
-      this.consumerWindowSize = consumerWindowSize;
-      this.consumerMaxRate = consumerMaxRate;
-      this.sendWindowSize = sendWindowSize;
-      this.producerMaxRate = producerMaxRate;
-      this.blockOnAcknowledge = blockOnAcknowledge;
-      this.blockOnNonPersistentSend = blockOnNonPersistentSend;
-      this.blockOnPersistentSend = blockOnPersistentSend;
-      this.minLargeMessageSize = minLargeMessageSize;
-      this.autoGroup = autoGroup;
-      this.maxConnections = maxConnections;
-      this.ackBatchSize = ackBatchSize;
-      this.preAcknowledge = preAcknowledge;
-   }
-
-   public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig,
-                                   final TransportConfiguration backupConfig)
-   {
-      this(connectorConfig,
-           backupConfig,
-           DEFAULT_PING_PERIOD,
-           DEFAULT_CALL_TIMEOUT,
-           DEFAULT_CONSUMER_WINDOW_SIZE,
-           DEFAULT_CONSUMER_MAX_RATE,
-           DEFAULT_SEND_WINDOW_SIZE,
-           DEFAULT_PRODUCER_MAX_RATE,
-           DEFAULT_BIG_MESSAGE_SIZE,
-           DEFAULT_BLOCK_ON_ACKNOWLEDGE,
-           DEFAULT_BLOCK_ON_PERSISTENT_SEND,
-           DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
-           DEFAULT_AUTO_GROUP,
-           DEFAULT_MAX_CONNECTIONS,
-           DEFAULT_PRE_ACKNOWLEDGE,
-           DEFAULT_ACK_BATCH_SIZE);
-   }
-
-   /**
-    * Create a ClientSessionFactoryImpl specify transport type and using defaults
-    */
-   public ClientSessionFactoryImpl(final TransportConfiguration connectorConfig)
-   {
-      this(connectorConfig, null);
-   }
-
-   // ClientSessionFactory implementation
-   // ---------------------------------------------
-
-   public ClientSession createSession(final String username,
-                                      final String password,
-                                      final boolean xa,
-                                      final boolean autoCommitSends,
-                                      final boolean autoCommitAcks,
-                                      final boolean preAcknowledge,
-                                      final int ackBatchSize) throws MessagingException
-   {
-      return createSessionInternal(username, password, xa, autoCommitSends, autoCommitAcks, preAcknowledge, ackBatchSize);
-   }
-
-   public ClientSession createSession(final boolean xa,
-                                      final boolean autoCommitSends,
-                                      final boolean autoCommitAcks) throws MessagingException
-   {
-      return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, preAcknowledge, ackBatchSize);
-   }
-
-   public ClientSession createSession(final boolean xa,
-                                      final boolean autoCommitSends,
-                                      final boolean autoCommitAcks,
-                                      final boolean preAcknowledge) throws MessagingException
-   {
-      return createSessionInternal(null, null, xa, autoCommitSends, autoCommitAcks, preAcknowledge, ackBatchSize);
-   }
-
-   public int getConsumerWindowSize()
-   {
-      return consumerWindowSize;
-   }
-
-   public void setConsumerWindowSize(final int size)
-   {
-      consumerWindowSize = size;
-   }
-
-   public int getSendWindowSize()
-   {
-      return sendWindowSize;
-   }
-
-   public void setSendWindowSize(final int size)
-   {
-      sendWindowSize = size;
-   }
-
-   public int getProducerMaxRate()
-   {
-      return producerMaxRate;
-   }
-
-   public void setProducerMaxRate(final int rate)
-   {
-      producerMaxRate = rate;
-   }
-
-   public int getConsumerMaxRate()
-   {
-      return consumerMaxRate;
-   }
-
-   public void setConsumerMaxRate(final int rate)
-   {
-      consumerMaxRate = rate;
-   }
-
-   public boolean isBlockOnPersistentSend()
-   {
-      return blockOnPersistentSend;
-   }
-
-   public void setBlockOnPersistentSend(final boolean blocking)
-   {
-      blockOnPersistentSend = blocking;
-   }
-
-   public boolean isBlockOnNonPersistentSend()
-   {
-      return blockOnNonPersistentSend;
-   }
-
-   public void setBlockOnNonPersistentSend(final boolean blocking)
-   {
-      blockOnNonPersistentSend = blocking;
-   }
-
-   public boolean isBlockOnAcknowledge()
-   {
-      return blockOnAcknowledge;
-   }
-
-   public void setBlockOnAcknowledge(final boolean blocking)
-   {
-      blockOnAcknowledge = blocking;
-   }
-
-   public boolean isAutoGroup()
-   {
-      return autoGroup;
-   }
-
-   public void setAutoGroup(boolean autoGroup)
-   {
-      this.autoGroup = autoGroup;
-   }
-   
-   public int getAckBatchSize()
-   {
-      return ackBatchSize;
-   }
-   
-   public void setAckBatchSize(int ackBatchSize)
-   {
-      this.ackBatchSize = ackBatchSize;
-   }
-
-   public boolean isPreAcknowledge()
-   {
-      return preAcknowledge;
-   }
-
-   public void setPreAcknowledge(boolean preAcknowledge)
-   {
-      this.preAcknowledge = preAcknowledge;
-   }
-
-   public ConnectorFactory getConnectorFactory()
-   {
-      return connectorFactory;
-   }
-
-   public Map<String, Object> getTransportParams()
-   {
-      return transportParams;
-   }
-
-   public ConnectorFactory getBackupConnectorFactory()
-   {
-      return backupConnectorFactory;
-   }
-
-   public Map<String, Object> getBackupTransportParams()
-   {
-      return backupTransportParams;
-   }
-
-   public long getPingPeriod()
-   {
-      return pingPeriod;
-   }
-
-   public long getCallTimeout()
-   {
-      return callTimeout;
-   }
-
-   public int getMaxConnections()
-   {
-      return maxConnections;
-   }
-
-   /**
-    * @return the minLargeMessageSize
-    */
-   public int getMinLargeMessageSize()
-   {
-      return minLargeMessageSize;
-   }
-
-   /**
-    * @param minLargeMessageSize the minLargeMessageSize to set
-    */
-   public void setMinLargeMessageSize(int minLargeMessageSize)
-   {
-      this.minLargeMessageSize = minLargeMessageSize;
-   }
-
-   // ClientSessionFactoryInternal implementation
-   // ------------------------------------------
-
-   // Must be synchronized to prevent it happening concurrently with failover which can lead to
-   // inconsistencies
-   public void removeSession(final ClientSessionInternal session)
-   {
-      //TODO - can we simplify this locking?
-      synchronized (createSessionLock)
-      {
-         synchronized (failoverLock)
-         {
-            if (!sessions.remove(session))
-            {
-               throw new IllegalStateException("Cannot find session to remove " + session);
-            }
-      
-            connectionManager.returnConnection(session.getConnection().getID());
-      
-            if (backupConnectionManager != null)
-            {
-               backupConnectionManager.returnConnection(session.getBackupConnection().getID());
-            }
-         }
-      }
-   }
-
-   public int numConnections()
-   {
-      return connectionManager.numConnections();
-   }
-
-   public int numBackupConnections()
-   {
-      return backupConnectionManager != null ? backupConnectionManager.numConnections() : 0;
-   }
-
-   public int numSessions()
-   {
-      return sessions.size();
-   }
-
-   // FailureListener implementation --------------------------------------------------------
-
-   public void connectionFailed(final MessagingException me)
-   {      
-      if (me.getCode() == MessagingException.OBJECT_CLOSED)
-      {
-         //The server has closed the connection. We don't want failover to occur in this case - 
-         //either the server has booted off the connection, or it didn't receive a ping in time
-         //in either case server side resources on both live and backup will be removed so the client
-         //can't failover anyway
-         return;
-      }
-      
-      synchronized (failoverLock)
-      {         
-         //Now get locks on all channel 1s, whilst holding the failoverLock - this makes sure
-         //There are either no threads executing in createSession, or one is blocking on a createSession
-         //result.
-         
-         //Then interrupt the channel 1 that is blocking (could just interrupt them all)
-         
-         //Then release all channel 1 locks - this allows the createSession to exit the monitor
-         
-         //Then get all channel 1 locks again - this ensures the any createSession thread has executed the section and
-         //returned all its connections to the connection manager (the code to return connections to connection manager
-         //must be inside the lock
-         
-         //Then perform failover
-         
-         //Then release failoverLock
-         
-         //The other side of the bargain - during createSession:
-         //The calling thread must get the failoverLock and get its' connections when this is locked.
-         //While this is still locked it must then get the channel1 lock
-         //It can then release the failoverLock
-         //It should catch MessagingException.INTERRUPTED in the call to channel.sendBlocking
-         //It should then return its connections, with channel 1 lock still held
-         //It can then release the channel 1 lock, and retry (which will cause locking on failoverLock
-         //until failover is complete
-         
-         if (backupConnectionManager != null)
-         {
-            log.info("Commencing automatic failover");
-            lockAllChannel1s();
-            
-            final boolean needToInterrupt;
-            
-            synchronized (exitLock)
-            {
-               needToInterrupt = inCreateSession;
-            }
-            
-            unlockAllChannel1s();
-                 
-            if (needToInterrupt)
-            {           
-               //Forcing return all channels won't guarantee that any blocked thread will return immediately
-               //So we need to wait for it
-               forceReturnAllChannel1s();
-               
-               //Now we need to make sure that the thread has actually exited and returned it's connections
-               //before failover occurs
-               
-               synchronized (exitLock)
-               {
-                  while (inCreateSession)
-                  {
-                     try
-                     {
-                        exitLock.wait(5000);
-                     }
-                     catch (InterruptedException e)
-                     {                        
-                     }
-                  }
-               }
-            }
-            
-            //Now we absolutely know that no threads are executing in or blocked in createSession, and no
-            //more will execute it until failover is complete
-            
-            //So.. do failover
-            
-            connectionManager = backupConnectionManager;
-   
-            backupConnectionManager = null;
-            
-            for (ClientSessionInternal session : sessions)
-            {
-               session.handleFailover();
-            }
-            
-            log.info("Failover complete");
-         }                    
-      }      
-   }
-   
-   // Public
-   // ---------------------------------------------------------------------------------------
-
-   // Protected
-   // ------------------------------------------------------------------------------------
-
-   // Package Private
-   // ------------------------------------------------------------------------------
-
-   // Private
-   // --------------------------------------------------------------------------------------
-
-   
-   //The whole method must be synchonrized to prevent more than one thread executing concurrently
-   private ClientSession createSessionInternal(final String username,
-                                               final String password,
-                                               final boolean xa,
-                                               final boolean autoCommitSends,
-                                               final boolean autoCommitAcks,
-                                               final boolean preAcknowledge,
-                                               final int ackBatchSize) throws MessagingException
-   {
-      synchronized (createSessionLock)
-      {
-         String name = UUIDGenerator.getInstance().generateSimpleStringUUID().toString();
-         boolean retry = false;
-         do
-         {         
-            Version clientVersion = VersionLoader.getVersion();
-      
-            RemotingConnection connection = null;
-      
-            RemotingConnection backupConnection = null;
-            
-            Lock lock = null;
-      
-            try
-            {    
-               Channel channel1;
-               
-               synchronized (failoverLock)
-               {               
-                  connection = connectionManager.getConnection();
-      
-                  if (backupConnectionManager != null)
-                  {
-                     backupConnection = backupConnectionManager.getConnection();
-                  }
-                  
-                  channel1 = connection.getChannel(1, -1, false);
-                  
-                  //Lock it - this must be done while the failoverLock is held
-                  channel1.getLock().lock();
-                  
-                  lock = channel1.getLock();
-               } //We can now release the failoverLock
-               
-               //We now set a flag saying createSession is executing
-               synchronized (exitLock)
-               {
-                  inCreateSession = true;
-               }
-                                    
-               long sessionChannelID = connection.generateChannelID();
-      
-               Packet request = new CreateSessionMessage(name,
-                                                         sessionChannelID,
-                                                         clientVersion.getIncrementingVersion(),
-                                                         username,
-                                                         password,
-                                                         minLargeMessageSize,
-                                                         xa,
-                                                         autoCommitSends,
-                                                         autoCommitAcks,
-                                                         preAcknowledge,
-                                                         sendWindowSize);
-      
-               Packet pResponse = channel1.sendBlocking(request);
-               
-               if (pResponse.getType() == EARLY_RESPONSE)
-               {
-                  //This means the thread was blocked on create session and failover unblocked it
-                  //so failover could occur
-                  
-                  //So we just need to return our connections and flag for retry
-                  
-                  connectionManager.returnConnection(connection.getID());               
-         
-                  backupConnectionManager.returnConnection(backupConnection.getID());
-                  
-                  retry = true;                             
-               }
-               else
-               {         
-                  CreateSessionResponseMessage response = (CreateSessionResponseMessage)pResponse;
-         
-                  Channel sessionChannel = connection.getChannel(sessionChannelID,
-                                                                 sendWindowSize,
-                                                                 sendWindowSize != -1);
-         
-                  ClientSessionInternal session = new ClientSessionImpl(this,
-                                                                        name,
-                                                                        xa,                                                                      
-                                                                        autoCommitSends,
-                                                                        autoCommitAcks,
-                                                                        preAcknowledge,
-                                                                        blockOnAcknowledge,
-                                                                        autoGroup,
-                                                                        ackBatchSize,
-                                                                        connection,
-                                                                        backupConnection,                                                                       
-                                                                        response.getServerVersion(),
-                                                                        sessionChannel);
-                           
-                  sessions.add(session);
-
-                  ChannelHandler handler = new ClientSessionPacketHandler(session, sessionChannel);
-         
-                  sessionChannel.setHandler(handler);
-         
-                  connection.addFailureListener(this);
-         
-                  return session;
-               }
-            }
-            catch (Throwable t)
-            {
-               if (connection != null)
-               {
-                  connectionManager.returnConnection(connection.getID());
-               }
-      
-               if (backupConnection != null)
-               {
-                  backupConnectionManager.returnConnection(backupConnection.getID());
-               }
-      
-               if (t instanceof MessagingException)
-               {
-                  throw (MessagingException)t;
-               }
-               else
-               {
-                  MessagingException me = new MessagingException(MessagingException.INTERNAL_ERROR,
-                                                                 "Failed to create session");
-      
-                  me.initCause(t);
-      
-                  throw me;
-               }
-            } 
-            finally
-            {
-               if (lock != null)
-               {
-                  lock.unlock();
-               }
-               
-               //Execution has finished so notify any failover thread that may be waiting for us to be done
-               synchronized (exitLock)
-               {
-                  inCreateSession = false;
-                  
-                  exitLock.notify();
-               }                     
-            }
-         }
-         while (retry);
-      }
-      
-      //Should never get here
-      throw new IllegalStateException("How did you get here??");
-   }
-
-   private ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName)
-   {
-      ClassLoader loader = Thread.currentThread().getContextClassLoader();
-      try
-      {
-         Class<?> clazz = loader.loadClass(connectorFactoryClassName);
-         return (ConnectorFactory)clazz.newInstance();
-      }
-      catch (Exception e)
-      {
-         throw new IllegalArgumentException("Error instantiating connector factory \"" + connectorFactoryClassName +
-                                            "\"", e);
-      }
-   }
-   
-   private void lockAllChannel1s()
-   {
-      Set<RemotingConnection> conns = connectionManager.getConnections();
-      
-      for (RemotingConnection conn: conns)
-      {
-         Channel channel1 = conn.getChannel(1, -1, false);
-         
-         channel1.getLock().lock();
-      }
-   }
-   
-   private void unlockAllChannel1s()
-   {
-      Set<RemotingConnection> conns = connectionManager.getConnections();
-      
-      for (RemotingConnection conn: conns)
-      {
-         Channel channel1 = conn.getChannel(1, -1, false);
-         
-         channel1.getLock().unlock();
-      }
-   }
-   
-   private void forceReturnAllChannel1s()
-   {
-      Set<RemotingConnection> conns = connectionManager.getConnections();
-      
-      for (RemotingConnection conn: conns)
-      {
-         Channel channel1 = conn.getChannel(1, -1, false);
-         
-         channel1.returnBlocking();
-      }
-   }
-   
-
-}

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionFactoryInternal.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -30,14 +30,10 @@
  *
  */
 public interface ClientSessionFactoryInternal extends ClientSessionFactory
-{
-   void removeSession(ClientSessionInternal session);
-   
+{ 
    //for testing
    
    int numConnections();
    
-   int numBackupConnections();
-   
    int numSessions();
 }

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -35,9 +35,10 @@
 import javax.transaction.xa.Xid;
 
 import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientFileMessage;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
-import org.jboss.messaging.core.client.ClientFileMessage;
+import org.jboss.messaging.core.client.ConnectionManager;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.Channel;
@@ -115,7 +116,7 @@
 
    // Attributes ----------------------------------------------------------------------------
 
-   private final ClientSessionFactoryInternal sessionFactory;
+   private final ConnectionManager connectionManager;
 
    private final String name;
 
@@ -125,8 +126,6 @@
 
    private volatile RemotingConnection remotingConnection;
 
-   private volatile RemotingConnection backupConnection;
-
    private final Set<ClientProducerInternal> producers = new ConcurrentHashSet<ClientProducerInternal>();
 
    private final Map<Long, ClientConsumerInternal> consumers = new ConcurrentHashMap<Long, ClientConsumerInternal>();
@@ -144,6 +143,18 @@
    private final boolean autoGroup;
 
    private final int ackBatchSize;
+   
+   private final int consumerWindowSize;
+   
+   private final int consumerMaxRate;
+   
+   private final int producerMaxRate;
+   
+   private final boolean blockOnNonPersistentSend;
+   
+   private final boolean blockOnPersistentSend;
+   
+   private final int minLargeMessageSize;
 
    private final Channel channel;
 
@@ -158,7 +169,7 @@
 
    // Constructors ----------------------------------------------------------------------------
 
-   public ClientSessionImpl(final ClientSessionFactoryInternal sessionFactory,
+   public ClientSessionImpl(final ConnectionManager connectionManager,
                             final String name,
                             final boolean xa,
                             final boolean autoCommitSends,
@@ -167,19 +178,22 @@
                             final boolean blockOnAcknowledge,
                             final boolean autoGroup,
                             final int ackBatchSize,
+                            final int consumerWindowSize,                            
+                            final int consumerMaxRate,                            
+                            final int producerMaxRate,                            
+                            final boolean blockOnNonPersistentSend,                            
+                            final boolean blockOnPersistentSend,                            
+                            final int minLargeMessageSize,
                             final RemotingConnection remotingConnection,
-                            final RemotingConnection backupConnection,
                             final int version,
                             final Channel channel) throws MessagingException
    {
-      this.sessionFactory = sessionFactory;
+      this.connectionManager = connectionManager;
 
       this.name = name;
 
       this.remotingConnection = remotingConnection;
 
-      this.backupConnection = backupConnection;
-
       executor = executorFactory.getExecutor();
 
       this.xa = xa;
@@ -199,6 +213,18 @@
       this.version = version;
 
       this.ackBatchSize = ackBatchSize;
+      
+      this.consumerWindowSize = consumerWindowSize;
+      
+      this.consumerMaxRate = consumerMaxRate;
+      
+      this.producerMaxRate = producerMaxRate;
+      
+      this.blockOnNonPersistentSend = blockOnNonPersistentSend;
+      
+      this.blockOnPersistentSend = blockOnPersistentSend;
+      
+      this.minLargeMessageSize = minLargeMessageSize;
    }
 
    // ClientSession implementation
@@ -283,8 +309,8 @@
 
       return createConsumer(queueName,
                             filterString,
-                            sessionFactory.getConsumerWindowSize(),
-                            sessionFactory.getConsumerMaxRate(),
+                            consumerWindowSize,
+                            consumerMaxRate,
                             false);
    }
 
@@ -294,8 +320,8 @@
    {
       return createConsumer(queueName,
                             filterString,
-                            sessionFactory.getConsumerWindowSize(),
-                            sessionFactory.getConsumerMaxRate(),
+                            consumerWindowSize,
+                            consumerMaxRate,
                             browseOnly);
    }
 
@@ -332,8 +358,8 @@
       return createFileConsumer(directory,
                                 queueName,
                                 filterString,
-                                sessionFactory.getConsumerWindowSize(),
-                                sessionFactory.getConsumerMaxRate(),
+                                consumerWindowSize,
+                                consumerMaxRate,
                                 false);
    }
 
@@ -345,8 +371,8 @@
       return createFileConsumer(directory,
                                 queueName,
                                 filterString,
-                                sessionFactory.getConsumerWindowSize(),
-                                sessionFactory.getConsumerMaxRate(),
+                                consumerWindowSize,
+                                consumerMaxRate,
                                 browseOnly);
    }
 
@@ -372,15 +398,15 @@
    {
       checkClosed();
 
-      return createProducer(address, sessionFactory.getProducerMaxRate());
+      return createProducer(address, producerMaxRate);
    }
 
    public ClientProducer createProducer(final SimpleString address, final int maxRate) throws MessagingException
    {
       return createProducer(address,
                             maxRate,
-                            sessionFactory.isBlockOnNonPersistentSend(),
-                            sessionFactory.isBlockOnPersistentSend());
+                            blockOnNonPersistentSend,
+                            blockOnPersistentSend);
    }
 
    public ClientProducer createProducer(final SimpleString address,
@@ -397,7 +423,7 @@
                                                                autoCommitSends && blockOnNonPersistentSend,
                                                                autoCommitSends && blockOnPersistentSend,
                                                                autoGroup,
-                                                               sessionFactory.getMinLargeMessageSize(),
+                                                               minLargeMessageSize,
                                                                channel);
 
       addProducer(producer);
@@ -630,6 +656,8 @@
       {
          return;
       }
+      
+     // log.info("closing client session " + System.identityHashCode(this));
 
       try
       {
@@ -658,7 +686,7 @@
    }
 
    // Needs to be synchronized to prevent issues with occurring concurrently with close()
-   public synchronized void handleFailover()
+   public synchronized void handleFailover(final RemotingConnection backupConnection)
    {
       if (closed)
       {
@@ -694,7 +722,7 @@
             channel.returnBlocking();
          }
 
-         backupConnection = null;
+         //backupConnection = null;
       }
       catch (Throwable t)
       {
@@ -1006,16 +1034,16 @@
       return remotingConnection;
    }
 
-   public RemotingConnection getBackupConnection()
-   {
-      return backupConnection;
-   }
+//   public RemotingConnection getBackupConnection()
+//   {
+//      return backupConnection;
+//   }
+//
+//   public void setBackupConnection(RemotingConnection connection)
+//   {
+//      this.backupConnection = connection;
+//   }
 
-   public void setBackupConnection(RemotingConnection connection)
-   {
-      this.backupConnection = connection;
-   }
-
    // Protected
    // ----------------------------------------------------------------------------
 
@@ -1120,7 +1148,7 @@
          channel.close();
       }
 
-      sessionFactory.removeSession(this);
+      connectionManager.removeSession(this);
    }
 
    private void cleanUpChildren() throws Exception

Modified: trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ClientSessionInternal.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -43,11 +43,11 @@
    
    void handleReceiveChunk(long consumerID, SessionSendChunkMessage chunk) throws Exception;
 
-   void handleFailover();
+   void handleFailover(RemotingConnection backupConnection);
    
    RemotingConnection getConnection();
    
-   RemotingConnection getBackupConnection();
+//   RemotingConnection getBackupConnection();
    
-   void setBackupConnection(RemotingConnection connection);
+ //  void setBackupConnection(RemotingConnection connection);
 }

Added: trunk/src/main/org/jboss/messaging/core/client/impl/ConnectionManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/ConnectionManagerImpl.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/ConnectionManagerImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,712 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client.impl;
+
+import static org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl.EARLY_RESPONSE;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.locks.Lock;
+
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ConnectionManager;
+import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
+import org.jboss.messaging.core.remoting.Channel;
+import org.jboss.messaging.core.remoting.ChannelHandler;
+import org.jboss.messaging.core.remoting.FailureListener;
+import org.jboss.messaging.core.remoting.Packet;
+import org.jboss.messaging.core.remoting.RemotingConnection;
+import org.jboss.messaging.core.remoting.impl.AbstractBufferHandler;
+import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
+import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionMessage;
+import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
+import org.jboss.messaging.core.remoting.spi.Connection;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
+import org.jboss.messaging.core.remoting.spi.Connector;
+import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
+import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
+import org.jboss.messaging.core.version.Version;
+import org.jboss.messaging.util.JBMThreadFactory;
+import org.jboss.messaging.util.UUIDGenerator;
+import org.jboss.messaging.util.VersionLoader;
+
+/**
+ * A ConnectionManagerImpl
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 27 Nov 2008 18:46:06
+ *
+ *
+ */
+public class ConnectionManagerImpl implements ConnectionManager, FailureListener, ConnectionLifeCycleListener
+{
+   // Constants
+   // ------------------------------------------------------------------------------------
+
+   private static final long serialVersionUID = 2512460695662741413L;
+
+   private static final Logger log = Logger.getLogger(ClientSessionFactoryImpl.class);
+
+   // Attributes
+   // -----------------------------------------------------------------------------------
+
+   private ConnectorFactory connectorFactory;
+
+   private Map<String, Object> transportParams;
+
+   private ConnectorFactory backupConnectorFactory;
+
+   private Map<String, Object> backupTransportParams;
+
+   private final int maxConnections;
+   
+   private final long callTimeout;
+   
+   private final long pingPeriod;
+
+   private final Map<ClientSessionInternal, RemotingConnection> sessions = new HashMap<ClientSessionInternal, RemotingConnection>();
+
+   private final Object exitLock = new Object();
+
+   private final Object createSessionLock = new Object();
+
+   private boolean inCreateSession;
+
+   private final Object failoverLock = new Object();
+
+   // TODO - allow this to be configurable
+   private static final ScheduledThreadPoolExecutor pingExecutor = new ScheduledThreadPoolExecutor(5,
+                                                                                                   new JBMThreadFactory("jbm-pinger-threads"));
+
+   private final Map<Object, ConnectionEntry> connections = new LinkedHashMap<Object, ConnectionEntry>();
+
+   private int refCount;
+
+   private Iterator<ConnectionEntry> mapIterator;
+
+   private Object failConnectionLock = new Object();
+
+   // Static
+   // ---------------------------------------------------------------------------------------
+
+   // Constructors
+   // ---------------------------------------------------------------------------------
+
+   public ConnectionManagerImpl(final TransportConfiguration connectorConfig,
+                                final TransportConfiguration backupConfig,
+                                final int maxConnections,
+                                final long callTimeout,
+                                final long pingPeriod)
+   {
+      connectorFactory = instantiateConnectorFactory(connectorConfig.getFactoryClassName());
+
+      transportParams = connectorConfig.getParams();
+
+      if (backupConfig != null)
+      {
+         backupConnectorFactory = instantiateConnectorFactory(backupConfig.getFactoryClassName());
+
+         backupTransportParams = backupConfig.getParams();
+
+      }
+      else
+      {
+         backupConnectorFactory = null;
+
+         backupTransportParams = null;
+      }
+      this.maxConnections = maxConnections;
+      
+      this.callTimeout = callTimeout;
+      
+      this.pingPeriod = pingPeriod;
+   }
+
+   // ConnectionLifeCycleListener implementation --------------------
+
+   public void connectionCreated(final Connection connection)
+   {
+   }
+
+   public void connectionDestroyed(final Object connectionID)
+   {
+      // If conn still exists here this means that the underlying transport
+      // conn has been closed from the server side without
+      // being returned from the client side so we need to fail the conn and
+      // call it's listeners
+      if (connections.containsKey(connectionID))
+      {
+         MessagingException me = new MessagingException(MessagingException.OBJECT_CLOSED,
+                                                        "The conn has been closed by the server");
+
+         failConnection(me);
+      }
+   }
+
+   public void connectionException(final Object connectionID, final MessagingException me)
+   {
+      failConnection(me);
+   }
+   
+   // ConnectionManager implementation ------------------------------------------------------------------
+
+   public ClientSession createSession(final String username,
+                                      final String password,
+                                      final boolean xa,
+                                      final boolean autoCommitSends,
+                                      final boolean autoCommitAcks,
+                                      final boolean preAcknowledge,
+                                      final int ackBatchSize,
+                                      final int minLargeMessageSize,
+                                      final boolean blockOnAcknowledge,
+                                      final boolean autoGroup,
+                                      final int sendWindowSize,
+                                      final int consumerWindowSize,                            
+                                      final int consumerMaxRate,                            
+                                      final int producerMaxRate,                            
+                                      final boolean blockOnNonPersistentSend,                            
+                                      final boolean blockOnPersistentSend) throws MessagingException
+   {
+      synchronized (createSessionLock)
+      {
+         String name = UUIDGenerator.getInstance().generateSimpleStringUUID().toString();
+
+         boolean retry = false;
+         do
+         {
+            Version clientVersion = VersionLoader.getVersion();
+
+            RemotingConnection connection = null;
+
+            Lock lock = null;
+
+            try
+            {
+               Channel channel1;
+
+               synchronized (failoverLock)
+               {
+                  connection = getConnection(1);
+
+                  channel1 = connection.getChannel(1, -1, false);
+
+                  // Lock it - this must be done while the failoverLock is held
+                  channel1.getLock().lock();
+
+                  lock = channel1.getLock();
+               } // We can now release the failoverLock
+
+               // We now set a flag saying createSession is executing
+               synchronized (exitLock)
+               {
+                  inCreateSession = true;
+               }
+
+               long sessionChannelID = connection.generateChannelID();
+
+               Packet request = new CreateSessionMessage(name,
+                                                         sessionChannelID,
+                                                         clientVersion.getIncrementingVersion(),
+                                                         username,
+                                                         password,
+                                                         minLargeMessageSize,
+                                                         xa,
+                                                         autoCommitSends,
+                                                         autoCommitAcks,
+                                                         preAcknowledge,
+                                                         sendWindowSize);
+
+               Packet pResponse = channel1.sendBlocking(request);
+
+               if (pResponse.getType() == EARLY_RESPONSE)
+               {
+                  // This means the thread was blocked on create session and failover unblocked it
+                  // so failover could occur
+
+                  // So we just need to return our connections and flag for retry
+
+                  this.returnConnection(connection.getID());
+
+                  retry = true;
+               }
+               else
+               {
+                  CreateSessionResponseMessage response = (CreateSessionResponseMessage)pResponse;
+
+                  Channel sessionChannel = connection.getChannel(sessionChannelID, sendWindowSize, sendWindowSize != -1);
+
+                  ClientSessionInternal session = new ClientSessionImpl(this,
+                                                                        name,
+                                                                        xa,
+                                                                        autoCommitSends,
+                                                                        autoCommitAcks,
+                                                                        preAcknowledge,
+                                                                        blockOnAcknowledge,
+                                                                        autoGroup,
+                                                                        ackBatchSize,
+                                                                        consumerWindowSize,                            
+                                                                        consumerMaxRate,                            
+                                                                        producerMaxRate,                            
+                                                                        blockOnNonPersistentSend,                            
+                                                                        blockOnPersistentSend,                            
+                                                                        minLargeMessageSize,
+                                                                        connection,
+                                                                        response.getServerVersion(),
+                                                                        sessionChannel);
+
+                  sessions.put(session, connection);
+
+                  ChannelHandler handler = new ClientSessionPacketHandler(session, sessionChannel);
+
+                  sessionChannel.setHandler(handler);
+
+                  connection.addFailureListener(this);
+
+                  return session;
+               }
+            }
+            catch (Throwable t)
+            {
+               if (connection != null)
+               {
+                  returnConnection(connection.getID());
+               }
+
+               if (t instanceof MessagingException)
+               {
+                  throw (MessagingException)t;
+               }
+               else
+               {
+                  MessagingException me = new MessagingException(MessagingException.INTERNAL_ERROR,
+                                                                 "Failed to create session");
+
+                  me.initCause(t);
+
+                  throw me;
+               }
+            }
+            finally
+            {
+               if (lock != null)
+               {
+                  lock.unlock();
+               }
+
+               // Execution has finished so notify any failover thread that may be waiting for us to be done
+               synchronized (exitLock)
+               {
+                  inCreateSession = false;
+
+                  exitLock.notify();
+               }
+            }
+         }
+         while (retry);
+      }
+
+      // Should never get here
+      throw new IllegalStateException("Oh my God it's full of stars");
+   }
+
+   // Must be synchronized to prevent it happening concurrently with failover which can lead to
+   // inconsistencies
+   public void removeSession(final ClientSessionInternal session)
+   {
+      // TODO - can we simplify this locking?
+      synchronized (createSessionLock)
+      {
+         synchronized (failoverLock)
+         {
+            if (sessions.remove(session) == null)
+            {
+               throw new IllegalStateException("Cannot find session to remove " + session);
+            }
+
+            this.returnConnection(session.getConnection().getID());
+         }
+      }
+   }
+
+   public synchronized int numConnections()
+   {
+      return connections.size();
+   }
+
+   public int numSessions()
+   {
+      return sessions.size();
+   }
+
+   // FailureListener implementation --------------------------------------------------------
+
+   public void connectionFailed(final MessagingException me)
+   {
+      if (me.getCode() == MessagingException.OBJECT_CLOSED)
+      {
+         // The server has closed the connection. We don't want failover to occur in this case -
+         // either the server has booted off the connection, or it didn't receive a ping in time
+         // in either case server side resources on both live and backup will be removed so the client
+         // can't failover anyway
+         return;
+      }
+
+      synchronized (failoverLock)
+      {
+         // Now get locks on all channel 1s, whilst holding the failoverLock - this makes sure
+         // There are either no threads executing in createSession, or one is blocking on a createSession
+         // result.
+
+         // Then interrupt the channel 1 that is blocking (could just interrupt them all)
+
+         // Then release all channel 1 locks - this allows the createSession to exit the monitor
+
+         // Then get all channel 1 locks again - this ensures the any createSession thread has executed the section and
+         // returned all its connections to the connection manager (the code to return connections to connection manager
+         // must be inside the lock
+
+         // Then perform failover
+
+         // Then release failoverLock
+
+         // The other side of the bargain - during createSession:
+         // The calling thread must get the failoverLock and get its' connections when this is locked.
+         // While this is still locked it must then get the channel1 lock
+         // It can then release the failoverLock
+         // It should catch MessagingException.INTERRUPTED in the call to channel.sendBlocking
+         // It should then return its connections, with channel 1 lock still held
+         // It can then release the channel 1 lock, and retry (which will cause locking on failoverLock
+         // until failover is complete
+
+         if (this.backupConnectorFactory != null)
+         {
+            log.info("Commencing automatic failover");
+            lockAllChannel1s();
+
+            final boolean needToInterrupt;
+
+            synchronized (exitLock)
+            {
+               needToInterrupt = inCreateSession;
+            }
+
+            unlockAllChannel1s();
+
+            if (needToInterrupt)
+            {
+               // Forcing return all channels won't guarantee that any blocked thread will return immediately
+               // So we need to wait for it
+               forceReturnAllChannel1s();
+
+               // Now we need to make sure that the thread has actually exited and returned it's connections
+               // before failover occurs
+
+               synchronized (exitLock)
+               {
+                  while (inCreateSession)
+                  {
+                     try
+                     {
+                        exitLock.wait(5000);
+                     }
+                     catch (InterruptedException e)
+                     {
+                     }
+                  }
+               }
+            }
+
+            // Now we absolutely know that no threads are executing in or blocked in createSession, and no
+            // more will execute it until failover is complete
+
+            // So.. do failover
+
+            Set<RemotingConnection> oldConnections = new HashSet<RemotingConnection>();
+
+            for (ConnectionEntry entry : connections.values())
+            {
+               oldConnections.add(entry.connection);
+            }
+
+            connections.clear();
+
+            refCount = 0;
+
+            mapIterator = null;
+
+            connectorFactory = backupConnectorFactory;
+
+            transportParams = backupTransportParams;
+
+            backupConnectorFactory = null;
+
+            backupTransportParams = null;
+
+            // We fail over sessions per connection to ensure there is the same mapping of channel id
+            // on live and backup connections
+
+            Map<RemotingConnection, List<ClientSessionInternal>> sessionsPerConnection = new HashMap<RemotingConnection, List<ClientSessionInternal>>();
+
+            for (Map.Entry<ClientSessionInternal, RemotingConnection> entry : sessions.entrySet())
+            {
+               ClientSessionInternal session = entry.getKey();
+
+               RemotingConnection connection = entry.getValue();
+
+               List<ClientSessionInternal> sessions = sessionsPerConnection.get(connection);
+
+               if (sessions == null)
+               {
+                  sessions = new ArrayList<ClientSessionInternal>();
+
+                  sessionsPerConnection.put(connection, sessions);
+               }
+
+               sessions.add(session);
+            }
+
+            for (Map.Entry<RemotingConnection, List<ClientSessionInternal>> entry : sessionsPerConnection.entrySet())
+            {
+               List<ClientSessionInternal> sessions = entry.getValue();
+
+               RemotingConnection backupConnection = getConnection(sessions.size());
+
+               for (ClientSessionInternal session : sessions)
+               {
+                  session.handleFailover(backupConnection);
+
+                  this.sessions.put(session, backupConnection);
+               }
+            }
+
+            for (RemotingConnection connection : oldConnections)
+            {
+               connection.destroy();
+            }
+
+            log.info("Failover complete");
+         }
+      }
+   }
+
+   // Public
+   // ---------------------------------------------------------------------------------------
+
+   // Protected
+   // ------------------------------------------------------------------------------------
+
+   // Package Private
+   // ------------------------------------------------------------------------------
+
+   // Private
+   // --------------------------------------------------------------------------------------
+
+   private void checkCloseConnections()
+   {
+      if (refCount == 0)
+      {
+         // Close connections
+
+         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());
+
+         connections.clear();
+
+         for (ConnectionEntry entry : copy)
+         {
+            try
+            {
+               entry.connection.destroy();
+
+               entry.connector.close();
+            }
+            catch (Throwable ignore)
+            {
+            }
+         }
+      }
+   }
+
+   private RemotingConnection getConnection(int count)
+   {
+      RemotingConnection conn;
+
+      if (connections.size() < maxConnections)
+      {
+         // Create a new one
+
+         DelegatingBufferHandler handler = new DelegatingBufferHandler();
+
+         Connector connector = connectorFactory.createConnector(transportParams, handler, this);
+
+         connector.start();
+
+         Connection tc = connector.createConnection();
+
+         if (tc == null)
+         {
+            throw new IllegalStateException("Failed to connect");
+         }
+
+         conn = new RemotingConnectionImpl(tc, callTimeout, pingPeriod, pingExecutor, null);
+
+         handler.conn = conn;
+
+         conn.startPinger();
+
+         connections.put(conn.getID(), new ConnectionEntry(conn, connector));
+      }
+      else
+      {
+         // Return one round-robin from the list
+
+         if (mapIterator == null || !mapIterator.hasNext())
+         {
+            mapIterator = connections.values().iterator();
+         }
+
+         ConnectionEntry entry = mapIterator.next();
+
+         conn = entry.connection;
+      }
+
+      refCount += count;
+
+      return conn;
+   }
+
+   private void returnConnection(final Object connectionID)
+   {
+      ConnectionEntry entry = connections.get(connectionID);
+
+      if (refCount != 0)
+      {
+         refCount--;
+      }
+
+      if (entry != null)
+      {
+         checkCloseConnections();
+      }
+      else
+      {
+         // Can be legitimately null if session was closed before then went to remove session from csf
+         // and locked since failover had started then after failover removes it but it's already been failed
+      }
+   }
+
+   private void failConnection(final MessagingException me)
+   {
+      synchronized (failConnectionLock)
+      {
+         // When a single connection fails, we fail *all* the connections
+
+         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());
+
+         for (ConnectionEntry entry : copy)
+         {
+            entry.connection.fail(me);
+         }
+
+         refCount = 0;
+      }
+   }
+
+   private ConnectorFactory instantiateConnectorFactory(final String connectorFactoryClassName)
+   {
+      ClassLoader loader = Thread.currentThread().getContextClassLoader();
+      try
+      {
+         Class<?> clazz = loader.loadClass(connectorFactoryClassName);
+         return (ConnectorFactory)clazz.newInstance();
+      }
+      catch (Exception e)
+      {
+         throw new IllegalArgumentException("Error instantiating connector factory \"" + connectorFactoryClassName +
+                                            "\"", e);
+      }
+   }
+
+   private void lockAllChannel1s()
+   {
+      for (ConnectionEntry entry : connections.values())
+      {
+         Channel channel1 = entry.connection.getChannel(1, -1, false);
+
+         channel1.getLock().lock();
+      }
+   }
+
+   private void unlockAllChannel1s()
+   {
+      for (ConnectionEntry entry : connections.values())
+      {
+         Channel channel1 = entry.connection.getChannel(1, -1, false);
+
+         channel1.getLock().unlock();
+      }
+   }
+
+   private void forceReturnAllChannel1s()
+   {
+      for (ConnectionEntry entry : connections.values())
+      {
+         Channel channel1 = entry.connection.getChannel(1, -1, false);
+
+         channel1.returnBlocking();
+      }
+   }
+
+   private class ConnectionEntry
+   {
+      ConnectionEntry(final RemotingConnection connection, final Connector connector)
+      {
+         this.connection = connection;
+
+         this.connector = connector;
+      }
+
+      final RemotingConnection connection;
+
+      final Connector connector;
+   }
+
+   private class DelegatingBufferHandler extends AbstractBufferHandler
+   {
+      RemotingConnection conn;
+
+      public void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
+      {
+         conn.bufferReceived(connectionID, buffer);
+      }
+   }
+}

Added: trunk/src/main/org/jboss/messaging/core/client/impl/FirstElementConnectionLoadBalancingPolicy.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/FirstElementConnectionLoadBalancingPolicy.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/FirstElementConnectionLoadBalancingPolicy.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,43 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client.impl;
+
+import org.jboss.messaging.core.client.ConnectionLoadBalancingPolicy;
+
+/**
+ * A FirstElementConnectionLoadBalancingPolicy
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 28 Nov 2008 10:56:59
+ *
+ *
+ */
+public class FirstElementConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy
+{
+   public int select(final int max)
+   {
+      return 0;
+   }
+}

Added: trunk/src/main/org/jboss/messaging/core/client/impl/RandomConnectionLoadBalancingPolicy.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/RandomConnectionLoadBalancingPolicy.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/RandomConnectionLoadBalancingPolicy.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,46 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client.impl;
+
+import org.jboss.messaging.core.client.ConnectionLoadBalancingPolicy;
+import org.jboss.messaging.util.Random;
+
+/**
+ * A RandomConnectionLoadBalancingPolicy
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 28 Nov 2008 10:24:11
+ *
+ *
+ */
+public class RandomConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy
+{
+   private Random random = new Random();
+   
+   public int select(final int max)
+   {
+      return random.getRandom().nextInt(max);
+   }
+}

Added: trunk/src/main/org/jboss/messaging/core/client/impl/RoundRobinConnectionLoadBalancingPolicy.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/client/impl/RoundRobinConnectionLoadBalancingPolicy.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/core/client/impl/RoundRobinConnectionLoadBalancingPolicy.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,67 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.core.client.impl;
+
+import org.jboss.messaging.core.client.ConnectionLoadBalancingPolicy;
+import org.jboss.messaging.util.Random;
+
+/**
+ * A RoundRobinConnectionLoadBalancingPolicy
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 28 Nov 2008 10:21:08
+ *
+ *
+ */
+public class RoundRobinConnectionLoadBalancingPolicy implements ConnectionLoadBalancingPolicy
+{
+   private Random random = new Random();
+   
+   private boolean first = true;
+   
+   private int pos;
+
+   public int select(final int max)
+   {
+      if (first)
+      {
+         //We start on a random one
+         pos = random.getRandom().nextInt(max);
+         
+         first = false;
+      }
+      else
+      {
+         pos++;
+         
+         if (pos >= max)
+         {
+            pos = 0;
+         }
+      }
+     
+      return pos;
+   }  
+}

Modified: trunk/src/main/org/jboss/messaging/core/config/Configuration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/Configuration.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/config/Configuration.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -100,9 +100,9 @@
    
    void setBroadcastGroupConfigurations(Set<BroadcastGroupConfiguration> configs);
    
-   Set<DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations();
+   Map<String, DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations();
    
-   void setDiscoveryGroupConfigurations(Set<DiscoveryGroupConfiguration> configs);
+   void setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> configs);
    
    Set<MessageFlowConfiguration> getMessageFlowConfigurations();
 

Modified: trunk/src/main/org/jboss/messaging/core/config/cluster/BroadcastGroupConfiguration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/cluster/BroadcastGroupConfiguration.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/config/cluster/BroadcastGroupConfiguration.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -24,9 +24,10 @@
 package org.jboss.messaging.core.config.cluster;
 
 import java.io.Serializable;
-import java.util.ArrayList;
 import java.util.List;
 
+import org.jboss.messaging.util.Pair;
+
 /**
  * A BroadcastGroupConfiguration
  *
@@ -52,7 +53,7 @@
    
    private final long broadcastPeriod;
    
-   private final List<String> connectorNames;
+   private final List<Pair<String, String>> connectorInfos;
 
    public BroadcastGroupConfiguration(final String name,
                                       final String localBindAddress,
@@ -60,7 +61,7 @@
                                       final String groupAddress,
                                       final int groupPort,
                                       final long broadcastPeriod,
-                                      final List<String> connectorNames)
+                                      final List<Pair<String, String>> connectorInfos)
    {
       super();
       this.name = name;
@@ -69,7 +70,7 @@
       this.groupAddress = groupAddress;
       this.groupPort = groupPort;
       this.broadcastPeriod = broadcastPeriod;
-      this.connectorNames = connectorNames;
+      this.connectorInfos = connectorInfos;
    }
 
    public String getName()
@@ -102,9 +103,9 @@
       return broadcastPeriod;
    }
    
-   public List<String> getConnectorNames()
+   public List<Pair<String, String>> getConnectorInfos()
    {
-      return connectorNames;
+      return connectorInfos;
    }
 
 }

Modified: trunk/src/main/org/jboss/messaging/core/config/cluster/MessageFlowConfiguration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/cluster/MessageFlowConfiguration.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/config/cluster/MessageFlowConfiguration.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,7 +25,7 @@
 import java.io.Serializable;
 import java.util.List;
 
-import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A MessageFlowConfiguration
@@ -52,7 +52,7 @@
 
    private final long maxBatchTime;
 
-   private final List<String> staticConnectorNames;
+   private final List<Pair<String, String>> staticConnectorNamePairs;
 
    private final String discoveryGroupName;
 
@@ -65,7 +65,7 @@
                                    final int maxBatchSize,
                                    final long maxBatchTime,
                                    final String transformerClassName,
-                                   final List<String> staticConnectorNames)
+                                   final List<Pair<String, String>> staticConnectorNamePairs)
    {
       this.name = name;
       this.address = address;
@@ -74,7 +74,7 @@
       this.maxBatchSize = maxBatchSize;
       this.maxBatchTime = maxBatchTime;
       this.transformerClassName = transformerClassName;
-      this.staticConnectorNames = staticConnectorNames;
+      this.staticConnectorNamePairs = staticConnectorNamePairs;
       this.discoveryGroupName = null;
    }
 
@@ -94,7 +94,7 @@
       this.maxBatchSize = maxBatchSize;
       this.maxBatchTime = maxBatchTime;
       this.transformerClassName = transformerClassName;
-      this.staticConnectorNames = null;
+      this.staticConnectorNamePairs = null;
       this.discoveryGroupName = discoveryGroupName;
    }
 
@@ -133,9 +133,9 @@
       return transformerClassName;
    }
 
-   public List<String> getConnectorNames()
+   public List<Pair<String, String>> getConnectorNamePairs()
    {
-      return staticConnectorNames;
+      return staticConnectorNamePairs;
    }
 
    public String getDiscoveryGroupName()

Modified: trunk/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/config/impl/ConfigurationImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -143,7 +143,7 @@
    
    protected Set<BroadcastGroupConfiguration> broadcastGroupConfigurations = new HashSet<BroadcastGroupConfiguration>();
    
-   protected Set<DiscoveryGroupConfiguration> discoveryGroupConfigurations = new HashSet<DiscoveryGroupConfiguration>();
+   protected Map<String, DiscoveryGroupConfiguration> discoveryGroupConfigurations = new HashMap<String, DiscoveryGroupConfiguration>();
 
    // Paging related attributes ------------------------------------------------------------
 
@@ -322,12 +322,12 @@
       this.broadcastGroupConfigurations = broadcastGroupConfigurations;
    }
 
-   public Set<DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations()
+   public Map<String, DiscoveryGroupConfiguration> getDiscoveryGroupConfigurations()
    {
       return discoveryGroupConfigurations;
    }
 
-   public void setDiscoveryGroupConfigurations(Set<DiscoveryGroupConfiguration> discoveryGroupConfigurations)
+   public void setDiscoveryGroupConfigurations(Map<String, DiscoveryGroupConfiguration> discoveryGroupConfigurations)
    {
       this.discoveryGroupConfigurations = discoveryGroupConfigurations;
    }

Modified: trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/config/impl/FileConfiguration.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -36,6 +36,7 @@
 import org.jboss.messaging.core.config.cluster.MessageFlowConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.JournalType;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.XMLUtil;
 import org.w3c.dom.Element;
@@ -104,7 +105,9 @@
 
       managementAddress = new SimpleString(getString(e, "management-address", managementAddress.toString()));
 
-      managementNotificationAddress = new SimpleString(getString(e, "management-notification-address", managementNotificationAddress.toString()));
+      managementNotificationAddress = new SimpleString(getString(e,
+                                                                 "management-notification-address",
+                                                                 managementNotificationAddress.toString()));
 
       NodeList interceptorNodes = e.getElementsByTagName("remoting-interceptors");
 
@@ -124,7 +127,7 @@
             }
          }
       }
-      
+
       interceptorClassNames = interceptorList;
 
       NodeList backups = e.getElementsByTagName("backup-connector");
@@ -137,15 +140,15 @@
 
          backupConnectorName = backupNode.getAttributes().getNamedItem("connector-name").getNodeValue();
       }
-      
+
       NodeList connectorNodes = e.getElementsByTagName("connector");
-      
+
       for (int i = 0; i < connectorNodes.getLength(); i++)
       {
          Node connectorNode = connectorNodes.item(i);
 
          TransportConfiguration connectorConfig = parseTransportConfiguration(connectorNode);
-         
+
          if (connectorConfig.getName() == null)
          {
             log.warn("Cannot deploy a connector with no name specified.");
@@ -160,7 +163,7 @@
 
             continue;
          }
-         
+
          connectorConfigs.put(connectorConfig.getName(), connectorConfig);
       }
 
@@ -183,7 +186,7 @@
 
          parseBroadcastGroupConfiguration(bgNode);
       }
-      
+
       NodeList dgNodes = e.getElementsByTagName("discovery-group");
 
       for (int i = 0; i < dgNodes.getLength(); i++)
@@ -192,7 +195,7 @@
 
          parseDiscoveryGroupConfiguration(dgNode);
       }
-      
+
       NodeList mfNodes = e.getElementsByTagName("message-flow");
 
       for (int i = 0; i < mfNodes.getLength(); i++)
@@ -205,7 +208,7 @@
       // Persistence config
 
       largeMessagesDirectory = getString(e, "large-messages-directory", largeMessagesDirectory);
-      
+
       bindingsDirectory = getString(e, "bindings-directory", bindingsDirectory);
 
       createBindingsDir = getBoolean(e, "create-bindings-dir", createBindingsDir);
@@ -215,7 +218,7 @@
       pagingDirectory = getString(e, "paging-directory", pagingDirectory);
 
       pagingMaxGlobalSize = getLong(e, "paging-max-global-size-bytes", pagingMaxGlobalSize);
-      
+
       pagingDefaultSize = getLong(e, "paging-default-size", pagingDefaultSize);
 
       createJournalDir = getBoolean(e, "create-journal-dir", createJournalDir);
@@ -308,9 +311,9 @@
    private TransportConfiguration parseTransportConfiguration(final Node node)
    {
       Node nameNode = node.getAttributes().getNamedItem("name");
-                 
+
       String name = nameNode != null ? nameNode.getNodeValue() : null;
-      
+
       NodeList children = node.getChildNodes();
 
       String clazz = null;
@@ -366,11 +369,11 @@
                throw new IllegalArgumentException("Invalid parameter type " + type);
             }
          }
-      }               
+      }
 
       return new TransportConfiguration(clazz, params, name);
    }
-   
+
    private void parseBroadcastGroupConfiguration(final Element bgNode)
    {
       String name = bgNode.getAttribute("name");
@@ -386,9 +389,9 @@
       long broadcastPeriod = ConfigurationImpl.DEFAULT_BROADCAST_PERIOD;
 
       NodeList children = bgNode.getChildNodes();
-      
-      List<String> connectorNames = new ArrayList<String>();
 
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+
       for (int j = 0; j < children.getLength(); j++)
       {
          Node child = children.item(j);
@@ -416,8 +419,19 @@
          else if (child.getNodeName().equals("connector-ref"))
          {
             String connectorName = child.getAttributes().getNamedItem("connector-name").getNodeValue();
-            
-            connectorNames.add(connectorName);
+
+            Node backupConnectorNode = child.getAttributes().getNamedItem("backup-connector-name");
+
+            String backupConnectorName = null;
+
+            if (backupConnectorNode != null)
+            {
+               backupConnectorName = backupConnectorNode.getNodeValue();
+            }
+
+            Pair<String, String> connectorInfo = new Pair<String, String>(connectorName, backupConnectorName);
+
+            connectorNames.add(connectorInfo);
          }
       }
 
@@ -428,10 +442,10 @@
                                                                            groupPort,
                                                                            broadcastPeriod,
                                                                            connectorNames);
-      
+
       broadcastGroupConfigurations.add(config);
    }
-   
+
    private void parseDiscoveryGroupConfiguration(final Element bgNode)
    {
       String name = bgNode.getAttribute("name");
@@ -464,12 +478,21 @@
 
       DiscoveryGroupConfiguration config = new DiscoveryGroupConfiguration(name,
                                                                            groupAddress,
-                                                                           groupPort,                                                              
+                                                                           groupPort,
                                                                            refreshTimeout);
-      
-      discoveryGroupConfigurations.add(config);
+
+      if (discoveryGroupConfigurations.containsKey(name))
+      {
+         log.warn("There is already a discovery group with name " + name + " deployed. This one will not be deployed.");
+
+         return;
+      }
+      else
+      {
+         discoveryGroupConfigurations.put(name, config);
+      }
    }
-   
+
    private void parseMessageFlowConfiguration(final Element bgNode)
    {
       String name = bgNode.getAttribute("name");
@@ -484,7 +507,7 @@
 
       long maxBatchTime = DEFAULT_MAX_FORWARD_BATCH_TIME;
 
-      List<String> staticConnectorNames = new ArrayList<String>();
+      List<Pair<String, String>> staticConnectorNames = new ArrayList<Pair<String, String>>();
 
       String discoveryGroupName = null;
 
@@ -516,9 +539,9 @@
          {
             maxBatchTime = parseLong(child);
          }
-         else if (child.getNodeName().equals("discovery-group-name"))
+         else if (child.getNodeName().equals("discovery-group-ref"))
          {
-            discoveryGroupName = child.getTextContent().trim();
+            discoveryGroupName = child.getAttributes().getNamedItem("discovery-group-name").getNodeValue();
          }
          else if (child.getNodeName().equals("transformer-class-name"))
          {
@@ -527,24 +550,45 @@
          else if (child.getNodeName().equals("connector"))
          {
             String connectorName = child.getAttributes().getNamedItem("connector-name").getNodeValue();
-            
-            staticConnectorNames.add(connectorName);
+
+            Node backupNode = child.getAttributes().getNamedItem("backup-connector-name");
+
+            String backupConnectorName = null;
+
+            if (backupNode != null)
+            {
+               backupConnectorName = backupNode.getNodeValue();
+            }
+
+            staticConnectorNames.add(new Pair<String, String>(connectorName, backupConnectorName));
          }
       }
 
       MessageFlowConfiguration config;
-      
+
       if (!staticConnectorNames.isEmpty())
       {
-         config = new MessageFlowConfiguration(name, address, filterString, fanout, maxBatchSize, maxBatchTime,
-                                               transformerClassName, staticConnectorNames);
+         config = new MessageFlowConfiguration(name,
+                                               address,
+                                               filterString,
+                                               fanout,
+                                               maxBatchSize,
+                                               maxBatchTime,
+                                               transformerClassName,
+                                               staticConnectorNames);
       }
       else
       {
-         config = new MessageFlowConfiguration(name, address, filterString, fanout, maxBatchSize, maxBatchTime,
-                                               transformerClassName, discoveryGroupName);
+         config = new MessageFlowConfiguration(name,
+                                               address,
+                                               filterString,
+                                               fanout,
+                                               maxBatchSize,
+                                               maxBatchTime,
+                                               transformerClassName,
+                                               discoveryGroupName);
       }
-      
+
       messageFlowConfigurations.add(config);
    }
 

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/remoting/ConnectionManager.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1,48 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * 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.messaging.core.remoting;
-
-import java.util.Set;
-
-/**
- * A ConnectionManager
- *
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * 
- * Created 24 Oct 2008 09:07:05
- *
- *
- */
-public interface ConnectionManager
-{
-   RemotingConnection getConnection();
-   
-   RemotingConnection createConnection();
-   
-   void returnConnection(Object connectionID);
-   
-   int numConnections();
-   
-   Set<RemotingConnection> getConnections();
-}

Deleted: trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/ConnectionManagerImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1,330 +0,0 @@
-/*
- * JBoss, Home of Professional Open Source
- * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
- * 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.messaging.core.remoting.impl;
-
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-
-import org.jboss.messaging.core.exception.MessagingException;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.ConnectionManager;
-import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.spi.Connection;
-import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
-import org.jboss.messaging.core.remoting.spi.Connector;
-import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
-import org.jboss.messaging.util.JBMThreadFactory;
-
-/**
- * A ConnectionManagerImpl
- *
- * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
- * 
- * Created 24 Oct 2008 09:08:12
- *
- *
- */
-public class ConnectionManagerImpl implements ConnectionManager, ConnectionLifeCycleListener
-{
-   private static final Logger log = Logger.getLogger(ConnectionManagerImpl.class);
-
-   private final ConnectorFactory connectorFactory;
-
-   private final Map<String, Object> params;
-
-   private final long pingInterval;
-
-   private final long callTimeout;
-
-   private final int maxConnections;
-
-   // TODO - allow this to be configurable
-   private static final ScheduledThreadPoolExecutor pingExecutor = new ScheduledThreadPoolExecutor(5,
-                                                                                                   new JBMThreadFactory("jbm-pinger-threads"));
-
-   private final Map<Object, ConnectionEntry> connections = new LinkedHashMap<Object, ConnectionEntry>();
-
-   private int refCount;
-
-   private Iterator<ConnectionEntry> mapIterator;
-
-   private Object failConnectionLock = new Object();
-   
-   public ConnectionManagerImpl(final ConnectorFactory connectorFactory,
-                                final Map<String, Object> params,
-                                final long pingInterval,
-                                final long callTimeout,
-                                final int maxConnections)
-   {
-      this.connectorFactory = connectorFactory;
-
-      this.params = params;
-
-      this.pingInterval = pingInterval;
-
-      this.callTimeout = callTimeout;
-
-      this.maxConnections = maxConnections;
-   }
-
-   public RemotingConnection createConnection()
-   {
-      DelegatingBufferHandler handler = new DelegatingBufferHandler();
-
-      NoCacheConnectionLifeCycleListener listener = new NoCacheConnectionLifeCycleListener();
-
-      Connector connector = connectorFactory.createConnector(params, handler, listener);
-
-      connector.start();
-
-      Connection tc = connector.createConnection();
-
-      if (tc == null)
-      {
-         throw new IllegalStateException("Failed to connect");
-      }
-      
-      RemotingConnection connection = new RemotingConnectionImpl(tc, callTimeout, pingInterval, pingExecutor, null);
-
-      handler.conn = connection;
-
-      listener.conn = connection;
-
-      connection.startPinger();
-
-      return connection;
-   }
-
-   public synchronized RemotingConnection getConnection()
-   {
-      RemotingConnection conn;
-
-      if (connections.size() < maxConnections)
-      {
-         // Create a new one
-
-         DelegatingBufferHandler handler = new DelegatingBufferHandler();
-
-         Connector connector = connectorFactory.createConnector(params, handler, this);
-
-         connector.start();
-
-         Connection tc = connector.createConnection();
-
-         if (tc == null)
-         {
-            throw new IllegalStateException("Failed to connect");
-         }
-
-         conn = new RemotingConnectionImpl(tc, callTimeout, pingInterval, pingExecutor, null);
-
-         handler.conn = conn;
-
-         conn.startPinger();
-
-         connections.put(conn.getID(), new ConnectionEntry(conn, connector));
-      }
-      else
-      {
-         // Return one round-robin from the list
-
-         if (mapIterator == null || !mapIterator.hasNext())
-         {
-            mapIterator = connections.values().iterator();
-         }
-
-         ConnectionEntry entry = mapIterator.next();
-
-         conn = entry.connection;
-      }
-
-      refCount++;
-
-      return conn;
-   }
-
-   public synchronized void returnConnection(final Object connectionID)
-   {
-      ConnectionEntry entry = connections.get(connectionID);
-
-      if (refCount != 0)
-      {
-         refCount--;
-      }
-
-      if (entry != null)
-      {
-         checkCloseConnections();
-      }
-      else
-      {
-         // Can be legitimately null if session was closed before then went to remove session from csf
-         // and locked since failover had started then after failover removes it but it's already been failed
-      }
-   }
-
-   public void failConnection(final MessagingException me)
-   {
-      synchronized (failConnectionLock)
-      {
-         // When a single connection fails, we fail *all* the connections
-
-         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());
-
-         for (ConnectionEntry entry : copy)
-         {
-            entry.connection.fail(me);
-         }
-
-         refCount = 0;
-      }
-   }
-
-   public synchronized int getRefCount()
-   {
-      return refCount;
-   }
-
-   public synchronized int numConnections()
-   {
-      return connections.size();
-   }
-
-   public synchronized Set<RemotingConnection> getConnections()
-   {
-      Set<RemotingConnection> conns = new HashSet<RemotingConnection>();
-
-      for (ConnectionEntry entry : connections.values())
-      {
-         conns.add(entry.connection);
-      }
-
-      return conns;
-   }
-
-   // Private -------------------------------------------------------
-
-   private void checkCloseConnections()
-   {
-      if (refCount == 0)
-      {
-         // Close connections
-
-         Set<ConnectionEntry> copy = new HashSet<ConnectionEntry>(connections.values());
-
-         connections.clear();
-
-         for (ConnectionEntry entry : copy)
-         {
-            try
-            {
-               entry.connection.destroy();
-
-               entry.connector.close();
-            }
-            catch (Throwable ignore)
-            {
-            }
-         }
-      }
-   }
-
-   // ConnectionLifeCycleListener implementation --------------------
-
-   public void connectionCreated(final Connection connection)
-   {
-   }
-
-   public void connectionDestroyed(final Object connectionID)
-   {
-      // If conn still exists here this means that the underlying transport
-      // conn has been closed from the server side without
-      // being returned from the client side so we need to fail the conn and
-      // call it's listeners
-      MessagingException me = new MessagingException(MessagingException.OBJECT_CLOSED, "The conn has been closed by the server");
-      
-      failConnection(me);
-   }
-
-   public void connectionException(final Object connectionID, final MessagingException me)
-   {
-      failConnection(me);
-   }
-
-   // Inner classes ----------------------------------------------------------------
-
-   private class ConnectionEntry
-   {
-      ConnectionEntry(final RemotingConnection connection, final Connector connector)
-      {
-         this.connection = connection;
-
-         this.connector = connector;
-      }
-
-      final RemotingConnection connection;
-
-      final Connector connector;
-   }
-
-   private class DelegatingBufferHandler extends AbstractBufferHandler
-   {
-      RemotingConnection conn;
-
-      public void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
-      {
-         conn.bufferReceived(connectionID, buffer);
-      }
-   }
-
-   private static class NoCacheConnectionLifeCycleListener implements ConnectionLifeCycleListener
-   {
-      private RemotingConnection conn;
-
-      public void connectionCreated(final Connection connection)
-      {
-      }
-
-      public void connectionDestroyed(final Object connectionID)
-      {
-         if (conn != null)
-         {
-            conn.destroy();
-         }
-      }
-
-      public void connectionException(final Object connectionID, final MessagingException me)
-      {
-         if (conn != null)
-         {
-            conn.fail(me);
-         }
-      }
-   }
-
-}

Modified: trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/remoting/impl/RemotingConnectionImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -133,6 +133,9 @@
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXASetTimeoutResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.SessionXAStartMessage;
 import org.jboss.messaging.core.remoting.spi.Connection;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
+import org.jboss.messaging.core.remoting.spi.Connector;
+import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.core.remoting.spi.MessagingBuffer;
 import org.jboss.messaging.util.SimpleIDGenerator;
 
@@ -153,6 +156,43 @@
    // Static
    // ---------------------------------------------------------------------------------------
 
+   public static RemotingConnection createConnection(final ConnectorFactory connectorFactory,
+                                                     final Map<String, Object> params,
+                                                     final long callTimeout,
+                                                     final long pingInterval,
+                                                     final ScheduledExecutorService pingExecutor,
+                                                     final ConnectionLifeCycleListener listener)
+   {
+      DelegatingBufferHandler handler = new DelegatingBufferHandler();
+
+      Connector connector = connectorFactory.createConnector(params, handler, listener);
+
+      connector.start();
+
+      Connection tc = connector.createConnection();
+
+      if (tc == null)
+      {
+         throw new IllegalStateException("Failed to connect");
+      }
+
+      RemotingConnection connection = new RemotingConnectionImpl(tc, callTimeout, pingInterval, pingExecutor, null);
+
+      handler.conn = connection;
+
+      return connection;
+   }
+
+   private static class DelegatingBufferHandler extends AbstractBufferHandler
+   {
+      RemotingConnection conn;
+
+      public void bufferReceived(final Object connectionID, final MessagingBuffer buffer)
+      {
+         conn.bufferReceived(connectionID, buffer);
+      }
+   }
+
    // Attributes
    // -----------------------------------------------------------------------------------
 
@@ -817,9 +857,9 @@
       private final Condition failoverCondition = lock.newCondition();
 
       private final Object sendLock = new Object();
-      
+
       private final Object sendBlockingLock = new Object();
-      
+
       private final Object replicationLock = new Object();
 
       private boolean failingOver;
@@ -963,11 +1003,15 @@
             }
          }
       }
-      
+
       public Packet sendBlocking(final Packet packet) throws MessagingException
       {
+         // log.info("sending blocking channel id" + id + " packet id " + packet.getType() + " on connection " +
+         // System.identityHashCode(this.connection) + " " + packet.getType());
+
          if (closed)
          {
+            // log.info("channel is closed");
             throw new MessagingException(MessagingException.NOT_CONNECTED, "Connection is destroyed");
          }
 
@@ -975,17 +1019,17 @@
          {
             throw new IllegalStateException("Cannot do a blocking call timeout on a server side connection");
          }
-         
-         //Synchronized since can't be called concurrently by more than one thread and this can occur
-         //E.g. blocking acknowledge() from inside a message handler at some time as other operation on main thread
+
+         // Synchronized since can't be called concurrently by more than one thread and this can occur
+         // E.g. blocking acknowledge() from inside a message handler at some time as other operation on main thread
          synchronized (sendBlockingLock)
-         {   
+         {
             packet.setChannelID(id);
-   
+
             final MessagingBuffer buffer = connection.transportConnection.createBuffer(packet.getRequiredBufferSize());
-   
+
             int size = packet.encode(buffer);
-   
+
             // Must block on semaphore outside the main lock or this can prevent failover from occurring
             if (sendSemaphore != null)
             {
@@ -998,9 +1042,9 @@
                   throw new IllegalStateException("Semaphore interrupted");
                }
             }
-   
+
             lock.lock();
-   
+
             try
             {
                while (failingOver)
@@ -1014,20 +1058,20 @@
                   {
                   }
                }
-   
+
                response = null;
-   
+
                if (resendCache != null && packet.isRequiresConfirmations())
                {
                   resendCache.add(packet);
                }
-   
+
                connection.transportConnection.write(buffer);
-   
+
                long toWait = connection.blockingCallTimeout;
-   
+
                long start = System.currentTimeMillis();
-   
+
                while (response == null && toWait > 0)
                {
                   try
@@ -1037,24 +1081,24 @@
                   catch (InterruptedException e)
                   {
                   }
-   
+
                   final long now = System.currentTimeMillis();
-   
+
                   toWait -= now - start;
-   
+
                   start = now;
                }
-   
+
                if (response == null)
                {
                   throw new MessagingException(MessagingException.CONNECTION_TIMEDOUT,
                                                "Timed out waiting for response when sending packet " + packet.getType());
                }
-   
+
                if (response.getType() == PacketImpl.EXCEPTION)
                {
                   final MessagingExceptionMessage mem = (MessagingExceptionMessage)response;
-   
+
                   throw mem.getException();
                }
                else
@@ -1078,11 +1122,11 @@
             if (replicatingChannel != null)
             {
                DelayedResult result = new DelayedResult();
-   
+
                responseActions.add(result);
-   
+
                replicatingChannel.send(packet);
-   
+
                return result;
             }
             else
@@ -1098,13 +1142,13 @@
          synchronized (replicationLock)
          {
             replicatingChannel = null;
-   
+
             // Execute all the response actions now
-   
+
             while (true)
             {
                DelayedResult result = responseActions.poll();
-   
+
                if (result != null)
                {
                   result.replicated();
@@ -1152,7 +1196,7 @@
             }
          }
 
-         //Must execute outside of lock
+         // Must execute outside of lock
          if (result != null)
          {
             result.replicated();
@@ -1166,6 +1210,7 @@
 
       public void close()
       {
+         // log.info("channel " + id + " is being closed on connection " + System.identityHashCode(connection));
          if (closed)
          {
             return;
@@ -1338,15 +1383,15 @@
             receivedBytes += packet.getPacketSize();
 
             if (receivedBytes >= confWindowSize)
-            {               
+            {
                receivedBytes = 0;
 
                if (connection.active)
                {
                   final Packet confirmed = new PacketsConfirmedMessage(lastReceivedCommandID);
-   
+
                   confirmed.setChannelID(id);
-                  
+
                   doWrite(confirmed);
                }
             }

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/BroadcastGroup.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/BroadcastGroup.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/BroadcastGroup.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,6 +25,7 @@
 
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.server.MessagingComponent;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A BroadcastGroup
@@ -37,10 +38,8 @@
  */
 public interface BroadcastGroup extends MessagingComponent
 {
-   void addConnector(final TransportConfiguration connector);
+   void addConnectorPair(final Pair<TransportConfiguration, TransportConfiguration> connectorPair);
 
-   void removeConnector(final TransportConfiguration connector);
-
    int size();
 
    void broadcastConnectors() throws Exception;

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/DiscoveryGroup.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/DiscoveryGroup.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/DiscoveryGroup.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -27,6 +27,7 @@
 
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.server.MessagingComponent;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A DiscoveryGroup
@@ -39,7 +40,7 @@
  */
 public interface DiscoveryGroup extends MessagingComponent
 {
-   List<TransportConfiguration> getConnectors();
+   List<Pair<TransportConfiguration, TransportConfiguration>> getConnectors();
    
    boolean waitForBroadcast(long timeout);
    

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/impl/BroadcastGroupImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/impl/BroadcastGroupImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/impl/BroadcastGroupImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -34,6 +34,7 @@
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.cluster.BroadcastGroup;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A BroadcastGroupImpl
@@ -57,7 +58,7 @@
 
    private DatagramSocket socket;
    
-   private final List<TransportConfiguration> connectors = new ArrayList<TransportConfiguration>();
+   private final List<Pair<TransportConfiguration, TransportConfiguration>> connectorPairs = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
    
    private volatile boolean started;
    
@@ -115,19 +116,14 @@
       return started;
    }
    
-   public void addConnector(final TransportConfiguration connector)
+   public void addConnectorPair(final Pair<TransportConfiguration, TransportConfiguration> connectorPair)
    {
-      connectors.add(connector);
+      connectorPairs.add(connectorPair);
    }
 
-   public void removeConnector(final TransportConfiguration connector)
-   {
-      connectors.remove(connector);
-   }
-
    public int size()
    {
-      return connectors.size();
+      return connectorPairs.size();
    }
    
    public void broadcastConnectors() throws Exception
@@ -138,11 +134,22 @@
 
       ObjectOutputStream oos = new ObjectOutputStream(bos);
 
-      oos.writeInt(connectors.size());
+      oos.writeInt(connectorPairs.size());
 
-      for (TransportConfiguration connector : connectors)
+      for (Pair<TransportConfiguration, TransportConfiguration> connectorPair : connectorPairs)
       {
-         oos.writeObject(connector);
+         oos.writeObject(connectorPair.a);
+         
+         if (connectorPair.b != null)
+         {
+            oos.writeBoolean(true);
+            
+            oos.writeObject(connectorPair.b);
+         }
+         else
+         {
+            oos.writeBoolean(false);
+         }
       }
 
       oos.flush();

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ClusterManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ClusterManagerImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ClusterManagerImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -48,6 +48,7 @@
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.util.ExecutorFactory;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -115,7 +116,7 @@
          deployBroadcastGroup(config);
       }
 
-      for (DiscoveryGroupConfiguration config : configuration.getDiscoveryGroupConfigurations())
+      for (DiscoveryGroupConfiguration config : configuration.getDiscoveryGroupConfigurations().values())
       {
          deployDiscoveryGroup(config);
       }
@@ -182,20 +183,33 @@
                                                         config.getLocalBindPort(),
                                                         groupAddress,
                                                         config.getGroupPort());
-      
-      for (String connectorName: config.getConnectorNames())
+
+      for (Pair<String, String> connectorInfo : config.getConnectorInfos())
       {
-         TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName);
-         
+         TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorInfo.a);
+
          if (connector == null)
          {
-            log.warn("There is no connector deployed with name '" + connectorName + "'. The broadcast group with name '" +
-                     config.getName() + "' will not be deployed.");
-            
+            logWarnNoConnector(config.getName(), connectorInfo.a);
+
             return;
          }
-         
-         group.addConnector(connector);
+
+         TransportConfiguration backupConnector = null;
+
+         if (connectorInfo.b != null)
+         {
+            backupConnector = configuration.getConnectorConfigurations().get(connectorInfo.b);
+
+            if (connector == null)
+            {
+               logWarnNoConnector(config.getName(), connectorInfo.b);
+
+               return;
+            }
+         }
+
+         group.addConnectorPair(new Pair<TransportConfiguration, TransportConfiguration>(connector, backupConnector));
       }
 
       ScheduledFuture<?> future = scheduledExecutor.scheduleWithFixedDelay(group,
@@ -210,6 +224,14 @@
       group.start();
    }
 
+   private void logWarnNoConnector(final String connectorName, final String bgName)
+   {
+      log.warn("There is no connector deployed with name '" + connectorName +
+               "'. The broadcast group with name '" +
+               bgName +
+               "' will not be deployed.");
+   }
+
    private synchronized void deployDiscoveryGroup(final DiscoveryGroupConfiguration config) throws Exception
    {
       if (discoveryGroups.containsKey(config.getName()))
@@ -291,21 +313,36 @@
       {
          // Create message flow with list of static connectors
 
-         List<TransportConfiguration> conns = new ArrayList<TransportConfiguration>();
+         List<Pair<TransportConfiguration, TransportConfiguration>> conns = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
 
-         for (String connectorName : config.getConnectorNames())
+         for (Pair<String, String> connectorNamePair : config.getConnectorNamePairs())
          {
-            TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName);
+            TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorNamePair.a);
 
             if (connector == null)
             {
-               log.warn("No connector defined with name '" + connectorName +
+               log.warn("No connector defined with name '" + connectorNamePair.a +
                         "'. The message flow will not be deployed.");
 
                return;
             }
 
-            conns.add(connector);
+            TransportConfiguration backupConnector = null;
+
+            if (connectorNamePair.b != null)
+            {
+               backupConnector = configuration.getConnectorConfigurations().get(connectorNamePair.b);
+
+               if (backupConnector == null)
+               {
+                  log.warn("No connector defined with name '" + connectorNamePair.b +
+                           "'. The message flow will not be deployed.");
+
+                  return;
+               }
+            }
+
+            conns.add(new Pair<TransportConfiguration, TransportConfiguration>(connector, backupConnector));
          }
 
          flow = new MessageFlowImpl(new SimpleString(config.getName()),

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/impl/DiscoveryGroupImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/impl/DiscoveryGroupImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/impl/DiscoveryGroupImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -38,6 +38,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.server.cluster.DiscoveryGroup;
 import org.jboss.messaging.core.server.cluster.DiscoveryListener;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A DiscoveryGroupImpl
@@ -63,7 +64,7 @@
    
    private final Object waitLock = new Object();
    
-   private final Map<TransportConfiguration, Long> connectors = new HashMap<TransportConfiguration, Long>();
+   private final Map<Pair<TransportConfiguration, TransportConfiguration>, Long> connectors = new HashMap<Pair<TransportConfiguration, TransportConfiguration>, Long>();
    
    private final long timeout;
    
@@ -80,6 +81,8 @@
       this.timeout = timeout;
       
       thread = new Thread(this);
+      
+      thread.setDaemon(true);
    }
    
    public synchronized void start() throws Exception
@@ -122,9 +125,9 @@
       return started;
    }
         
-   public synchronized List<TransportConfiguration> getConnectors()
+   public synchronized List<Pair<TransportConfiguration, TransportConfiguration>> getConnectors()
    {
-      return new ArrayList<TransportConfiguration>(connectors.keySet());
+      return new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>(connectors.keySet());
    }
    
    public boolean waitForBroadcast(final long timeout)
@@ -198,14 +201,51 @@
             
             int size = ois.readInt();
             
+            boolean changed = false;
+            
             synchronized (this)
             {            
                for (int i = 0; i < size; i++)
                {
                   TransportConfiguration connector = (TransportConfiguration)ois.readObject();
                   
-                  connectors.put(connector, System.currentTimeMillis());
+                  boolean existsBackup = ois.readBoolean();
+                  
+                  TransportConfiguration backupConnector = null;
+                  
+                  if (existsBackup)
+                  {
+                     backupConnector = (TransportConfiguration)ois.readObject();
+                  }
+                  
+                  Pair<TransportConfiguration, TransportConfiguration> connectorPair =
+                     new Pair<TransportConfiguration, TransportConfiguration>(connector, backupConnector);
+                  
+                  Long oldVal = connectors.put(connectorPair, System.currentTimeMillis());
+                  
+                  if (oldVal == null)
+                  {
+                     changed = true;
+                  }
                }
+               
+               long now = System.currentTimeMillis();
+               
+               Iterator<Map.Entry<Pair<TransportConfiguration, TransportConfiguration>, Long>> iter = connectors.entrySet().iterator();
+               
+               //Weed out any expired connectors
+               
+               while (iter.hasNext())
+               {
+                  Map.Entry<Pair<TransportConfiguration, TransportConfiguration>, Long> entry = iter.next();
+                  
+                  if (entry.getValue() + timeout <= now)
+                  {
+                     iter.remove();
+                     
+                     changed = true;
+                  }
+               }
             }
             
             packet.setLength(data.length);
@@ -217,7 +257,10 @@
                waitLock.notify();
             }
             
-            callListeners();
+            if (changed)
+            {
+               callListeners();
+            }
          }
       }
       catch (Exception e)
@@ -236,24 +279,8 @@
       this.listeners.remove(listener);
    }
    
-   private synchronized void callListeners()
-   {
-      long now = System.currentTimeMillis();
-      
-      Iterator<Map.Entry<TransportConfiguration, Long>> iter = connectors.entrySet().iterator();
-      
-      //Weed out any expired connectors
-      
-      while (iter.hasNext())
-      {
-         Map.Entry<TransportConfiguration, Long> entry = iter.next();
-         
-         if (entry.getValue() + timeout <= now)
-         {
-            iter.remove();
-         }
-      }
-      
+   private void callListeners()
+   {      
       for (DiscoveryListener listener: listeners)
       {
          try

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ForwarderImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ForwarderImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/impl/ForwarderImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -47,6 +47,7 @@
 import org.jboss.messaging.core.transaction.Transaction;
 import org.jboss.messaging.core.transaction.impl.TransactionImpl;
 import org.jboss.messaging.util.Future;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A ForwarderImpl
@@ -108,7 +109,7 @@
    // Public --------------------------------------------------------
 
    public ForwarderImpl(final Queue queue,
-                        final TransportConfiguration connectorConfig,
+                        final Pair<TransportConfiguration,TransportConfiguration> connectorPair,
                         final Executor executor,
                         final int maxBatchSize,
                         final long maxBatchTime,
@@ -134,7 +135,7 @@
       
       this.transformer = transformer;
       
-      this.csf = new ClientSessionFactoryImpl(connectorConfig);  
+      this.csf = new ClientSessionFactoryImpl(connectorPair.a, connectorPair.b);  
       
       if (maxBatchTime != -1)
       {

Modified: trunk/src/main/org/jboss/messaging/core/server/cluster/impl/MessageFlowImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/cluster/impl/MessageFlowImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/cluster/impl/MessageFlowImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -45,6 +45,7 @@
 import org.jboss.messaging.core.settings.HierarchicalRepository;
 import org.jboss.messaging.core.settings.impl.QueueSettings;
 import org.jboss.messaging.util.ExecutorFactory;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.messaging.util.UUIDGenerator;
 
@@ -83,10 +84,10 @@
 
    private final Transformer transformer;
 
-   private Map<TransportConfiguration, Forwarder> forwarders = new HashMap<TransportConfiguration, Forwarder>();
+   private Map<Pair<TransportConfiguration, TransportConfiguration>, Forwarder> forwarders = new HashMap<Pair<TransportConfiguration, TransportConfiguration>, Forwarder>();
 
    private final DiscoveryGroup discoveryGroup;
-   
+
    private final ScheduledExecutorService scheduledExecutor;
 
    private volatile boolean started;
@@ -106,7 +107,7 @@
                           final HierarchicalRepository<QueueSettings> queueSettingsRepository,
                           final ScheduledExecutorService scheduledExecutor,
                           final Transformer transformer,
-                          final List<TransportConfiguration> connectors) throws Exception
+                          final List<Pair<TransportConfiguration,TransportConfiguration>> connectors) throws Exception
    {
       this.name = name;
 
@@ -131,7 +132,7 @@
       this.transformer = transformer;
 
       this.discoveryGroup = null;
-      
+
       this.scheduledExecutor = scheduledExecutor;
 
       this.updateConnectors(connectors);
@@ -173,7 +174,7 @@
       this.postOffice = postOffice;
 
       this.queueSettingsRepository = queueSettingsRepository;
-      
+
       this.scheduledExecutor = scheduledExecutor;
 
       this.transformer = transformer;
@@ -187,6 +188,7 @@
       {
          return;
       }
+
       if (discoveryGroup != null)
       {
          updateConnectors(discoveryGroup.getConnectors());
@@ -228,7 +230,7 @@
    {
       try
       {
-         List<TransportConfiguration> connectors = discoveryGroup.getConnectors();
+         List<Pair<TransportConfiguration, TransportConfiguration>> connectors = discoveryGroup.getConnectors();
 
          updateConnectors(connectors);
       }
@@ -238,17 +240,17 @@
       }
    }
 
-   private void updateConnectors(final List<TransportConfiguration> connectors) throws Exception
+   private void updateConnectors(final List<Pair<TransportConfiguration, TransportConfiguration>> connectors) throws Exception
    {
-      Set<TransportConfiguration> connectorSet = new HashSet<TransportConfiguration>();
+      Set<Pair<TransportConfiguration, TransportConfiguration>> connectorSet = new HashSet<Pair<TransportConfiguration, TransportConfiguration>>();
 
       connectorSet.addAll(connectors);
 
-      Iterator<Map.Entry<TransportConfiguration, Forwarder>> iter = forwarders.entrySet().iterator();
+      Iterator<Map.Entry<Pair<TransportConfiguration,TransportConfiguration>, Forwarder>> iter = forwarders.entrySet().iterator();
 
       while (iter.hasNext())
       {
-         Map.Entry<TransportConfiguration, Forwarder> entry = iter.next();
+         Map.Entry<Pair<TransportConfiguration,TransportConfiguration>, Forwarder> entry = iter.next();
 
          if (!connectorSet.contains(entry.getKey()))
          {
@@ -260,9 +262,9 @@
          }
       }
 
-      for (TransportConfiguration connector : connectors)
+      for (Pair<TransportConfiguration,TransportConfiguration> connectorPair : connectors)
       {
-         if (!forwarders.containsKey(connector))
+         if (!forwarders.containsKey(connectorPair))
          {
             SimpleString queueName = new SimpleString("outflow." + name +
                                                       "." +
@@ -280,7 +282,7 @@
             }
 
             Forwarder forwarder = new ForwarderImpl(binding.getQueue(),
-                                                    connector,
+                                                    connectorPair,
                                                     executorFactory.getExecutor(),
                                                     maxBatchSize,
                                                     maxBatchTime,
@@ -290,7 +292,7 @@
                                                     scheduledExecutor,
                                                     transformer);
 
-            forwarders.put(connector, forwarder);
+            forwarders.put(connectorPair, forwarder);
 
             binding.getQueue().addConsumer(forwarder);
 

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/MessagingServerImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,7 +25,6 @@
 import java.util.concurrent.ScheduledThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 
-import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.core.exception.MessagingException;
@@ -40,12 +39,13 @@
 import org.jboss.messaging.core.postoffice.impl.PostOfficeImpl;
 import org.jboss.messaging.core.remoting.Channel;
 import org.jboss.messaging.core.remoting.ChannelHandler;
-import org.jboss.messaging.core.remoting.ConnectionManager;
 import org.jboss.messaging.core.remoting.RemotingConnection;
 import org.jboss.messaging.core.remoting.RemotingService;
-import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
+import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
 import org.jboss.messaging.core.remoting.impl.wireformat.CreateSessionResponseMessage;
 import org.jboss.messaging.core.remoting.impl.wireformat.ReattachSessionResponseMessage;
+import org.jboss.messaging.core.remoting.spi.Connection;
+import org.jboss.messaging.core.remoting.spi.ConnectionLifeCycleListener;
 import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
 import org.jboss.messaging.core.security.JBMSecurityManager;
 import org.jboss.messaging.core.security.Role;
@@ -120,6 +120,10 @@
 
    private ClusterManager clusterManager;
 
+   private ConnectorFactory backupConnectorFactory;
+
+   private Map<String, Object> backupConnectorParams;
+
    // plugins
 
    private StorageManager storageManager;
@@ -132,8 +136,6 @@
 
    private ManagementService managementService;
 
-   private ConnectionManager replicatingConnectionManager;
-
    private ScheduledThreadPoolExecutor messageExpiryExecutor;
 
    // Constructors
@@ -155,7 +157,7 @@
       {
          return;
       }
-    
+
       /*
        * The following components are pluggable on the messaging server: Configuration, StorageManager, RemotingService,
        * SecurityManager and ManagementRegistration They must already be injected by the time the messaging server
@@ -245,8 +247,13 @@
       postOffice.start();
       MessageExpiryRunner messageExpiryRunner = new MessageExpiryRunner(postOffice);
       messageExpiryRunner.setPriority(3);
-      messageExpiryExecutor = new ScheduledThreadPoolExecutor(1, new JBMThreadFactory("JBM-scheduled-threads", configuration.getMessageExpiryThreadPriority()) );
-      messageExpiryExecutor.scheduleAtFixedRate(messageExpiryRunner, configuration.getMessageExpiryScanPeriod(), configuration.getMessageExpiryScanPeriod(), TimeUnit.MILLISECONDS);
+      messageExpiryExecutor = new ScheduledThreadPoolExecutor(1,
+                                                              new JBMThreadFactory("JBM-scheduled-threads",
+                                                                                   configuration.getMessageExpiryThreadPriority()));
+      messageExpiryExecutor.scheduleAtFixedRate(messageExpiryRunner,
+                                                configuration.getMessageExpiryScanPeriod(),
+                                                configuration.getMessageExpiryScanPeriod(),
+                                                TimeUnit.MILLISECONDS);
       resourceManager.start();
 
       // FIXME the destination corresponding to the notification address is always created
@@ -257,18 +264,18 @@
       }
 
       String backupConnectorName = configuration.getBackupConnectorName();
-      
+
       if (backupConnectorName != null)
       {
          TransportConfiguration backupConnector = configuration.getConnectorConfigurations().get(backupConnectorName);
-         
+
          if (backupConnector == null)
          {
             log.warn("connector with name '" + backupConnectorName + "' is not defined in the configuration.");
          }
          else
          {
-            ConnectorFactory backupConnectorFactory;
+
             ClassLoader loader = Thread.currentThread().getContextClassLoader();
             try
             {
@@ -281,15 +288,8 @@
                                                            "\"",
                                                   e);
             }
-   
-            Map<String, Object> backupConnectorParams = backupConnector.getParams();
-   
-            // TODO don't hardcode ping interval and code timeout
-            replicatingConnectionManager = new ConnectionManagerImpl(backupConnectorFactory,
-                                                                     backupConnectorParams,
-                                                                     5000,
-                                                                     30000,
-                                                                     ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS);
+
+            backupConnectorParams = backupConnector.getParams();
          }
       }
       remotingService.setMessagingServer(this);
@@ -305,7 +305,7 @@
 
          clusterManager.start();
       }
-      
+
       log.info("Started messaging server");
 
       started = true;
@@ -589,7 +589,7 @@
    {
       sessions.remove(name);
    }
-   
+
    public List<ServerSession> getSessions(final String connectionID)
    {
       Set<Entry<String, ServerSession>> sessionEntries = sessions.entrySet();
@@ -613,16 +613,27 @@
       // need to preserve channel ids
       // before and after failover
 
-      if (this.replicatingConnectionManager != null)
+      if (backupConnectorFactory != null)
       {
-         RemotingConnection replicatingConnection = replicatingConnectionManager.createConnection();
+         NoCacheConnectionLifeCycleListener listener = new NoCacheConnectionLifeCycleListener();
+         RemotingConnectionImpl replicatingConnection = (RemotingConnectionImpl)RemotingConnectionImpl.createConnection(backupConnectorFactory,
+                                                                                                                        backupConnectorParams,
+                                                                                                                        30000,
+                                                                                                                        5000,
+                                                                                                                        this.scheduledExecutor,
+                                                                                                                        listener);
 
+         listener.conn = replicatingConnection;
+
+         replicatingConnection.startPinger();
+
          return replicatingConnection;
       }
       else
       {
          return null;
       }
+
    }
 
    public MessagingServerControlMBean getServerManagement()
@@ -770,4 +781,30 @@
          }
       }
    }
+
+   private static class NoCacheConnectionLifeCycleListener implements ConnectionLifeCycleListener
+   {
+      private RemotingConnection conn;
+
+      public void connectionCreated(final Connection connection)
+      {
+      }
+
+      public void connectionDestroyed(final Object connectionID)
+      {
+         if (conn != null)
+         {
+            conn.destroy();
+         }
+      }
+
+      public void connectionException(final Object connectionID, final MessagingException me)
+      {
+         if (conn != null)
+         {
+            conn.fail(me);
+         }
+      }
+   }
+
 }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/QueueImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -119,7 +119,7 @@
       this.clustered = clustered;
 
       this.durable = durable;
-                                                                                    
+
       this.temporary = temporary;
 
       this.postOffice = postOffice;
@@ -140,7 +140,7 @@
 
    // Queue implementation
    // -------------------------------------------------------------------
-  
+
    public boolean isClustered()
    {
       return clustered;
@@ -187,7 +187,7 @@
          {
             messageReferences.addFirst(ref, msg.getPriority());
          }
-         if(ref.getMessage().getExpiration() != 0)
+         if (ref.getMessage().getExpiration() != 0)
          {
             expiringMessageReferences.addIfAbsent(ref);
          }
@@ -284,10 +284,10 @@
             break;
          }
       }
-      
+
       if (removed == null)
       {
-         //Look in scheduled deliveries
+         // Look in scheduled deliveries
          removed = scheduledDeliveryHandler.removeReferenceWithID(id);
       }
 
@@ -370,11 +370,9 @@
       return deliveringCount.get();
    }
 
-   public void referenceAcknowledged(MessageReference ref) throws Exception
+   public void referenceAcknowledged(final MessageReference ref) throws Exception
    {
-
       referenceRemoved(ref);
-
    }
 
    public void referenceCancelled()
@@ -471,9 +469,9 @@
    }
 
    public synchronized boolean expireMessage(final long messageID,
-                                final StorageManager storageManager,
-                                final PostOffice postOffice,
-                                final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
+                                             final StorageManager storageManager,
+                                             final PostOffice postOffice,
+                                             final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       Iterator<MessageReference> iter = messageReferences.iterator();
 
@@ -519,10 +517,11 @@
    }
    
    public void expireMessages(final StorageManager storageManager,
-                                final PostOffice postOffice,
-                                final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
+                              final PostOffice postOffice,
+                              final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       List<MessageReference> refs = new ArrayList<MessageReference>();
+
       for (MessageReference expiringMessageReference : expiringMessageReferences)
       {
          if (expiringMessageReference.getMessage().isExpired())
@@ -532,7 +531,7 @@
       }
       for (MessageReference ref : refs)
       {
-         if(expiringMessageReferences.remove(ref))
+         if (expiringMessageReferences.remove(ref))
          {
             expireMessage(ref.getMessage().getMessageID(), storageManager, postOffice, queueSettingsRepository);
          }
@@ -540,9 +539,9 @@
    }
 
    public boolean sendMessageToDeadLetterAddress(final long messageID,
-                                   final StorageManager storageManager,
-                                   final PostOffice postOffice,
-                                   final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
+                                                 final StorageManager storageManager,
+                                                 final PostOffice postOffice,
+                                                 final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       Iterator<MessageReference> iter = messageReferences.iterator();
 
@@ -681,7 +680,7 @@
                   " so queue will be activated now");
 
          backup = false;
-         
+
          scheduledDeliveryHandler.reSchedule();
 
          deliverAsync(executor);
@@ -855,7 +854,7 @@
 
       if (add)
       {
-         if(ref.getMessage().getExpiration() != 0)
+         if (ref.getMessage().getExpiration() != 0)
          {
             expiringMessageReferences.addIfAbsent(ref);
          }
@@ -905,9 +904,9 @@
     * @param ref
     * @throws Exception
     */
-   private void referenceRemoved(MessageReference ref) throws Exception
+   private void referenceRemoved(final MessageReference ref) throws Exception
    {
-      if(ref.getMessage().getExpiration() > 0)
+      if (ref.getMessage().getExpiration() > 0)
       {
          expiringMessageReferences.remove(ref);
       }

Modified: trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/core/server/impl/ServerSessionImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -112,10 +112,10 @@
 
    // Static -------------------------------------------------------------------------------
 
-   public static void moveReferencesBackToHeadOfQueues(List<MessageReference> references,
-                                                       PostOffice postOffice,
-                                                       StorageManager storageManager,
-                                                       HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
+   public static void moveReferencesBackToHeadOfQueues(final List<MessageReference> references,
+                                                       final PostOffice postOffice,
+                                                       final StorageManager storageManager,
+                                                       final HierarchicalRepository<QueueSettings> queueSettingsRepository) throws Exception
    {
       Map<Queue, LinkedList<MessageReference>> queueMap = new HashMap<Queue, LinkedList<MessageReference>>();
 
@@ -245,7 +245,7 @@
 
       this.postOffice = postOffice;
 
-      this.pager = postOffice.getPagingManager();
+      pager = postOffice.getPagingManager();
 
       this.queueSettingsRepository = queueSettingsRepository;
 
@@ -403,7 +403,7 @@
                                                           storageManager,
                                                           queueSettingsRepository,
                                                           postOffice,
-                                                          channel,                                                         
+                                                          channel,
                                                           preAcknowledge);
 
          consumers.put(consumer.getID(), consumer);
@@ -1939,7 +1939,7 @@
 
    public void handleStart(final Packet packet)
    {
-      boolean lock = this.channel.getReplicatingChannel() != null;
+      boolean lock = channel.getReplicatingChannel() != null;
 
       if (lock)
       {
@@ -2180,11 +2180,11 @@
          if (!packet.isContinues())
          {
             final ServerLargeMessage message = largeMessage;
-            
+
             largeMessage = null;
 
             message.complete();
-            
+
             send(message);
          }
 
@@ -2418,7 +2418,7 @@
    // Private
    // ----------------------------------------------------------------------------
 
-   private ServerLargeMessage createLargeMessageStorage(long messageID, byte[] header) throws Exception
+   private ServerLargeMessage createLargeMessageStorage(final long messageID, final byte[] header) throws Exception
    {
       ServerLargeMessage largeMessage = storageManager.createLargeMessage();
 
@@ -2498,9 +2498,9 @@
                storageManager.storeMessage(msg);
             }
 
-            //TODO - this code is also duplicated in transactionimpl and in depaging
-            //it should all be centralised
-            
+            // TODO - this code is also duplicated in transactionimpl and in depaging
+            // it should all be centralised
+
             for (MessageReference ref : refs)
             {
                if (scheduledDeliveryTime != null)
@@ -2538,5 +2538,4 @@
          throw e;
       }
    }
-
 }

Modified: trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/client/JBossConnectionFactory.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -15,6 +15,8 @@
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
 
 import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
 
 import javax.jms.Connection;
 import javax.jms.ConnectionFactory;
@@ -34,12 +36,15 @@
 
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.ConnectionLoadBalancingPolicy;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.jms.referenceable.ConnectionFactoryObjectFactory;
 import org.jboss.messaging.jms.referenceable.SerializableObjectRefAddr;
+import org.jboss.messaging.util.Pair;
 
 /**
  * @author <a href="mailto:ovidiu at feodorov.com">Ovidiu Feodorov</a>
@@ -64,10 +69,18 @@
 
    private transient volatile ClientSessionFactory sessionFactory;
 
-   private final TransportConfiguration connectorConfig;
+   private final String connectionLoadBalancingPolicyClassName;
 
-   private final TransportConfiguration backupConnectorConfig;
+   private final List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs;
 
+   private final String discoveryGroupAddress;
+
+   private final int discoveryGroupPort;
+
+   private final long discoveryRefreshTimeout;
+
+   private final long discoveryInitialWaitTimeout;
+
    private final String clientID;
 
    private final int dupsOKBatchSize;
@@ -85,7 +98,7 @@
    private final int sendWindowSize;
 
    private final int producerMaxRate;
-   
+
    private final int minLargeMessageSize;
 
    private final boolean blockOnAcknowledge;
@@ -102,8 +115,11 @@
 
    // Constructors ---------------------------------------------------------------------------------
 
-   public JBossConnectionFactory(final TransportConfiguration connectorConfig,
-                                 final TransportConfiguration backupConnectorConfig,
+   public JBossConnectionFactory(final String discoveryGroupAddress,
+                                 final int discoveryGroupPort,
+                                 final long discoveryRefreshTimeout,
+                                 final long discoveryInitialWaitTimeout,
+                                 final String loadBalancingPolicyClassName,
                                  final long pingPeriod,
                                  final long callTimeout,
                                  final String clientID,
@@ -121,8 +137,12 @@
                                  final int maxConnections,
                                  final boolean preAcknowledge)
    {
-      this.connectorConfig = connectorConfig;
-      this.backupConnectorConfig = backupConnectorConfig;
+      this.connectorConfigs = null;
+      this.discoveryGroupAddress = discoveryGroupAddress;
+      this.discoveryGroupPort = discoveryGroupPort;
+      this.discoveryRefreshTimeout = discoveryRefreshTimeout;
+      this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout;
+      this.connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName;
       this.clientID = clientID;
       this.dupsOKBatchSize = dupsOKBatchSize;
       this.transactionBatchSize = transactionBatchSize;
@@ -141,6 +161,189 @@
       this.preAcknowledge = preAcknowledge;
    }
 
+   public JBossConnectionFactory(final String discoveryGroupAddress,
+                                 final int discoveryGroupPort,
+                                 final long discoveryRefreshTimeout,
+                                 final long discoveryInitialWaitTimeout)
+   {
+      this.connectorConfigs = null;
+      this.discoveryGroupAddress = discoveryGroupAddress;
+      this.discoveryGroupPort = discoveryGroupPort;
+      this.discoveryRefreshTimeout = discoveryRefreshTimeout;
+      this.discoveryInitialWaitTimeout = discoveryInitialWaitTimeout;
+      this.connectionLoadBalancingPolicyClassName = ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
+      this.clientID = null;
+      this.dupsOKBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.transactionBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;
+      this.callTimeout = ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT;
+      this.consumerMaxRate = ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
+      this.consumerWindowSize = ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE;
+      this.producerMaxRate = ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
+      this.sendWindowSize = ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE;
+      this.blockOnAcknowledge = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
+      this.minLargeMessageSize = ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
+      this.blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+      this.blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
+      this.autoGroup = ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP;
+      this.maxConnections = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
+      this.preAcknowledge = ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
+   }
+
+   public JBossConnectionFactory(final String discoveryGroupName, final int discoveryGroupPort)
+   {
+      this(discoveryGroupName,
+           discoveryGroupPort,
+           ConfigurationImpl.DEFAULT_BROADCAST_REFRESH_TIMEOUT,
+           ClientSessionFactoryImpl.DEFAULT_DISCOVERY_INITIAL_WAIT);
+   }
+   
+   public JBossConnectionFactory(final List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs,
+                                 final String loadBalancingPolicyClassName,
+                                 final long pingPeriod,
+                                 final long callTimeout,
+                                 final String clientID,
+                                 final int dupsOKBatchSize,
+                                 final int transactionBatchSize,
+                                 final int consumerWindowSize,
+                                 final int consumerMaxRate,
+                                 final int sendWindowSize,
+                                 final int producerMaxRate,
+                                 final int minLargeMessageSize,
+                                 final boolean blockOnAcknowledge,
+                                 final boolean blockOnNonPersistentSend,
+                                 final boolean blockOnPersistentSend,
+                                 final boolean autoGroup,
+                                 final int maxConnections,
+                                 final boolean preAcknowledge)
+   {
+      this.discoveryGroupAddress = null;
+      this.discoveryGroupPort = -1;
+      this.discoveryRefreshTimeout = -1;
+      this.discoveryInitialWaitTimeout = -1;
+      this.connectorConfigs = connectorConfigs;
+      this.connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName;
+      this.clientID = clientID;
+      this.dupsOKBatchSize = dupsOKBatchSize;
+      this.transactionBatchSize = transactionBatchSize;
+      this.pingPeriod = pingPeriod;
+      this.callTimeout = callTimeout;
+      this.consumerMaxRate = consumerMaxRate;
+      this.consumerWindowSize = consumerWindowSize;
+      this.producerMaxRate = producerMaxRate;
+      this.sendWindowSize = sendWindowSize;
+      this.blockOnAcknowledge = blockOnAcknowledge;
+      this.minLargeMessageSize = minLargeMessageSize;
+      this.blockOnNonPersistentSend = blockOnNonPersistentSend;
+      this.blockOnPersistentSend = blockOnPersistentSend;
+      this.autoGroup = autoGroup;
+      this.maxConnections = maxConnections;
+      this.preAcknowledge = preAcknowledge;
+   }
+   
+   public JBossConnectionFactory(final TransportConfiguration transportConfig,
+                                 final TransportConfiguration backupConfig,
+                                 final String loadBalancingPolicyClassName,
+                                 final long pingPeriod,
+                                 final long callTimeout,
+                                 final String clientID,
+                                 final int dupsOKBatchSize,
+                                 final int transactionBatchSize,
+                                 final int consumerWindowSize,
+                                 final int consumerMaxRate,
+                                 final int sendWindowSize,
+                                 final int producerMaxRate,
+                                 final int minLargeMessageSize,
+                                 final boolean blockOnAcknowledge,
+                                 final boolean blockOnNonPersistentSend,
+                                 final boolean blockOnPersistentSend,
+                                 final boolean autoGroup,
+                                 final int maxConnections,
+                                 final boolean preAcknowledge)
+   {
+      this.discoveryGroupAddress = null;
+      this.discoveryGroupPort = -1;
+      this.discoveryRefreshTimeout = -1;
+      this.discoveryInitialWaitTimeout = -1;
+      List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+      connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(transportConfig, backupConfig));
+      this.connectorConfigs = connectorConfigs;
+      this.connectionLoadBalancingPolicyClassName = loadBalancingPolicyClassName;
+      this.clientID = null;
+      this.dupsOKBatchSize = dupsOKBatchSize;
+      this.transactionBatchSize = transactionBatchSize;
+      this.pingPeriod = pingPeriod;
+      this.callTimeout = callTimeout;
+      this.consumerMaxRate = consumerMaxRate;
+      this.consumerWindowSize = consumerWindowSize;
+      this.producerMaxRate = producerMaxRate;
+      this.sendWindowSize = sendWindowSize;
+      this.blockOnAcknowledge = blockOnAcknowledge;
+      this.minLargeMessageSize = minLargeMessageSize;
+      this.blockOnNonPersistentSend = blockOnNonPersistentSend;
+      this.blockOnPersistentSend = blockOnPersistentSend;
+      this.autoGroup = autoGroup;
+      this.maxConnections = maxConnections;
+      this.preAcknowledge = preAcknowledge;
+   }
+
+
+   public JBossConnectionFactory(final List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs)
+   {
+      this.discoveryGroupAddress = null;
+      this.discoveryGroupPort = -1;
+      this.discoveryRefreshTimeout = -1;
+      this.discoveryInitialWaitTimeout = -1;
+      this.connectorConfigs = connectorConfigs;
+      this.connectionLoadBalancingPolicyClassName = ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
+      this.clientID = null;
+      this.dupsOKBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.transactionBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;
+      this.callTimeout = ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT;
+      this.consumerMaxRate = ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
+      this.consumerWindowSize = ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE;
+      this.producerMaxRate = ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
+      this.sendWindowSize = ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE;
+      this.blockOnAcknowledge = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
+      this.minLargeMessageSize = ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
+      this.blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+      this.blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
+      this.autoGroup = ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP;
+      this.maxConnections = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
+      this.preAcknowledge = ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
+   }
+   
+   public JBossConnectionFactory(final TransportConfiguration connectorConfig)
+   {
+      this.discoveryGroupAddress = null;
+      this.discoveryGroupPort = -1;
+      this.discoveryRefreshTimeout = -1;
+      this.discoveryInitialWaitTimeout = -1;
+      List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+      Pair<TransportConfiguration, TransportConfiguration> pair = new Pair<TransportConfiguration, TransportConfiguration>(connectorConfig,
+                                                                                                                           null);
+      connectorConfigs.add(pair);
+      this.connectorConfigs = connectorConfigs;
+      this.connectionLoadBalancingPolicyClassName = ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
+      this.clientID = null;
+      this.dupsOKBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.transactionBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
+      this.pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;
+      this.callTimeout = ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT;
+      this.consumerMaxRate = ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
+      this.consumerWindowSize = ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE;
+      this.producerMaxRate = ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
+      this.sendWindowSize = ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE;
+      this.blockOnAcknowledge = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
+      this.minLargeMessageSize = ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
+      this.blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
+      this.blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
+      this.autoGroup = ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP;
+      this.maxConnections = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
+      this.preAcknowledge = ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
+   }
+
    // ConnectionFactory implementation -------------------------------------------------------------
 
    public Connection createConnection() throws JMSException
@@ -225,11 +428,6 @@
 
    // Public ---------------------------------------------------------------------------------------
 
-   public TransportConfiguration getConnectorFactory()
-   {
-      return connectorConfig;
-   }
-
    public long getPingPeriod()
    {
       return pingPeriod;
@@ -298,27 +496,59 @@
                                                                    final String password,
                                                                    final boolean isXA,
                                                                    final int type) throws JMSException
-   {     
-      if (sessionFactory == null)
+   {
+      try
       {
-         sessionFactory = new ClientSessionFactoryImpl(connectorConfig,
-                                                       backupConnectorConfig,
-                                                       pingPeriod,
-                                                       callTimeout,
-                                                       consumerWindowSize,
-                                                       consumerMaxRate,
-                                                       sendWindowSize,
-                                                       producerMaxRate,
-                                                       minLargeMessageSize,
-                                                       blockOnAcknowledge,
-                                                       blockOnNonPersistentSend,
-                                                       blockOnPersistentSend,
-                                                       autoGroup,
-                                                       maxConnections,
-                                                       preAcknowledge,
-                                                       DEFAULT_ACK_BATCH_SIZE);
-
+         if (sessionFactory == null)
+         {
+            if (connectorConfigs != null)
+            {
+               sessionFactory = new ClientSessionFactoryImpl(connectorConfigs,
+                                                             connectionLoadBalancingPolicyClassName,
+                                                             pingPeriod,
+                                                             callTimeout,
+                                                             consumerWindowSize,
+                                                             consumerMaxRate,
+                                                             sendWindowSize,
+                                                             producerMaxRate,
+                                                             minLargeMessageSize,
+                                                             blockOnAcknowledge,
+                                                             blockOnNonPersistentSend,
+                                                             blockOnPersistentSend,
+                                                             autoGroup,
+                                                             maxConnections,
+                                                             preAcknowledge,
+                                                             DEFAULT_ACK_BATCH_SIZE);
+            }
+            else
+            {
+               sessionFactory = new ClientSessionFactoryImpl(discoveryGroupAddress,
+                                                             discoveryGroupPort,
+                                                             discoveryRefreshTimeout,
+                                                             discoveryInitialWaitTimeout,
+                                                             connectionLoadBalancingPolicyClassName,
+                                                             pingPeriod,
+                                                             callTimeout,
+                                                             consumerWindowSize,
+                                                             consumerMaxRate,
+                                                             sendWindowSize,
+                                                             producerMaxRate,
+                                                             minLargeMessageSize,
+                                                             blockOnAcknowledge,
+                                                             blockOnNonPersistentSend,
+                                                             blockOnPersistentSend,
+                                                             autoGroup,
+                                                             maxConnections,
+                                                             preAcknowledge,
+                                                             DEFAULT_ACK_BATCH_SIZE);
+            }
+   
+         }
       }
+      catch (MessagingException me)
+      {
+         throw JMSExceptionHelper.convertFromMessagingException(me);
+      }
 
       if (username != null)
       {

Modified: trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/server/JMSServerManager.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,6 +25,8 @@
 import java.util.List;
 
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
+import org.jboss.messaging.util.Pair;
 
 /**
  * The JMS Management interface.
@@ -106,9 +108,9 @@
    boolean destroyTopic(String name) throws Exception;
 
    boolean createConnectionFactory(String name,
-                                   TransportConfiguration connectorConfig,
-                                   TransportConfiguration backupConnectorConfig,
-                                   long pingPeriod,                                
+                                   List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs,
+                                   String connectionLoadBalancingPolicyClassName,
+                                   long pingPeriod,
                                    long callTimeout,
                                    String clientID,
                                    int dupsOKBatchSize,
@@ -117,19 +119,20 @@
                                    int consumerMaxRate,
                                    int sendWindowSize,
                                    int producerMaxRate,
-                                   int minLargeMessageSize, 
+                                   int minLargeMessageSize,
                                    boolean blockOnAcknowledge,
                                    boolean blockOnNonPersistentSend,
                                    boolean blockOnPersistentSend,
                                    boolean autoGroup,
                                    int maxConnections,
                                    boolean preAcknowledge,
-                                   String jndiBinding) throws Exception;
-
+                                   List<String> jndiBindings) throws Exception;
+   
    boolean createConnectionFactory(String name,
-                                   TransportConfiguration connectorConfig,
-                                   TransportConfiguration backupConnectorConfig,
-                                   long pingPeriod,                              
+                                   DiscoveryGroupConfiguration discoveryGroupConfig,
+                                   long discoveryInitialWait,
+                                   String connectionLoadBalancingPolicyClassName,
+                                   long pingPeriod,
                                    long callTimeout,
                                    String clientID,
                                    int dupsOKBatchSize,
@@ -138,14 +141,14 @@
                                    int consumerMaxRate,
                                    int sendWindowSize,
                                    int producerMaxRate,
-                                   int minLargeMessageSize, 
+                                   int minLargeMessageSize,
                                    boolean blockOnAcknowledge,
                                    boolean blockOnNonPersistentSend,
                                    boolean blockOnPersistentSend,
-                                   boolean autoGroupId,
+                                   boolean autoGroup,
                                    int maxConnections,
                                    boolean preAcknowledge,
-                                   List<String> jndiBinding) throws Exception;
+                                   List<String> jndiBindings) throws Exception;
 
    /**
     * destroys a connection factory.

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerDeployer.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -18,10 +18,12 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
 import org.jboss.messaging.core.deployers.DeploymentManager;
 import org.jboss.messaging.core.deployers.impl.XmlDeployer;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.jms.server.JMSServerManager;
+import org.jboss.messaging.util.Pair;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
@@ -32,7 +34,7 @@
 public class JMSServerDeployer extends XmlDeployer
 {
    Logger log = Logger.getLogger(JMSServerDeployer.class);
-   
+
    private final Configuration configuration;
 
    private JMSServerManager jmsServerManager;
@@ -44,7 +46,7 @@
    private static final String CALL_TIMEOUT_ELEMENT = "call-timeout";
 
    private static final String DUPS_OK_BATCH_SIZE_ELEMENT = "dups-ok-batch-size";
-   
+
    private static final String TRANSACTION_BATCH_SIZE_ELEMENT = "transaction-batch-size";
 
    private static final String CONSUMER_WINDOW_SIZE_ELEMENT = "consumer-window-size";
@@ -54,9 +56,9 @@
    private static final String SEND_WINDOW_SIZE = "send-window-size";
 
    private static final String PRODUCER_MAX_RATE_ELEMENT = "producer-max-rate";
-   
+
    private static final String BIG_MESSAGE_ELEMENT = "big-message-size";
-   
+
    private static final String BLOCK_ON_ACKNOWLEDGE_ELEMENT = "block-on-acknowledge";
 
    private static final String SEND_NP_MESSAGES_SYNCHRONOUSLY_ELEMENT = "send-np-messages-synchronously";
@@ -64,14 +66,14 @@
    private static final String SEND_P_MESSAGES_SYNCHRONOUSLY_ELEMENT = "send-p-messages-synchronously";
 
    private static final String AUTO_GROUP_ID_ELEMENT = "auto-group-id";
-   
+
    private static final String MAX_CONNECTIONS_ELEMENT = "max-connections";
 
    private static final String PRE_ACKNOWLEDGE_ELEMENT = "pre-acknowledge";
 
    private static final String CONNECTOR_LINK_ELEMENT = "connector-ref";
 
-   private static final String BACKUP_CONNECTOR_ELEMENT = "backup-connector";
+   private static final String DISCOVERY_GROUP_ELEMENT = "discovery-group-ref";
 
    private static final String ENTRY_NODE_NAME = "entry";
 
@@ -80,11 +82,15 @@
    private static final String QUEUE_NODE_NAME = "queue";
 
    private static final String TOPIC_NODE_NAME = "topic";
+   
+   private static final String CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME_ELEMENT = "connection-load-balancing-policy-class-name";
+   
+   private static final String DISCOVERY_INITIAL_WAIT_ELEMENT = "discovery-initial-wait";
 
    public JMSServerDeployer(final DeploymentManager deploymentManager, final Configuration config)
    {
       super(deploymentManager);
-      
+
       this.configuration = config;
    }
 
@@ -128,7 +134,7 @@
       {
          NodeList children = node.getChildNodes();
 
-         long pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;     
+         long pingPeriod = ClientSessionFactoryImpl.DEFAULT_PING_PERIOD;
          long callTimeout = ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT;
          String clientID = null;
          int dupsOKBatchSize = ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
@@ -137,7 +143,7 @@
          int consumerMaxRate = ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
          int sendWindowSize = ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE;
          int producerMaxRate = ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
-         int minLargeMessageSize = ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE;
+         int minLargeMessageSize = ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
          boolean blockOnAcknowledge = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
          boolean blockOnNonPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
          boolean blockOnPersistentSend = ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
@@ -145,15 +151,17 @@
          int maxConnections = ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
          boolean preAcknowledge = ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
          List<String> jndiBindings = new ArrayList<String>();
-         String connectorName = null;
-         String backupConnectorName = null;
-
+         List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+         DiscoveryGroupConfiguration discoveryGroupConfiguration = null;
+         String connectionLoadBalancingPolicyClassName = ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
+         long discoveryInitialWait = ClientSessionFactoryImpl.DEFAULT_DISCOVERY_INITIAL_WAIT;
+         
          for (int j = 0; j < children.getLength(); j++)
          {
             Node child = children.item(j);
-            
+
             String childText = child.getTextContent().trim();
-            
+
             if (PING_PERIOD_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
                pingPeriod = Long.parseLong(childText);
@@ -180,7 +188,7 @@
             }
             else if (BIG_MESSAGE_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
-               minLargeMessageSize  = Integer.parseInt(childText);
+               minLargeMessageSize = Integer.parseInt(childText);
             }
             else if (CLIENTID_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
@@ -206,15 +214,15 @@
             {
                blockOnPersistentSend = Boolean.parseBoolean(childText);
             }
-            else if(AUTO_GROUP_ID_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            else if (AUTO_GROUP_ID_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
                autoGroup = Boolean.parseBoolean(childText);
             }
-            else if(MAX_CONNECTIONS_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            else if (MAX_CONNECTIONS_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
                maxConnections = Integer.parseInt(childText);
             }
-            else if(PRE_ACKNOWLEDGE_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            else if (PRE_ACKNOWLEDGE_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
                preAcknowledge = Boolean.parseBoolean(childText);;
             }
@@ -225,64 +233,109 @@
             }
             else if (CONNECTOR_LINK_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
-               connectorName = child.getAttributes().getNamedItem("connector-name").getNodeValue();
+               String connectorName = child.getAttributes().getNamedItem("connector-name").getNodeValue();
+
+               TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName);
+               
+               if (connector == null)
+               {
+                  log.warn("There is no connector with name '" + connectorName + "' deployed.");
+
+                  return;
+               }
+               
+               TransportConfiguration backupConnector = null;
+
+               Node backupNode = child.getAttributes().getNamedItem("backup-connector-name");
+
+               if (backupNode != null)
+               {
+                  String backupConnectorName = node.getNodeValue();
+                  
+                  backupConnector = configuration.getConnectorConfigurations().get(backupConnectorName);
+                  
+                  if (backupConnector == null)
+                  {
+                     log.warn("There is no backup connector with name '" + connectorName + "' deployed.");
+
+                     return;
+                  }                  
+               }
+               
+               connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(connector, backupConnector));
             }
-            else if (BACKUP_CONNECTOR_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            else if (DISCOVERY_GROUP_ELEMENT.equalsIgnoreCase(child.getNodeName()))
             {
-               backupConnectorName = child.getAttributes().getNamedItem("connector-name").getNodeValue();
+               String discoveryGroupName = child.getAttributes().getNamedItem("discovery-group-name").getNodeValue();
+               
+               discoveryGroupConfiguration = configuration.getDiscoveryGroupConfigurations().get(discoveryGroupName);
+               
+               if (discoveryGroupConfiguration == null)
+               {
+                  log.warn("There is no discovery group with name '" + discoveryGroupName + "' deployed.");
+
+                  return;
+               } 
             }
+            else if (CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            {
+               connectionLoadBalancingPolicyClassName = child.getTextContent().trim();
+            }
+            else if (DISCOVERY_INITIAL_WAIT_ELEMENT.equalsIgnoreCase(child.getNodeName()))
+            {
+               discoveryInitialWait = Integer.parseInt(child.getTextContent().trim());
+            }
          }
+         
+         String name = node.getAttributes().getNamedItem(getKeyAttribute()).getNodeValue();
 
-         if (connectorName == null)
+         if (discoveryGroupConfiguration != null)
          {
-            throw new IllegalArgumentException("connector must be specified in configuration");
+            jmsServerManager.createConnectionFactory(name,
+                                                     discoveryGroupConfiguration,
+                                                     discoveryInitialWait,
+                                                     connectionLoadBalancingPolicyClassName,
+                                                     pingPeriod,
+                                                     callTimeout,
+                                                     clientID,
+                                                     dupsOKBatchSize,
+                                                     transactionBatchSize,
+                                                     consumerWindowSize,
+                                                     consumerMaxRate,
+                                                     sendWindowSize,
+                                                     producerMaxRate,
+                                                     minLargeMessageSize,
+                                                     blockOnAcknowledge,
+                                                     blockOnNonPersistentSend,
+                                                     blockOnPersistentSend,
+                                                     autoGroup,
+                                                     maxConnections,
+                                                     preAcknowledge,
+                                                     jndiBindings);
          }
-         
-         TransportConfiguration connector = configuration.getConnectorConfigurations().get(connectorName);
-         
-         if (connector == null)
+         else
          {
-            log.warn("There is no connector with name '" + connectorName + "' deployed.");
-            
-            return;
+            jmsServerManager.createConnectionFactory(name,
+                                                     connectorConfigs,
+                                                     connectionLoadBalancingPolicyClassName,
+                                                     pingPeriod,
+                                                     callTimeout,
+                                                     clientID,
+                                                     dupsOKBatchSize,
+                                                     transactionBatchSize,
+                                                     consumerWindowSize,
+                                                     consumerMaxRate,
+                                                     sendWindowSize,
+                                                     producerMaxRate,
+                                                     minLargeMessageSize,
+                                                     blockOnAcknowledge,
+                                                     blockOnNonPersistentSend,
+                                                     blockOnPersistentSend,
+                                                     autoGroup,
+                                                     maxConnections,
+                                                     preAcknowledge,
+                                                     jndiBindings);
          }
-         
-         TransportConfiguration backupConnector = null;
-         
-         if (backupConnectorName != null)
-         {
-            backupConnector = configuration.getConnectorConfigurations().get(backupConnectorName);
-            
-            if (backupConnector == null)
-            {
-               log.warn("There is no connector with name '" + connectorName + "' deployed.");
-               
-               return;
-            }
-         }
-         
-         String name = node.getAttributes().getNamedItem(getKeyAttribute()).getNodeValue();
-
-         jmsServerManager.createConnectionFactory(name,
-                                                  connector,
-                                                  backupConnector,
-                                                  pingPeriod,                                      
-                                                  callTimeout,
-                                                  clientID,
-                                                  dupsOKBatchSize,
-                                                  transactionBatchSize,
-                                                  consumerWindowSize,
-                                                  consumerMaxRate,
-                                                  sendWindowSize,
-                                                  producerMaxRate,
-                                                  minLargeMessageSize,
-                                                  blockOnAcknowledge,
-                                                  blockOnNonPersistentSend,
-                                                  blockOnPersistentSend,
-                                                  autoGroup,
-                                                  maxConnections,
-                                                  preAcknowledge,
-                                                  jndiBindings);
       }
       else if (node.getNodeName().equals(QUEUE_NODE_NAME))
       {
@@ -297,7 +350,6 @@
                String jndiName = child.getAttributes().getNamedItem("name").getNodeValue();
                jmsServerManager.createQueue(queueName, jndiName);
             }
-
          }
       }
       else if (node.getNodeName().equals(TOPIC_NODE_NAME))

Modified: trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/server/impl/JMSServerManagerImpl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -32,8 +32,8 @@
 import javax.naming.InitialContext;
 import javax.naming.NamingException;
 
-import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.management.MessagingServerControlMBean;
 import org.jboss.messaging.core.management.impl.MessagingServerControl;
@@ -51,6 +51,7 @@
 import org.jboss.messaging.jms.server.management.JMSManagementService;
 import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
 import org.jboss.messaging.util.JNDIUtil;
+import org.jboss.messaging.util.Pair;
 
 /**
  * A Deployer used to create and add to JNDI queues, topics and connection
@@ -84,14 +85,23 @@
 
    private final JMSManagementService managementService;
 
-   public static JMSServerManagerImpl newJMSServerManagerImpl(MessagingServer server) throws Exception
+   public static JMSServerManagerImpl newJMSServerManagerImpl(final MessagingServer server) throws Exception
    {
-      MessagingServerControlMBean control = new MessagingServerControl(server.getPostOffice(), server.getStorageManager(), server.getConfiguration(),
-                                                                       server.getQueueSettingsRepository(), server.getResourceManager(), 
-                                                                       server.getRemotingService(), server, new MessageCounterManagerImpl(1000), new NotificationBroadcasterSupport());
+      MessagingServerControlMBean control = new MessagingServerControl(server.getPostOffice(),
+                                                                       server.getStorageManager(),
+                                                                       server.getConfiguration(),
+                                                                       server.getQueueSettingsRepository(),
+                                                                       server.getResourceManager(),
+                                                                       server.getRemotingService(),
+                                                                       server,
+                                                                       new MessageCounterManagerImpl(1000),
+                                                                       new NotificationBroadcasterSupport());
       JMSManagementService jmsManagementService = new JMSManagementServiceImpl(server.getManagementService());
-      return new JMSServerManagerImpl(control, server.getPostOffice(), server.getStorageManager(),
-                                      server.getQueueSettingsRepository(), jmsManagementService);
+      return new JMSServerManagerImpl(control,
+                                      server.getPostOffice(),
+                                      server.getStorageManager(),
+                                      server.getQueueSettingsRepository(),
+                                      jmsManagementService);
    }
 
    public JMSServerManagerImpl(final MessagingServerControlMBean server,
@@ -100,7 +110,7 @@
                                final HierarchicalRepository<QueueSettings> queueSettingsRepository,
                                final JMSManagementService managementService)
    {
-      this.messagingServer = server;
+      messagingServer = server;
       this.postOffice = postOffice;
       this.storageManager = storageManager;
       this.queueSettingsRepository = queueSettingsRepository;
@@ -165,7 +175,7 @@
       return added;
    }
 
-   public boolean undeployDestination(String name) throws Exception
+   public boolean undeployDestination(final String name) throws Exception
    {
       List<String> jndiBindings = destinations.get(name);
       if (jndiBindings == null || jndiBindings.size() == 0)
@@ -202,78 +212,85 @@
       return true;
    }
 
-   public boolean createConnectionFactory(String name,
-                                          TransportConfiguration connectorConfig,
-                                          TransportConfiguration backupConnectorConfig,
-                                          long pingPeriod,
-                                          long callTimeout,
-                                          String clientID,
-                                          int dupsOKBatchSize,
-                                          int transactionBatchSize,
-                                          int consumerWindowSize,
-                                          int consumerMaxRate,
-                                          int sendWindowSize,
-                                          int producerMaxRate,
-                                          int minLargeMessageSize,
-                                          boolean blockOnAcknowledge,
-                                          boolean blockOnNonPersistentSend,
-                                          boolean blockOnPersistentSend,
-                                          boolean autoGroup,
-                                          int maxConnections,
-                                          boolean preAcknowledge,
-                                          String jndiBinding) throws Exception
+   public boolean createConnectionFactory(final String name,
+                                          final List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs,
+                                          final String connectionLoadBalancingPolicyClassName,
+                                          final long pingPeriod,
+                                          final long callTimeout,
+                                          final String clientID,
+                                          final int dupsOKBatchSize,
+                                          final int transactionBatchSize,
+                                          final int consumerWindowSize,
+                                          final int consumerMaxRate,
+                                          final int sendWindowSize,
+                                          final int producerMaxRate,
+                                          final int minLargeMessageSize,
+                                          final boolean blockOnAcknowledge,
+                                          final boolean blockOnNonPersistentSend,
+                                          final boolean blockOnPersistentSend,
+                                          final boolean autoGroup,
+                                          final int maxConnections,
+                                          final boolean preAcknowledge,
+                                          final List<String> jndiBindings) throws Exception
    {
-      ArrayList<String> bindings = new ArrayList<String>(1);
-      bindings.add(jndiBinding);
+      JBossConnectionFactory cf = connectionFactories.get(name);
+      if (cf == null)
+      {
+         cf = new JBossConnectionFactory(connectorConfigs,
+                                         connectionLoadBalancingPolicyClassName,
+                                         pingPeriod,
+                                         callTimeout,
+                                         clientID,
+                                         dupsOKBatchSize,
+                                         transactionBatchSize,
+                                         consumerWindowSize,
+                                         consumerMaxRate,
+                                         sendWindowSize,
+                                         producerMaxRate,
+                                         minLargeMessageSize,
+                                         blockOnAcknowledge,
+                                         blockOnNonPersistentSend,
+                                         blockOnPersistentSend,
+                                         autoGroup,
+                                         maxConnections,
+                                         preAcknowledge);
+      }
 
-      return createConnectionFactory(name,
-                                     connectorConfig,
-                                     backupConnectorConfig,
-                                     pingPeriod,
-                                     callTimeout,
-                                     clientID,
-                                     dupsOKBatchSize,
-                                     transactionBatchSize,
-                                     consumerWindowSize,
-                                     consumerMaxRate,
-                                     sendWindowSize,
-                                     producerMaxRate,
-                                     minLargeMessageSize,
-                                     blockOnAcknowledge,
-                                     blockOnNonPersistentSend,
-                                     blockOnPersistentSend,
-                                     autoGroup,
-                                     maxConnections,
-                                     preAcknowledge,
-                                     bindings);
+      bindConnectionFactory(cf, name, jndiBindings);
+
+      return true;
    }
 
-   public boolean createConnectionFactory(String name,
-                                          TransportConfiguration connectorConfig,
-                                          TransportConfiguration backupConnectorConfig,
-                                          long pingPeriod,
-                                          long callTimeout,
-                                          String clientID,
-                                          int dupsOKBatchSize,
-                                          int transactionBatchSize,
-                                          int consumerWindowSize,
-                                          int consumerMaxRate,
-                                          int sendWindowSize,
-                                          int producerMaxRate,
-                                          int minLargeMessageSize,
-                                          boolean blockOnAcknowledge,
-                                          boolean blockOnNonPersistentSend,
-                                          boolean blockOnPersistentSend,
-                                          boolean autoGroup,
-                                          int maxConnections,
-                                          boolean preAcknowledge,
-                                          List<String> jndiBindings) throws Exception
+   public boolean createConnectionFactory(final String name,
+                                          final DiscoveryGroupConfiguration discoveryGroupConfig,
+                                          final long discoveryInitialWait,
+                                          final String connectionLoadBalancingPolicyClassName,
+                                          final long pingPeriod,
+                                          final long callTimeout,
+                                          final String clientID,
+                                          final int dupsOKBatchSize,
+                                          final int transactionBatchSize,
+                                          final int consumerWindowSize,
+                                          final int consumerMaxRate,
+                                          final int sendWindowSize,
+                                          final int producerMaxRate,
+                                          final int minLargeMessageSize,
+                                          final boolean blockOnAcknowledge,
+                                          final boolean blockOnNonPersistentSend,
+                                          final boolean blockOnPersistentSend,
+                                          final boolean autoGroup,
+                                          final int maxConnections,
+                                          final boolean preAcknowledge,
+                                          final List<String> jndiBindings) throws Exception
    {
       JBossConnectionFactory cf = connectionFactories.get(name);
       if (cf == null)
       {
-         cf = new JBossConnectionFactory(connectorConfig,
-                                         backupConnectorConfig,
+         cf = new JBossConnectionFactory(discoveryGroupConfig.getGroupAddress(),
+                                         discoveryGroupConfig.getGroupPort(),
+                                         discoveryGroupConfig.getRefreshTimeout(),
+                                         discoveryInitialWait,
+                                         connectionLoadBalancingPolicyClassName,
                                          pingPeriod,
                                          callTimeout,
                                          clientID,
@@ -283,8 +300,7 @@
                                          consumerMaxRate,
                                          sendWindowSize,
                                          producerMaxRate,
-                                         minLargeMessageSize == -1 ? ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE
-                                                                  : minLargeMessageSize,
+                                         minLargeMessageSize,
                                          blockOnAcknowledge,
                                          blockOnNonPersistentSend,
                                          blockOnPersistentSend,
@@ -292,17 +308,8 @@
                                          maxConnections,
                                          preAcknowledge);
       }
-      for (String jndiBinding : jndiBindings)
-      {
-         bindToJndi(jndiBinding, cf);
-         if (connectionFactoryBindings.get(name) == null)
-         {
-            connectionFactoryBindings.put(name, new ArrayList<String>());
-         }
-         connectionFactoryBindings.get(name).add(jndiBinding);
-      }
 
-      managementService.registerConnectionFactory(name, cf, jndiBindings);
+      bindConnectionFactory(cf, name, jndiBindings);
 
       return true;
    }
@@ -340,12 +347,12 @@
    {
       return messagingServer.closeConnectionsForAddress(ipAddress);
    }
-   
+
    public String[] listConnectionIDs()
    {
       return messagingServer.listConnectionIDs();
    }
-   
+
    public String[] listSessions(final String connectionID)
    {
       return messagingServer.listSessions(connectionID);
@@ -360,6 +367,24 @@
 
    // Private -------------------------------------------------------
 
+   private void bindConnectionFactory(final JBossConnectionFactory cf,
+                                      final String name,
+                                      final List<String> jndiBindings) throws Exception
+   {
+      for (String jndiBinding : jndiBindings)
+      {
+         bindToJndi(jndiBinding, cf);
+
+         if (connectionFactoryBindings.get(name) == null)
+         {
+            connectionFactoryBindings.put(name, new ArrayList<String>());
+         }
+         connectionFactoryBindings.get(name).add(jndiBinding);
+      }
+
+      managementService.registerConnectionFactory(name, cf, jndiBindings);
+   }
+
    private boolean bindToJndi(final String jndiName, final Object objectToBind) throws NamingException
    {
       String parentContext;

Modified: trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/server/management/JMSServerControlMBean.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -25,9 +25,13 @@
 import static javax.management.MBeanOperationInfo.ACTION;
 import static javax.management.MBeanOperationInfo.INFO;
 
+import java.util.List;
+
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
 import org.jboss.messaging.core.management.Operation;
 import org.jboss.messaging.core.management.Parameter;
+import org.jboss.messaging.util.Pair;
 
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
@@ -63,13 +67,14 @@
    boolean destroyTopic(@Parameter(name = "name", desc = "Name of the topic to destroy")
    String name) throws Exception;
 
-   @Operation(desc = "Create a JMS ConnectionFactory", impact = ACTION)
+   
+   @Operation(desc = "Create a JMS ConnectionFactory with a static list of servers", impact = ACTION)
    void createConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to create")
                                 String name,
-                                @Parameter(name = "transportConfiguration", desc = "The remoting connector configuration")
-                                TransportConfiguration connectorConfig,
-                                @Parameter(name = "backupTransportConfiguration", desc = "The backup remoting connector configuration")
-                                TransportConfiguration backupConnectorConfig,
+                                @Parameter(name = "connectorConfigs", desc = "List of pairs of live configuration, backup configuration")
+                                List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs,
+                                @Parameter(name = "connectionLoadBalancingPolicyClassName", desc = "The name of the class to use for client side connection load-balancing")
+                                String connectionLoadBalancingPolicyClassName,
                                 @Parameter(name = "pingPeriod", desc = "The ping period in m")
                                 long pingPeriod,
                                 @Parameter(name = "callTimeout", desc = "The call timeout in m")
@@ -104,6 +109,50 @@
                                 boolean preAcknowledge,
                                 @Parameter(name = "jndiBinding", desc = "JNDI Binding")
                                 String jndiBinding) throws Exception;
+   
+   @Operation(desc = "Create a JMS ConnectionFactory specifying a discovery group to obtain list of servers from", impact = ACTION)
+   void createConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to create")
+                                String name,
+                                @Parameter(name = "discoveryGroupConfig", desc = "Discovery group configuration")
+                                DiscoveryGroupConfiguration discoveryGroupConfig,
+                                @Parameter(name = "discoveryInitialWait", desc = "The amount of time in ms to wait for initial discovery information to arrive at first using connection factory")
+                                long discoveryInitialWait,
+                                @Parameter(name = "connectionLoadBalancingPolicyClassName", desc = "The name of the class to use for client side connection load-balancing")
+                                String connectionLoadBalancingPolicyClassName,
+                                @Parameter(name = "pingPeriod", desc = "The ping period in m")
+                                long pingPeriod,
+                                @Parameter(name = "callTimeout", desc = "The call timeout in m")
+                                long callTimeout,
+                                @Parameter(name = "clientID", desc = "ClientID for created connections")
+                                String clientID,
+                                @Parameter(name = "dupsOKBatchSize", desc = "Size of the batch in bytes when using DUPS_OK")
+                                int dupsOKBatchSize,
+                                @Parameter(name = "transactionBatchSize", desc = "Size of the batch in bytes when using transacted session")
+                                int transactionBatchSize,
+                                @Parameter(name = "consumerWindowSize", desc = "Consumer's window size")
+                                int consumerWindowSize,
+                                @Parameter(name = "consumerMaxRate", desc = "Consumer's max rate")
+                                int consumerMaxRate,
+                                @Parameter(name = "producerWindowSize", desc = "Producer's window size")
+                                int producerWindowSize,
+                                @Parameter(name = "producerMaxRate", desc = "Producer's max rate")
+                                int producerMaxRate,
+                                @Parameter(name = "minLargeMessageSize", desc = "Size of what is considered a big message requiring sending in chunks") 
+                                int minLargeMessageSize, 
+                                @Parameter(name = "blockOnAcknowledge", desc = "Does acknowlegment block?")
+                                boolean blockOnAcknowledge,
+                                @Parameter(name = "blockOnNonPersistentSend", desc = "Does sending non persistent messages block?")
+                                boolean blockOnNonPersistentSend,
+                                @Parameter(name = "blockOnPersistentSend", desc = "Does sending persistent messages block?")
+                                boolean blockOnPersistentSend,
+                                @Parameter(name = "autoGroup", desc = "Any Messages sent via this factories connections will automatically set the property 'JBM_GroupID'")
+                                boolean autoGroup,
+                                @Parameter(name = "maxConnections", desc = "The maximum number of physical connections created per client using this connection factory. Sessions created will be assigned a connection in a round-robin fashion")
+                                int maxConnections,
+                                @Parameter(name = "preAcknowledge", desc = "If the server will acknowledge delivery of a message before it is delivered")
+                                boolean preAcknowledge,
+                                @Parameter(name = "jndiBinding", desc = "JNDI Binding")
+                                String jndiBinding) throws Exception;
 
    @Operation(desc = "Create a JMS ConnectionFactory", impact = ACTION)
    void destroyConnectionFactory(@Parameter(name = "name", desc = "Name of the ConnectionFactory to create")

Modified: trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java
===================================================================
--- trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/jms/server/management/impl/JMSServerControl.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -38,9 +38,11 @@
 import javax.management.StandardMBean;
 
 import org.jboss.messaging.core.config.TransportConfiguration;
+import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
 import org.jboss.messaging.core.management.impl.MBeanInfoHelper;
 import org.jboss.messaging.jms.server.JMSServerManager;
 import org.jboss.messaging.jms.server.management.JMSServerControlMBean;
+import org.jboss.messaging.util.Pair;
 
 /**
  * @author <a href="mailto:jmesnil at redhat.com">Jeff Mesnil</a>
@@ -77,8 +79,8 @@
    // JMSServerControlMBean implementation --------------------------
 
    public void createConnectionFactory(String name,
-                                       TransportConfiguration connectorConfig,
-                                       TransportConfiguration backupConnectorConfig,
+                                       List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs,
+                                       String connectionLoadBalancingPolicyClassName,
                                        long pingPeriod,                                  
                                        long callTimeout,
                                        String clientID,
@@ -101,8 +103,8 @@
       bindings.add(jndiBinding);
 
       boolean created = server.createConnectionFactory(name,
-                                                       connectorConfig,
-                                                       backupConnectorConfig,
+                                                       connectorConfigs,
+                                                       connectionLoadBalancingPolicyClassName,
                                                        pingPeriod,                                                    
                                                        callTimeout,
                                                        clientID,
@@ -119,13 +121,65 @@
                                                        autoGroup,
                                                        maxConnections,
                                                        preAcknowledge,
-                                                       jndiBinding);
+                                                       bindings);
       if (created)
       {
          sendNotification(NotificationType.CONNECTION_FACTORY_CREATED, name);
       }
    }
+   
+   public void createConnectionFactory(String name,
+                                       DiscoveryGroupConfiguration discoveryGroupConfig,
+                                       long discoveryInitialWait,
+                                       String connectionLoadBalancingPolicyClassName,
+                                       long pingPeriod,                                  
+                                       long callTimeout,
+                                       String clientID,
+                                       int dupsOKBatchSize,
+                                       int transactionBatchSize,
+                                       int consumerWindowSize,
+                                       int consumerMaxRate,
+                                       int producerWindowSize,
+                                       int producerMaxRate,
+                                       int minLargeMessageSize, 
+                                       boolean blockOnAcknowledge,
+                                       boolean blockOnNonPersistentSend,
+                                       boolean blockOnPersistentSend,
+                                       boolean autoGroup,
+                                       int maxConnections,
+                                       boolean preAcknowledge,
+                                       String jndiBinding) throws Exception
+   {
+      List<String> bindings = new ArrayList<String>();
+      bindings.add(jndiBinding);
 
+      boolean created = server.createConnectionFactory(name,
+                                                       discoveryGroupConfig,
+                                                       discoveryInitialWait,
+                                                       connectionLoadBalancingPolicyClassName,
+                                                       pingPeriod,                                                    
+                                                       callTimeout,
+                                                       clientID,
+                                                       dupsOKBatchSize,
+                                                       transactionBatchSize,
+                                                       consumerWindowSize,
+                                                       consumerMaxRate,
+                                                       producerWindowSize,
+                                                       producerMaxRate,
+                                                       minLargeMessageSize,
+                                                       blockOnAcknowledge,
+                                                       blockOnNonPersistentSend,
+                                                       blockOnPersistentSend,
+                                                       autoGroup,
+                                                       maxConnections,
+                                                       preAcknowledge,
+                                                       bindings);
+      if (created)
+      {
+         sendNotification(NotificationType.CONNECTION_FACTORY_CREATED, name);
+      }
+   }
+
    public boolean createQueue(final String name, final String jndiBinding) throws Exception
    {
       boolean created = server.createQueue(name, jndiBinding);

Modified: trunk/src/main/org/jboss/messaging/util/Pair.java
===================================================================
--- trunk/src/main/org/jboss/messaging/util/Pair.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/src/main/org/jboss/messaging/util/Pair.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -22,6 +22,8 @@
 
 package org.jboss.messaging.util;
 
+import java.io.Serializable;
+
 /**
  * 
  * A Pair
@@ -29,8 +31,10 @@
  * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
  *
  */
-public class Pair<A, B>
+public class Pair<A, B> implements Serializable
 {
+   private static final long serialVersionUID = -2496357457812368127L;
+
    public Pair(A a, B b)
    {
       this.a = a;
@@ -41,4 +45,42 @@
    public A a;
    
    public B b;
+   
+   private int hash = -1;
+   
+   public int hashCode()
+   {
+      if (hash == -1)
+      {
+         if (a == null && b == null)
+         {
+            return super.hashCode();
+         }
+         else
+         {
+            hash = (a == null ? 0 : a.hashCode()) + 37 * (b == null ? 0 : b.hashCode());
+         }
+      }
+      
+      return hash;
+   }
+   
+   public boolean equals(Object other)
+   {
+      if (other == this)
+      {
+         return true;
+      }
+      
+      if (other instanceof Pair == false)
+      {
+         return false;
+      }
+      
+      Pair<A, B> pother = (Pair<A, B>)other;
+      
+      return (pother.a == null ? a == null : pother.a.equals(a)) &&
+             (pother.b == null ? b == null : pother.b.equals(b));                 
+      
+   }
 }

Added: trunk/src/main/org/jboss/messaging/util/Random.java
===================================================================
--- trunk/src/main/org/jboss/messaging/util/Random.java	                        (rev 0)
+++ trunk/src/main/org/jboss/messaging/util/Random.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -0,0 +1,54 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2005-2008, Red Hat Middleware LLC, and individual contributors
+ * 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.messaging.util;
+
+
+/**
+ * A Random
+ *
+ * @author <a href="mailto:tim.fox at jboss.com">Tim Fox</a>
+ * 
+ * Created 28 Nov 2008 10:28:28
+ *
+ *
+ */
+public class Random
+{
+   private static int extraSeed;
+   
+   private static long getSeed()
+   {
+      long seed = System.currentTimeMillis() + extraSeed++;
+      
+      return seed;
+   }
+   
+   private java.util.Random random = new java.util.Random(getSeed());
+   
+   public java.util.Random getRandom()
+   {
+      return random;
+   }
+
+}

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/CTSMiscellaneousTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -43,6 +43,7 @@
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
+import org.jboss.messaging.util.Pair;
 import org.jboss.test.messaging.JBMServerTestCase;
 import org.jboss.test.messaging.jms.message.SimpleJMSBytesMessage;
 import org.jboss.test.messaging.jms.message.SimpleJMSMessage;
@@ -86,10 +87,18 @@
          // Deploy a connection factory with load balancing but no failover on node0
          List<String> bindings = new ArrayList<String>();
          bindings.add("StrictTCKConnectionFactory");
-
+         
+         List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = 
+            new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+         
+         connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"), null));
+         
+         List<String> jndiBindings = new ArrayList<String>();
+         jndiBindings.add("/StrictTCKConnectionFactory");
+         
          getJmsServerManager().createConnectionFactory("StrictTCKConnectionFactory",
-                                                       new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"),
-                                                       null,
+                                                       connectorConfigs,
+                                                       ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                        ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,                                                       
                                                        ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                        null,
@@ -99,14 +108,14 @@
                                                        ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                        ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                        ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                       -1,
+                                                       ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                        true,
                                                        true,
                                                        true,
                                                        ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
                                                        ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
                                                        ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
-                                                       "/StrictTCKConnectionFactory");
+                                                       jndiBindings);
 
          cf = (JBossConnectionFactory)getInitialContext().lookup("/StrictTCKConnectionFactory");
       }

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/jms/JMSTestCase.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1,10 +1,14 @@
 package org.jboss.test.messaging.jms;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import javax.naming.InitialContext;
 
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
 import org.jboss.messaging.jms.client.JBossConnectionFactory;
+import org.jboss.messaging.util.Pair;
 import org.jboss.test.messaging.JBMServerTestCase;
 
 /**
@@ -37,9 +41,18 @@
       // All jms tests should use a specific cg which has blockOnAcknowledge = true and
       // both np and p messages are sent synchronously
 
+      List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = 
+         new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+      
+      connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"), null));
+      
+      List<String> jndiBindings = new ArrayList<String>();
+      jndiBindings.add("/testsuitecf");
+      
+      
       getJmsServerManager().createConnectionFactory("testsuitecf",
-                                                    new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"),
-                                                    null,
+                                                    connectorConfigs,
+                                                    ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                     ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,                                                       
                                                     ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                     null,
@@ -49,14 +62,14 @@
                                                     ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                     ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                     ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                    -1,
+                                                    ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                     true,
                                                     true,
                                                     true,
                                                     ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
                                                     ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
                                                     ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
-                                                    "/testsuitecf");
+                                                    jndiBindings);
       
       cf = (JBossConnectionFactory)getInitialContext().lookup("/testsuitecf");
    }

Modified: trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java
===================================================================
--- trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/jms-tests/src/org/jboss/test/messaging/tools/container/LocalTestServer.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -26,6 +26,7 @@
 import java.sql.Connection;
 import java.sql.PreparedStatement;
 import java.sql.SQLException;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
@@ -56,6 +57,7 @@
 import org.jboss.messaging.jms.server.management.TopicControlMBean;
 import org.jboss.messaging.jms.server.management.impl.JMSManagementServiceImpl;
 import org.jboss.messaging.integration.bootstrap.JBMBootstrapServer;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 import org.jboss.test.messaging.tools.ConfigurationHelper;
 import org.jboss.test.messaging.tools.ServerManagement;
@@ -536,19 +538,24 @@
    {
       log.info("deploying connection factory with name: " + objectName + " and dupsok: " + dupsOkBatchSize);
 
+      List<Pair<TransportConfiguration, TransportConfiguration>> connectorConfigs = 
+         new ArrayList<Pair<TransportConfiguration, TransportConfiguration>>();
+      
+      connectorConfigs.add(new Pair<TransportConfiguration, TransportConfiguration>(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"), null));
+           
       getJMSServerManager().createConnectionFactory(objectName,
-                                                    new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"),
-                                                    null,
-                                                    ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
+                                                    connectorConfigs,
+                                                    ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                    ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,                                                       
                                                     ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                     clientId,
                                                     dupsOkBatchSize,
                                                     ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
                                                     prefetchSize,
                                                     -1,
-                                                    ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                     -1,
-                                                    -1,
+                                                    ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                    ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,                                                    
                                                     blockOnAcknowledge,
                                                     true,
                                                     true,

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/clientcrash/ClientCrashTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -24,23 +24,25 @@
 
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP;
-import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE;
+import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE;
 import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE;
-import static org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE;
 
 import org.jboss.messaging.core.client.ClientConsumer;
 import org.jboss.messaging.core.client.ClientMessage;
 import org.jboss.messaging.core.client.ClientProducer;
 import org.jboss.messaging.core.client.ClientSession;
 import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.ConnectionLoadBalancingPolicy;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
@@ -154,13 +156,14 @@
 
       sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"),
                                         null,
+                                        DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                         2000,
                                         DEFAULT_CALL_TIMEOUT,
                                         DEFAULT_CONSUMER_WINDOW_SIZE,
                                         DEFAULT_CONSUMER_MAX_RATE,
                                         DEFAULT_SEND_WINDOW_SIZE,
                                         DEFAULT_PRODUCER_MAX_RATE,
-                                        DEFAULT_BIG_MESSAGE_SIZE,
+                                        DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                         DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                         DEFAULT_BLOCK_ON_PERSISTENT_SEND,
                                         DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/BasicMessageFlowTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/BasicMessageFlowTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/BasicMessageFlowTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -36,12 +36,11 @@
 import org.jboss.messaging.core.client.ClientSessionFactory;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.cluster.BroadcastGroupConfiguration;
-import org.jboss.messaging.core.config.cluster.DiscoveryGroupConfiguration;
 import org.jboss.messaging.core.config.cluster.MessageFlowConfiguration;
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -87,8 +86,8 @@
       connectors.put(server1tc.getName(), server1tc);
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       final SimpleString address1 = new SimpleString("testaddress");
 
@@ -182,8 +181,8 @@
       connectors.put(server1tc.getName(), server1tc);
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       final SimpleString address1 = new SimpleString("testaddress");
 
@@ -256,8 +255,8 @@
       connectors.put(server1tc.getName(), server1tc);
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       final SimpleString address1 = new SimpleString("testaddress");
 

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/DiscoveryFlowTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/DiscoveryFlowTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/DiscoveryFlowTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -42,6 +42,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -91,8 +92,8 @@
       Map<String, TransportConfiguration> server1Connectors = new HashMap<String, TransportConfiguration>();
       server1Connectors.put(server1tc.getName(), server1tc);
       service1.getServer().getConfiguration().setConnectorConfigurations(server1Connectors);
-      List<String> connectorNames1 = new ArrayList<String>();
-      connectorNames1.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames1 = new ArrayList<Pair<String, String>>();
+      connectorNames1.add(new Pair<String, String>(server1tc.getName(), null));
       BroadcastGroupConfiguration bcConfig1 = new BroadcastGroupConfiguration(bcGroupName,
                                                                               localBindAddress,
                                                                               localBindPort,
@@ -112,8 +113,8 @@
       Map<String, TransportConfiguration> server2Connectors = new HashMap<String, TransportConfiguration>();
       server2Connectors.put(server2tc.getName(), server2tc);
       service2.getServer().getConfiguration().setConnectorConfigurations(server2Connectors);
-      List<String> connectorNames2 = new ArrayList<String>();
-      connectorNames2.add(server2tc.getName());
+      List<Pair<String, String>> connectorNames2 = new ArrayList<Pair<String, String>>();
+      connectorNames2.add(new Pair<String, String>(server2tc.getName(), null));
       BroadcastGroupConfiguration bcConfig2 = new BroadcastGroupConfiguration(bcGroupName,
                                                                               localBindAddress,
                                                                               localBindPort,
@@ -133,8 +134,8 @@
       Map<String, TransportConfiguration> server3Connectors = new HashMap<String, TransportConfiguration>();
       server3Connectors.put(server3tc.getName(), server3tc);
       service3.getServer().getConfiguration().setConnectorConfigurations(server3Connectors);
-      List<String> connectorNames3 = new ArrayList<String>();
-      connectorNames3.add(server3tc.getName());
+      List<Pair<String, String>> connectorNames3 = new ArrayList<Pair<String, String>>();
+      connectorNames3.add(new Pair<String, String>(server3tc.getName(), null));
       BroadcastGroupConfiguration bcConfig3 = new BroadcastGroupConfiguration(bcGroupName,
                                                                               localBindAddress,
                                                                               localBindPort,
@@ -154,8 +155,8 @@
       Map<String, TransportConfiguration> server4Connectors = new HashMap<String, TransportConfiguration>();
       server4Connectors.put(server4tc.getName(), server4tc);
       service4.getServer().getConfiguration().setConnectorConfigurations(server4Connectors);
-      List<String> connectorNames4 = new ArrayList<String>();
-      connectorNames4.add(server4tc.getName());
+      List<Pair<String, String>> connectorNames4 = new ArrayList<Pair<String, String>>();
+      connectorNames4.add(new Pair<String, String>(server4tc.getName(), null));
       BroadcastGroupConfiguration bcConfig4 = new BroadcastGroupConfiguration(bcGroupName,
                                                                               localBindAddress,
                                                                               localBindPort,
@@ -180,8 +181,8 @@
                                                                              discoveryTimeout);
       
       
-      Set<DiscoveryGroupConfiguration> dcConfigs = new HashSet<DiscoveryGroupConfiguration>();
-      dcConfigs.add(dcConfig);
+      Map<String, DiscoveryGroupConfiguration> dcConfigs = new HashMap<String, DiscoveryGroupConfiguration>();
+      dcConfigs.put(dcConfig.getName(), dcConfig);
       service0.getServer().getConfiguration().setDiscoveryGroupConfigurations(dcConfigs);
 
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchSizeTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchSizeTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchSizeTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -40,6 +40,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -86,8 +87,9 @@
 
       final int batchSize = 10;
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
+      
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",
                                                                        address1.toString(),
                                                                        null,

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchTimeTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchTimeTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowBatchTimeTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -40,6 +40,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -87,8 +88,8 @@
       final int batchSize = 10;
       final long batchTime = 250;
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",
                                                                        address1.toString(),

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowTransformerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowTransformerTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowTransformerTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -40,6 +40,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -84,8 +85,8 @@
 
       final SimpleString address1 = new SimpleString("address1");
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",
                                                                        "address1",

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWildcardTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWildcardTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWildcardTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -40,6 +40,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -92,8 +93,8 @@
 
       final SimpleString match1 = new SimpleString("cheese.#");
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",
                                                                        match1.toString(),

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWithFilterTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWithFilterTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/MessageFlowWithFilterTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -40,6 +40,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -86,8 +87,8 @@
 
       final String filter = "selectorkey='ORANGES'";
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
 
       MessageFlowConfiguration ofconfig = new MessageFlowConfiguration("outflow1",
                                                                        address1.toString(),

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/StaticFlowTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/StaticFlowTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/distribution/StaticFlowTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -42,6 +42,7 @@
 import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.util.Pair;
 import org.jboss.messaging.util.SimpleString;
 
 /**
@@ -113,11 +114,11 @@
 
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
-      connectorNames.add(server2tc.getName());
-      connectorNames.add(server3tc.getName());
-      connectorNames.add(server4tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server2tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server3tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server4tc.getName(), null));
 
       final SimpleString testAddress = new SimpleString("testaddress");
 
@@ -274,11 +275,11 @@
 
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames = new ArrayList<String>();
-      connectorNames.add(server1tc.getName());
-      connectorNames.add(server2tc.getName());
-      connectorNames.add(server3tc.getName());
-      connectorNames.add(server4tc.getName());
+      List<Pair<String, String>> connectorNames = new ArrayList<Pair<String, String>>();
+      connectorNames.add(new Pair<String, String>(server1tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server2tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server3tc.getName(), null));
+      connectorNames.add(new Pair<String, String>(server4tc.getName(), null));
 
       final SimpleString testAddress = new SimpleString("testaddress");
 
@@ -444,15 +445,18 @@
 
       service0.getServer().getConfiguration().setConnectorConfigurations(connectors);
 
-      List<String> connectorNames1 = new ArrayList<String>();
-      connectorNames1.add(server1tc.getName());
-      List<String> connectorNames2 = new ArrayList<String>();
-      connectorNames2.add(server2tc.getName());
-      List<String> connectorNames3 = new ArrayList<String>();
-      connectorNames3.add(server3tc.getName());
-      List<String> connectorNames4 = new ArrayList<String>();
-      connectorNames4.add(server4tc.getName());
-
+      List<Pair<String, String>> connectorNames1 = new ArrayList<Pair<String, String>>();
+      connectorNames1.add(new Pair<String, String>(server1tc.getName(), null));
+      
+      List<Pair<String, String>> connectorNames2 = new ArrayList<Pair<String, String>>();
+      connectorNames2.add(new Pair<String, String>(server2tc.getName(), null));
+      
+      List<Pair<String, String>> connectorNames3 = new ArrayList<Pair<String, String>>();
+      connectorNames3.add(new Pair<String, String>(server3tc.getName(), null));
+      
+      List<Pair<String, String>> connectorNames4 = new ArrayList<Pair<String, String>>();
+      connectorNames4.add(new Pair<String, String>(server4tc.getName(), null));
+      
       final SimpleString testAddress = new SimpleString("testaddress");
 
       MessageFlowConfiguration ofconfig1 = new MessageFlowConfiguration("flow1",

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ActivationTimeoutTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ActivationTimeoutTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ActivationTimeoutTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -42,7 +42,6 @@
 import org.jboss.messaging.core.remoting.RemotingConnection;
 import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
-import org.jboss.messaging.core.remoting.spi.Connector;
 import org.jboss.messaging.core.server.MessagingService;
 import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
 import org.jboss.messaging.jms.client.JBossTextMessage;

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverManagementTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverManagementTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverManagementTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -27,8 +27,6 @@
 import java.util.HashMap;
 import java.util.Map;
 
-import javax.management.Notification;
-
 import junit.framework.TestCase;
 
 import org.jboss.messaging.core.client.ClientConsumer;

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverPreAcknowledgeTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverPreAcknowledgeTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/FailoverPreAcknowledgeTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -21,30 +21,31 @@
  */
 package org.jboss.messaging.tests.integration.cluster.failover;
 
+import java.util.HashMap;
+import java.util.Map;
+
 import junit.framework.TestCase;
-import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.server.MessagingService;
-import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
+
+import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.client.ClientMessage;
+import org.jboss.messaging.core.client.ClientProducer;
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.client.impl.ClientSessionFactoryInternal;
-import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
 import org.jboss.messaging.core.client.impl.ClientSessionImpl;
-import org.jboss.messaging.core.client.ClientSession;
-import org.jboss.messaging.core.client.ClientProducer;
-import org.jboss.messaging.core.client.ClientMessage;
-import org.jboss.messaging.core.client.ClientConsumer;
+import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.impl.ConfigurationImpl;
+import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.logging.Logger;
 import org.jboss.messaging.core.remoting.RemotingConnection;
+import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
 import org.jboss.messaging.core.remoting.impl.invm.TransportConstants;
-import org.jboss.messaging.core.remoting.impl.invm.InVMRegistry;
-import org.jboss.messaging.core.exception.MessagingException;
+import org.jboss.messaging.core.server.MessagingService;
+import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
+import org.jboss.messaging.jms.client.JBossTextMessage;
 import org.jboss.messaging.util.SimpleString;
-import org.jboss.messaging.jms.client.JBossTextMessage;
 
-import java.util.Map;
-import java.util.HashMap;
-
 /**
  * @author <a href="mailto:andy.taylor at jboss.org">Andy Taylor</a>
  */

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/MultiThreadRandomFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/MultiThreadRandomFailoverTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/MultiThreadRandomFailoverTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -1304,8 +1304,6 @@
 
          assertEquals(0, sf.numConnections());
 
-         assertEquals(0, sf.numBackupConnections());
-
          stop();
       }
    }

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/RandomFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/RandomFailoverTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/RandomFailoverTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -249,8 +249,6 @@
          
          assertEquals(0, sf.numConnections());
          
-         assertEquals(0, sf.numBackupConnections());
-
          stop();
       }
    }
@@ -358,13 +356,11 @@
          assertTrue("Didn't receive all messages", ok);
       }
 
-      log.info("*** closing sessions");
       sessSend.close();
       for (ClientSession session : sessions)
       {
          session.close();
       }
-      log.info("*** closed sessions");
 
       for (int i = 0; i < numSessions; i++)
       {

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ReplicateConnectionFailureTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ReplicateConnectionFailureTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/ReplicateConnectionFailureTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -77,24 +77,24 @@
    {
       final long pingPeriod = 500;
 
-      // TODO - use the defaults!!
       ClientSessionFactoryInternal sf1 = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                                       new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
                                                                                                  backupParams),
-                                                                      pingPeriod,
-                                                                      ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
-                                                                      ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
-                                                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
-                                                                      ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
-                                                                      ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
-                                                                      ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
-                                                                      ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                                                                 pingPeriod,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
+                                                                                                 ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
       
 
       sf1.setSendWindowSize(32 * 1024);
@@ -108,8 +108,8 @@
       // One connection
       assertEquals(1, liveService.getServer().getRemotingService().getConnections().size());
 
-      // One replicating connection per session + one backup connection per session
-      assertEquals(2, backupService.getServer().getRemotingService().getConnections().size());
+      // One replicating connection per session
+      assertEquals(1, backupService.getServer().getRemotingService().getConnections().size());
 
       session1.close();
 
@@ -123,7 +123,7 @@
 
       assertEquals(1, liveService.getServer().getRemotingService().getConnections().size());
 
-      assertEquals(2, backupService.getServer().getRemotingService().getConnections().size());
+      assertEquals(1, backupService.getServer().getRemotingService().getConnections().size());
 
       final RemotingConnectionImpl conn1 = (RemotingConnectionImpl)((ClientSessionImpl)session1).getConnection();
 
@@ -133,9 +133,7 @@
 
       assertEquals(0, liveService.getServer().getRemotingService().getConnections().size());
 
-      // Should be one connection left to the backup - the other one (replicating connection) should be automatically
-      // closed
-      assertEquals(1, backupService.getServer().getRemotingService().getConnections().size());
+      assertEquals(0, backupService.getServer().getRemotingService().getConnections().size());
 
       session1.close();
 

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleAutomaticFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleAutomaticFailoverTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleAutomaticFailoverTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -213,8 +213,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailoverChangeConnectionFactory() throws Exception
@@ -297,8 +295,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testNoMessagesLeftAfterFailoverNewSession() throws Exception
@@ -368,8 +364,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testCreateMoreSessionsAfterFailover() throws Exception
@@ -441,8 +435,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailureListenerCalledOnFailure() throws Exception
@@ -528,8 +520,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailoverMultipleSessions() throws Exception
@@ -619,8 +609,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testAllConnectionsReturned() throws Exception
@@ -652,8 +640,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testAllConnectionsReturnedAfterFailover() throws Exception
@@ -690,8 +676,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    public void testFailureAfterFailover() throws Exception
@@ -783,8 +767,6 @@
       assertEquals(0, sf.numSessions());
 
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    // Package protected ---------------------------------------------

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleManualFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleManualFailoverTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/cluster/failover/SimpleManualFailoverTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -169,8 +169,6 @@
       assertEquals(0, sf.numSessions());
       
       assertEquals(0, sf.numConnections());
-      
-      assertEquals(0, sf.numBackupConnections());
    }
 
    // Package protected ---------------------------------------------

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/consumer/ConsumerTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -410,7 +410,6 @@
 
    public void testConsumerAckImmediateAutoCommitTrue() throws Exception
    {
-
       ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"));
 
       ClientSession session = sf.createSession(false, true, true, true);
@@ -436,8 +435,8 @@
          assertEquals("m" + i, message2.getBody().getString());
       }
       // assert that all the messages are there and none have been acked
-      assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getDeliveringCount(), 0);
-      assertEquals(messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getMessageCount(), 0);
+      assertEquals(0, messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getDeliveringCount());
+      assertEquals(0, messagingService.getServer().getPostOffice().getBinding(QUEUE).getQueue().getMessageCount());
 
       session.close();
    }

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/jms/cluster/JMSFailoverTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/jms/cluster/JMSFailoverTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/jms/cluster/JMSFailoverTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -92,6 +92,7 @@
       JBossConnectionFactory jbcf = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                                new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
                                                                                           backupParams),
+                                                               ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                                ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                                ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                                null,
@@ -101,10 +102,10 @@
                                                                ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                                ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                                ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                               ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                               ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                                ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                                ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
-                                                               ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                               true,
                                                                ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
                                                                ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
                                                                ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE);
@@ -172,19 +173,20 @@
    {
       JBossConnectionFactory jbcfLive = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                                    null,
+                                                                   ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                                    ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                                    ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
-                                                                   null,                                                                   
+                                                                   null,
                                                                    ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
                                                                    ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
                                                                    ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
                                                                    ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                                    ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                                    ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                                   ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                                   ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                                    ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
-                                                                   ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                                    true,
+                                                                   true,
                                                                    ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
                                                                    ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
                                                                    ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE);
@@ -192,6 +194,7 @@
       JBossConnectionFactory jbcfBackup = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
                                                                                                 backupParams),
                                                                      null,
+                                                                     ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                                      ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                                      ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                                      null,
@@ -201,10 +204,10 @@
                                                                      ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                                      ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                                      ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                                     ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                                     ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
-                                                                     ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
-                                                                     ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                                     true,
+                                                                     true,
                                                                      ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
                                                                      ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
                                                                      ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE);
@@ -237,9 +240,9 @@
 
          producerLive.send(tm);
       }
-      
-      // Note we block on NP send to make sure all messages get to server before failover
 
+      // Note we block on P send to make sure all messages get to server before failover
+
       MessagingException me = new MessagingException(MessagingException.NOT_CONNECTED);
 
       coreConnLive.fail(me);
@@ -304,7 +307,8 @@
               .add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
       Map<String, TransportConfiguration> connectors = new HashMap<String, TransportConfiguration>();
       TransportConfiguration backupTC = new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory",
-                                                                   backupParams, "backup-connector");
+                                                                   backupParams,
+                                                                   "backup-connector");
       connectors.put(backupTC.getName(), backupTC);
       liveConf.setConnectorConfigurations(connectors);
       liveConf.setBackupConnectorName(backupTC.getName());

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/jms/consumer/ConsumerTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/jms/consumer/ConsumerTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/jms/consumer/ConsumerTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -63,7 +63,7 @@
       conf.setSecurityEnabled(false);
       conf.setJMXManagementEnabled(true);
       conf.getAcceptorConfigurations()
-            .add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
+          .add(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMAcceptorFactory"));
       service = MessagingServiceImpl.newNullStorageMessagingServer(conf);
       service.start();
       serverManager = JMSServerManagerImpl.newJMSServerManagerImpl(service.getServer());
@@ -71,23 +71,24 @@
       serverManager.setInitialContext(new NullInitialContext());
       serverManager.createQueue(Q_NAME, Q_NAME);
       cf = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
-                                                             null,
-                                                             ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
-                                                             ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
-                                                             null,
-                                                             ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
-                                                             ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
-                                                             ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
-                                                             ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
-                                                             ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
-                                                             true,
-                                                             ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
-                                                             ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
-                                                             true);
+                                      null,
+                                      ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                      ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
+                                      ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                      null,
+                                      ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
+                                      ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE,
+                                      ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                      ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                      ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                      ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                      ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                      ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                      true,
+                                      ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                      ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                      true);
    }
 
    @Override
@@ -117,18 +118,18 @@
       MessageProducer producer = session.createProducer(jBossQueue);
       MessageConsumer consumer = session.createConsumer(jBossQueue);
       int noOfMessages = 100;
-      for(int i = 0; i < noOfMessages; i++)
+      for (int i = 0; i < noOfMessages; i++)
       {
          producer.send(session.createTextMessage("m" + i));
       }
 
       conn.start();
-      for(int i = 0; i < noOfMessages; i++)
+      for (int i = 0; i < noOfMessages; i++)
       {
          Message m = consumer.receive(500);
          assertNotNull(m);
       }
-       // assert that all the messages are there and none have been acked
+      // assert that all the messages are there and none have been acked
       SimpleString queueName = new SimpleString(JBossQueue.JMS_QUEUE_ADDRESS_PREFIX + Q_NAME);
       assertEquals(service.getServer().getPostOffice().getBinding(queueName).getQueue().getDeliveringCount(), 0);
       assertEquals(service.getServer().getPostOffice().getBinding(queueName).getQueue().getMessageCount(), 0);

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSQueueControlTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSQueueControlTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSQueueControlTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -158,6 +158,7 @@
 
       JBossConnectionFactory cf = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                              null,
+                                                             ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                              ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                              null,
@@ -167,7 +168,7 @@
                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                             ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                              true,

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSUtil.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSUtil.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/jms/management/JMSUtil.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -59,6 +59,7 @@
    {
       JBossConnectionFactory cf = new JBossConnectionFactory(new TransportConfiguration(connectorFactory),
                                                              null,
+                                                             ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                              ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                              null,
@@ -68,7 +69,7 @@
                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                             ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                              true,
@@ -78,12 +79,12 @@
 
       return cf.createConnection();
    }
-   
 
    static MessageConsumer createConsumer(Destination destination, boolean startConnection, String connectorFactory) throws JMSException
    {
       JBossConnectionFactory cf = new JBossConnectionFactory(new TransportConfiguration(connectorFactory),
                                                              null,
+                                                             ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                              ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                              null,
@@ -93,7 +94,7 @@
                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                             ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                              true,
@@ -112,17 +113,19 @@
 
       return s.createConsumer(destination);
    }
-   
+
    static MessageConsumer createConsumer(Destination destination, boolean startConnection) throws JMSException
    {
-      return createConsumer(destination, startConnection, "org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory");
+      return createConsumer(destination,
+                            startConnection,
+                            "org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory");
    }
 
-   
    static TopicSubscriber createDurableSubscriber(Topic topic, String clientID, String subscriptionName) throws JMSException
    {
       JBossConnectionFactory cf = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                              null,
+                                                             ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                              ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                              null,
@@ -132,7 +135,7 @@
                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                             ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                              true,
@@ -152,6 +155,7 @@
    {
       JBossConnectionFactory cf = new JBossConnectionFactory(new TransportConfiguration("org.jboss.messaging.core.remoting.impl.invm.InVMConnectorFactory"),
                                                              null,
+                                                             ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
                                                              ClientSessionFactoryImpl.DEFAULT_PING_PERIOD,
                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
                                                              null,
@@ -161,7 +165,7 @@
                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
-                                                             ClientSessionFactoryImpl.DEFAULT_BIG_MESSAGE_SIZE,
+                                                             ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
                                                              true,
@@ -180,7 +184,6 @@
       }
    }
 
-
    // Constructors --------------------------------------------------
 
    // Public --------------------------------------------------------

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/remoting/PingTest.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -18,7 +18,7 @@
  * 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.messaging.tests.integration.remoting;
 
@@ -26,25 +26,25 @@
 import java.util.Map;
 import java.util.Set;
 
-import junit.framework.TestCase;
-
+import org.jboss.messaging.core.client.ClientSession;
+import org.jboss.messaging.core.client.ClientSessionFactory;
+import org.jboss.messaging.core.client.ConnectionManager;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryImpl;
+import org.jboss.messaging.core.client.impl.ClientSessionFactoryInternal;
+import org.jboss.messaging.core.client.impl.ClientSessionInternal;
+import org.jboss.messaging.core.client.impl.ConnectionManagerImpl;
 import org.jboss.messaging.core.config.Configuration;
 import org.jboss.messaging.core.config.TransportConfiguration;
-import org.jboss.messaging.core.config.impl.ConfigurationImpl;
 import org.jboss.messaging.core.exception.MessagingException;
 import org.jboss.messaging.core.logging.Logger;
-import org.jboss.messaging.core.remoting.ConnectionManager;
 import org.jboss.messaging.core.remoting.FailureListener;
 import org.jboss.messaging.core.remoting.Interceptor;
 import org.jboss.messaging.core.remoting.Packet;
 import org.jboss.messaging.core.remoting.RemotingConnection;
-import org.jboss.messaging.core.remoting.impl.ConnectionManagerImpl;
 import org.jboss.messaging.core.remoting.impl.RemotingConnectionImpl;
-import org.jboss.messaging.integration.transports.netty.NettyConnectorFactory;
 import org.jboss.messaging.core.remoting.impl.wireformat.PacketImpl;
 import org.jboss.messaging.core.remoting.spi.ConnectorFactory;
-import org.jboss.messaging.core.server.MessagingService;
-import org.jboss.messaging.core.server.impl.MessagingServiceImpl;
+import org.jboss.messaging.integration.transports.netty.NettyConnectorFactory;
 import org.jboss.messaging.tests.util.ServiceTestBase;
 
 /**
@@ -57,7 +57,7 @@
 public class PingTest extends ServiceTestBase
 {
    // Constants -----------------------------------------------------
-   
+
    private static final Logger log = Logger.getLogger(PingTest.class);
 
    private static final long PING_INTERVAL = 500;
@@ -83,16 +83,16 @@
    {
       messagingService.stop();
    }
-   
+
    class Listener implements FailureListener
    {
       volatile MessagingException me;
-      
+
       public void connectionFailed(MessagingException me)
       {
          this.me = me;
       }
-      
+
       public MessagingException getException()
       {
          return me;
@@ -103,243 +103,303 @@
     * Test that no failure listeners are triggered in a non failure case with pinging going on
     */
    public void testNoFailureWithPinging() throws Exception
-   {           
-      ConnectorFactory cf = new NettyConnectorFactory();
-      Map<String, Object> params = new HashMap<String, Object>();
-      
-      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1);
+   {
+      TransportConfiguration transportConfig = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
 
-      RemotingConnection conn = cm.getConnection();
-      assertNotNull(conn);
-      assertEquals(1, cm.numConnections());
-      
+      ClientSessionFactory csf = new ClientSessionFactoryImpl(transportConfig,
+                                                              null,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                              PING_INTERVAL,
+                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                                              ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
+
+      ClientSession session = csf.createSession(false, true, true);
+
+      assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections());
+
       Listener clientListener = new Listener();
-      
-      conn.addFailureListener(clientListener);
-      
+
+      session.addFailureListener(clientListener);
+
       RemotingConnection serverConn = null;
       while (serverConn == null)
       {
          Set<RemotingConnection> conns = messagingService.getServer().getRemotingService().getConnections();
-         
+
          if (!conns.isEmpty())
-         {            
+         {
             serverConn = messagingService.getServer().getRemotingService().getConnections().iterator().next();
          }
          else
          {
-            //It's async so need to wait a while
+            // It's async so need to wait a while
             Thread.sleep(10);
          }
       }
-      
+
       Listener serverListener = new Listener();
-      
+
       serverConn.addFailureListener(serverListener);
-      
+
       Thread.sleep(PING_INTERVAL * 3);
-      
+
       assertNull(clientListener.getException());
-      
+
       assertNull(serverListener.getException());
-      
-      RemotingConnection serverConn2 = messagingService.getServer().getRemotingService().getConnections().iterator().next();
-      
-      assertTrue(serverConn == serverConn2);    
-        
-      cm.returnConnection(conn.getID());
+
+      RemotingConnection serverConn2 = messagingService.getServer()
+                                                       .getRemotingService()
+                                                       .getConnections()
+                                                       .iterator()
+                                                       .next();
+
+      assertTrue(serverConn == serverConn2);
+
+      session.close();
    }
-   
+
    /*
     * Test that no failure listeners are triggered in a non failure case with no pinging going on
     */
    public void testNoFailureNoPinging() throws Exception
-   {           
-      ConnectorFactory cf = new NettyConnectorFactory();
-      Map<String, Object> params = new HashMap<String, Object>();
+   {
+      TransportConfiguration transportConfig = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
+
+      ClientSessionFactory csf = new ClientSessionFactoryImpl(transportConfig,
+                                                              null,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                              PING_INTERVAL,
+                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                                              ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
+
+      ClientSession session = csf.createSession(false, true, true);
       
-      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1);
-      
-      RemotingConnection conn = cm.getConnection();
-      assertNotNull(conn);
-      assertEquals(1, cm.numConnections());
-      
+      assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections());
+
       Listener clientListener = new Listener();
-      
-      conn.addFailureListener(clientListener);
-      
+
+      session.addFailureListener(clientListener);
+
       RemotingConnection serverConn = null;
       while (serverConn == null)
       {
          Set<RemotingConnection> conns = messagingService.getServer().getRemotingService().getConnections();
-         
+
          if (!conns.isEmpty())
-         {            
+         {
             serverConn = messagingService.getServer().getRemotingService().getConnections().iterator().next();
          }
          else
          {
-            //It's async so need to wait a while
+            // It's async so need to wait a while
             Thread.sleep(10);
          }
       }
-      
+
       Listener serverListener = new Listener();
-      
+
       serverConn.addFailureListener(serverListener);
-      
+
       Thread.sleep(PING_INTERVAL * 3);
-      
+
       assertNull(clientListener.getException());
-      
+
       assertNull(serverListener.getException());
-      
-      RemotingConnection serverConn2 = messagingService.getServer().getRemotingService().getConnections().iterator().next();
-      
-      assertTrue(serverConn == serverConn2); 
-      
-      cm.returnConnection(conn.getID());
+
+      RemotingConnection serverConn2 = messagingService.getServer()
+                                                       .getRemotingService()
+                                                       .getConnections()
+                                                       .iterator()
+                                                       .next();
+
+      assertTrue(serverConn == serverConn2);
+
+      session.close();
    }
-   
+
    /*
     * Test the server timing out a connection since it doesn't receive a ping in time
     */
    public void testServerFailureNoPing() throws Exception
-   {            
-      ConnectorFactory cf = new NettyConnectorFactory();
-      Map<String, Object> params = new HashMap<String, Object>();
+   {
+      TransportConfiguration transportConfig = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
+
+      ClientSessionFactory csf = new ClientSessionFactoryImpl(transportConfig,
+                                                              null,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                              PING_INTERVAL,
+                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                                              ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
       
-      ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1);
+      Listener clientListener = new Listener();
+
+      ClientSession session = csf.createSession(false, true, true);
       
-      RemotingConnectionImpl conn = (RemotingConnectionImpl)cm.getConnection();
-      assertEquals(1, cm.numConnections());
-      assertNotNull(conn);
-        
-      //We need to get it to send one ping then stop         
+      assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections());
+
+      session.addFailureListener(clientListener);
+      
+      RemotingConnectionImpl conn = (RemotingConnectionImpl)((ClientSessionInternal)session).getConnection();
+
+      // We need to get it to send one ping then stop
       conn.stopPingingAfterOne();
-             
-      Listener clientListener = new Listener();
-      
-      conn.addFailureListener(clientListener);
-                      
+
       RemotingConnection serverConn = null;
-      
+
       while (serverConn == null)
       {
          Set<RemotingConnection> conns = messagingService.getServer().getRemotingService().getConnections();
-         
+
          if (!conns.isEmpty())
-         {            
+         {
             serverConn = messagingService.getServer().getRemotingService().getConnections().iterator().next();
          }
          else
          {
-            //It's async so need to wait a while
+            // It's async so need to wait a while
             Thread.sleep(10);
          }
       }
-                  
+
       Listener serverListener = new Listener();
-      
+
       serverConn.addFailureListener(serverListener);
-      
+
       Thread.sleep(PING_INTERVAL * 10);
-      
-      //The client listener should be called too since the server will close it from the server side which will result in the
-      //MINA detecting closure on the client side and then calling failure listener
+
+      // The client listener should be called too since the server will close it from the server side which will result
+      // in the
+      // netty detecting closure on the client side and then calling failure listener
       assertNotNull(clientListener.getException());
-      
+
       assertNotNull(serverListener.getException());
-      
+
       assertTrue(messagingService.getServer().getRemotingService().getConnections().isEmpty());
-      
-      //Make sure we don't get the same connection back - it should have been removed from the registry
-      
-      RemotingConnection conn2 = cm.getConnection();
-      assertNotNull(conn2);
-      
-      cm.returnConnection(conn2.getID());    
+
+      session.close();
    }
 
    /*
    * Test the client triggering failure due to no pong received in time
    */
-  public void testClientFailureNoPong() throws Exception
-  {
-     Interceptor noPongInterceptor = new Interceptor()
-     {
-        public boolean intercept(Packet packet, RemotingConnection conn) throws MessagingException
-        {
-           log.info("In interceptor, packet is " + packet.getType());
-           if (packet.getType() == PacketImpl.PING)
-           {
-              return false;
-           }
-           else
-           {
-              return true;
-           }
-        }
-     };
-     
-     messagingService.getServer().getRemotingService().addInterceptor(noPongInterceptor);
-          
-     ConnectorFactory cf = new NettyConnectorFactory();
-     Map<String, Object> params = new HashMap<String, Object>();
-     
-     ConnectionManager cm = new ConnectionManagerImpl(cf, params, PING_INTERVAL, 5000, 1);
-     
-     RemotingConnection conn = cm.getConnection();
-     assertNotNull(conn);
-     assertEquals(1, cm.numConnections());
-            
-     Listener clientListener = new Listener();
-     
-     conn.addFailureListener(clientListener);
-     
-     RemotingConnection serverConn = null;
-     while (serverConn == null)
-     {
-        Set<RemotingConnection> conns = messagingService.getServer().getRemotingService().getConnections();
-        
-        if (!conns.isEmpty())
-        {            
-           serverConn = messagingService.getServer().getRemotingService().getConnections().iterator().next();
-        }
-        else
-        {
-           //It's async so need to wait a while
-           Thread.sleep(10);
-        }
-     }
-     
-     Listener serverListener = new Listener();
-     
-     serverConn.addFailureListener(serverListener);
-     
-     Thread.sleep(PING_INTERVAL * 2);
-     
-     assertNotNull(clientListener.getException());
-     
-     //Sleep a bit more since it's async
-     Thread.sleep(PING_INTERVAL);
-     
-     //We don't receive an exception on the server in this case
-     assertNull(serverListener.getException());
-     
-     assertTrue(messagingService.getServer().getRemotingService().getConnections().isEmpty());
-     
-     //Make sure we don't get the same connection back - it should have been removed from the registry
-     
-     RemotingConnection conn2 = cm.getConnection();
-     assertNotNull(conn2);        
+   public void testClientFailureNoPong() throws Exception
+   {
+      Interceptor noPongInterceptor = new Interceptor()
+      {
+         public boolean intercept(Packet packet, RemotingConnection conn) throws MessagingException
+         {
+            log.info("In interceptor, packet is " + packet.getType());
+            if (packet.getType() == PacketImpl.PING)
+            {
+               return false;
+            }
+            else
+            {
+               return true;
+            }
+         }
+      };
 
-     messagingService.getServer().getRemotingService().removeInterceptor(noPongInterceptor);
-     
-     cm.returnConnection(conn2.getID());
-     
-  }
-   
+      messagingService.getServer().getRemotingService().addInterceptor(noPongInterceptor);
+
+      TransportConfiguration transportConfig = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
+      
+      ClientSessionFactory csf = new ClientSessionFactoryImpl(transportConfig,
+                                                              null,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONNECTION_LOAD_BALANCING_POLICY_CLASS_NAME,
+                                                              PING_INTERVAL,
+                                                              ClientSessionFactoryImpl.DEFAULT_CALL_TIMEOUT,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_CONSUMER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_SEND_WINDOW_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRODUCER_MAX_RATE,
+                                                              ClientSessionFactoryImpl.DEFAULT_MIN_LARGE_MESSAGE_SIZE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_NON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_BLOCK_ON_PERSISTENT_SEND,
+                                                              ClientSessionFactoryImpl.DEFAULT_AUTO_GROUP,
+                                                              ClientSessionFactoryImpl.DEFAULT_MAX_CONNECTIONS,
+                                                              ClientSessionFactoryImpl.DEFAULT_PRE_ACKNOWLEDGE,
+                                                              ClientSessionFactoryImpl.DEFAULT_ACK_BATCH_SIZE);
+      
+      ClientSession session = csf.createSession(false, true, true);
+      
+      assertEquals(1, ((ClientSessionFactoryInternal)csf).numConnections());
+
+      Listener clientListener = new Listener();
+      
+      session.addFailureListener(clientListener);
+
+      RemotingConnection serverConn = null;
+      while (serverConn == null)
+      {
+         Set<RemotingConnection> conns = messagingService.getServer().getRemotingService().getConnections();
+
+         if (!conns.isEmpty())
+         {
+            serverConn = messagingService.getServer().getRemotingService().getConnections().iterator().next();
+         }
+         else
+         {
+            // It's async so need to wait a while
+            Thread.sleep(10);
+         }
+      }
+
+      Listener serverListener = new Listener();
+
+      serverConn.addFailureListener(serverListener);
+
+      Thread.sleep(PING_INTERVAL * 2);
+
+      assertNotNull(clientListener.getException());
+
+      // Sleep a bit more since it's async
+      Thread.sleep(PING_INTERVAL);
+
+      // We don't receive an exception on the server in this case
+      assertNull(serverListener.getException());
+
+      assertTrue(messagingService.getServer().getRemotingService().getConnections().isEmpty());
+
+      messagingService.getServer().getRemotingService().removeInterceptor(noPongInterceptor);
+
+      session.close();
+   }
+
    // Package protected ---------------------------------------------
 
    // Protected -----------------------------------------------------

Modified: trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java
===================================================================
--- trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java	2008-11-28 10:20:49 UTC (rev 5440)
+++ trunk/tests/src/org/jboss/messaging/tests/integration/ssl/CoreClientOverSSL.java	2008-11-28 18:59:53 UTC (rev 5441)
@@ -68,8 +68,9 @@
          
          System.out.println("ssl enabled is " + sslEnabled);
         
-         ClientSessionFactory sf = new ClientSessionFactoryImpl(new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory"));        
-         sf.getTransportParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, sslEnabled);
+         TransportConfiguration tc = new TransportConfiguration("org.jboss.messaging.integration.transports.netty.NettyConnectorFactory");
+         tc.getParams().put(TransportConstants.SSL_ENABLED_PROP_NAME, sslEnabled);
+         ClientSessionFactory sf = new ClientSessionFactoryImpl(tc);                 
          ClientSession session = sf.createSession(false, true, true);
          ClientProducer producer = session.createProducer(CoreClientOverSSLTest.QUEUE);
 




More information about the jboss-cvs-commits mailing list